pax_global_header00006660000000000000000000000064125262327600014517gustar00rootroot0000000000000052 comment=7051a3ae5ebc67461b0ace2d7090b598b2032621 pithos-1.1.1/000077500000000000000000000000001252623276000130255ustar00rootroot00000000000000pithos-1.1.1/.gitignore000066400000000000000000000003071252623276000150150ustar00rootroot00000000000000__pycache__/ *.py[cod] bin/ build/ develop-eggs/ dist/ eggs/ lib/ lib64/ parts/ sdist/ var/ *.egg-info/ .installed.cfg *.egg config/ *.patch debian/ build-debian.sh .project .pydevproject .settings/ pithos-1.1.1/MANIFEST.in000066400000000000000000000002401252623276000145570ustar00rootroot00000000000000include README.md recursive-include data *.svg pithos.desktop *.xml recursive-include pithos/data/ui *.ui *.xml recursive-include pithos/data/media *.png *.svg pithos-1.1.1/README.md000066400000000000000000000006261252623276000143100ustar00rootroot00000000000000Pithos ------ Pithos is a native Pandora Radio client for Linux. It's much more lightweight than the Pandora.com web client, and integrates with desktop features such as media keys, notifications, and the sound menu. For screenshots, install instructions and more, see [the Pithos home page](http://pithos.github.io). License: GNU GPLv3 Pithos is not affiliated with or endorsed by Pandora Media, Inc. pithos-1.1.1/data/000077500000000000000000000000001252623276000137365ustar00rootroot00000000000000pithos-1.1.1/data/icons/000077500000000000000000000000001252623276000150515ustar00rootroot00000000000000pithos-1.1.1/data/icons/hicolor/000077500000000000000000000000001252623276000165105ustar00rootroot00000000000000pithos-1.1.1/data/icons/hicolor/pithos-tray-icon.png000066400000000000000000000052541252623276000224350ustar00rootroot00000000000000PNG  IHDR00WbKGD pHYs B(xtIME`Q 9IDATh{\W}?qgvvfvc7~l؄@d QU ?"Q ^Ti `i*HP@mD:^k>9c֨RMJGwF:~kk Hl;A,8brVG-+e2CS_GF?omCf90+̗>3zq#S''etTg{ӏC: L+"K5nҤ/P8~W~x+],UVW_6{!RJ,K+ 8ӇeɤH iZ^@bRGI&I-%B n|9A8^ TC!I&n7F lF ME4=  阤 ŹZ7)|B(MF8qt'֦埾mk_oޑJ"Npę55Zj-ګCCp,2C* dۖ,Tˋ7niZ)aHT_M=ۓHCFJjB&Bh !0 2I&mܴr\5!a B?'AQ2;n4)F#ЍVZN [ )dPBuyW~=b&mdڟ xGc ~LwC}[:s Z$h)BҴ='jX^9Z-'a#zX:ßp'+k$S6Ch;U*;DfRC7S;E(5BH~/_p c Zڠ|ѷO}Vm*aTeؘ wn C)BBN05d!A#_]x瀹W}n X(KcZ&k̓SIIAti q#{^P Lˡkm&1^KKgE1A|WaW/o<4 44jƱM|3A;⊬M B1HEj%|~qdǔB LM5xW/Y?5~]Nc& 97ɥKFU'SI*o L6,ۤ)o~U?,VEl'H;6BKj,ԕ&Rۅ< W@źRtZa#Tܮql;w_xsaX} ɉy}9D-]L #5BEM_Icv̍ ~mm>>=lMaHNsz1F:ȳˑ".N>IƧw-OMϗ^5!?I*+-Ը c~8YBSQuJytkwa;1~!d_)߻-W/7v& KM 478Hb2F Qs[bg6*d\ZF}khfveMveRBiFc&tL¶*ٙ<̏U9Ͽ[o+f05{i 73مyY'4{ώɄ.tSZmJ+F&M?| image/svg+xml pithos-1.1.1/data/icons/hicolor/pithos.svg000066400000000000000000001035771252623276000205540ustar00rootroot00000000000000 image/svg+xml pithos-1.1.1/data/icons/ubuntu-mono-dark/000077500000000000000000000000001252623276000202605ustar00rootroot00000000000000pithos-1.1.1/data/icons/ubuntu-mono-dark/pithos-tray-icon.svg000066400000000000000000000053311252623276000242140ustar00rootroot00000000000000 image/svg+xml pithos-1.1.1/data/icons/ubuntu-mono-light/000077500000000000000000000000001252623276000204465ustar00rootroot00000000000000pithos-1.1.1/data/icons/ubuntu-mono-light/pithos-tray-icon.svg000066400000000000000000000050571252623276000244070ustar00rootroot00000000000000 image/svg+xml pithos-1.1.1/data/pithos.appdata.xml000066400000000000000000000014771252623276000174100ustar00rootroot00000000000000 pithos.desktop CC0 GPL-3.0+

Pithos is a easy to use native Pandora Radio client that is more lightweight than the pandora.com web client and integrates with the desktop.

It supports most functionality of pandora.com such as rating songs, creating/managing stations, quickmix, etc. On top of that it has features such as last.fm scrobbling, media keys, notifications, proxies, and mpris support.

https://pithos.github.io https://i.imgur.com/1vl3Dsk.png tingping_at_fedoraproject.org
pithos-1.1.1/data/pithos.desktop000066400000000000000000000002361252623276000166400ustar00rootroot00000000000000[Desktop Entry] Name=Pithos Comment=Play music from Pandora Radio Categories=GNOME;AudioVideo;Player; Exec=pithos Icon=pithos Terminal=false Type=Application pithos-1.1.1/debug.py000077500000000000000000000011531252623276000144700ustar00rootroot00000000000000#!/usr/bin/env python3 import os import sys # None of this works on Windows atm if sys.platform != 'win32': # Store config locally config_dir = os.path.abspath('./config') os.environ['XDG_CONFIG_HOME'] = config_dir # Migrate old debug_config old_config_dir = os.path.abspath('./debug_config') if os.path.exists(old_config_dir): os.rename(old_config_dir, config_dir) if not os.path.exists(config_dir): os.makedirs(config_dir) # Enable verbose logging and test mode if len(sys.argv) == 1: sys.argv.append('-tvv') from pithos import pithos pithos.main() pithos-1.1.1/docs/000077500000000000000000000000001252623276000137555ustar00rootroot00000000000000pithos-1.1.1/docs/conf.py000066400000000000000000000164471252623276000152700ustar00rootroot00000000000000#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Pithos documentation build configuration file, created by # sphinx-quickstart on Mon Sep 15 20:13:58 2014. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = 'Pithos' copyright = '2014, Kevin Mehall' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'Pithosdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'Pithos.tex', 'Pithos Documentation', 'Kevin Mehall', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'pithos', 'Pithos Documentation', ['Kevin Mehall'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'Pithos', 'Pithos Documentation', 'Kevin Mehall', 'Pithos', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' pithos-1.1.1/docs/index.rst000066400000000000000000000013671252623276000156250ustar00rootroot00000000000000.. Pithos documentation master file, created by sphinx-quickstart on Mon Sep 15 20:13:58 2014. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Welcome to Pithos's documentation! ================================== Pandora ------- .. autoclass:: pithos.pandora.Pandora :members: :undoc-members: .. autoclass:: pithos.pandora.Station :members: :undoc-members: .. autoclass:: pithos.pandora.Song :members: :undoc-members: .. autoclass:: pithos.pandora.SearchResult :members: :undoc-members: .. autoclass:: pithos.pandora.PandoraError :members: :undoc-members: Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` pithos-1.1.1/license000066400000000000000000001045061252623276000144000ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. {one line to give the program's name and a brief idea of what it does.} Copyright (C) {year} {name of author} This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: {project} Copyright (C) {year} {fullname} This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . pithos-1.1.1/pithos/000077500000000000000000000000001252623276000143335ustar00rootroot00000000000000pithos-1.1.1/pithos/AboutPithosDialog.py000066400000000000000000000050311252623276000202650ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- ### BEGIN LICENSE # Copyright (C) 2010-2012 Kevin Mehall #This program is free software: you can redistribute it and/or modify it #under the terms of the GNU General Public License version 3, as published #by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, but #WITHOUT ANY WARRANTY; without even the implied warranties of #MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR #PURPOSE. See the GNU General Public License for more details. # #You should have received a copy of the GNU General Public License along #with this program. If not, see . ### END LICENSE from gi.repository import Gtk, GdkPixbuf from .pithosconfig import get_ui_file, get_media_file from .util import open_browser class AboutPithosDialog(Gtk.AboutDialog): __gtype_name__ = "AboutPithosDialog" def __init__(self): """__init__ - This function is typically not called directly. Creation of a AboutPithosDialog requires redeading the associated ui file and parsing the ui definition extrenally, and then calling AboutPithosDialog.finish_initializing(). Use the convenience function NewAboutPithosDialog to create NewAboutPithosDialog objects. """ pass def finish_initializing(self, builder): """finish_initalizing should be called after parsing the ui definition and creating a AboutPithosDialog object with it in order to finish initializing the start of the new AboutPithosDialog instance. """ #get a reference to the builder and set up the signals self.builder = builder self.builder.connect_signals(self) self.set_logo(GdkPixbuf.Pixbuf.new_from_file_at_scale(get_media_file('icon'), -1, 96, True)) #code for other initialization actions should be added here def activate_link_cb(self, wid, uri): open_browser(uri) return True def NewAboutPithosDialog(): """NewAboutPithosDialog - returns a fully instantiated AboutPithosDialog object. Use this function rather than creating a AboutPithosDialog instance directly. """ builder = Gtk.Builder() builder.add_from_file(get_ui_file('about')) dialog = builder.get_object("about_pithos_dialog") dialog.finish_initializing(builder) return dialog if __name__ == "__main__": dialog = NewAboutPithosDialog() dialog.show() Gtk.main() pithos-1.1.1/pithos/PreferencesPithosDialog.py000066400000000000000000000315701252623276000214630ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- ### BEGIN LICENSE # Copyright (C) 2010 Kevin Mehall #This program is free software: you can redistribute it and/or modify it #under the terms of the GNU General Public License version 3, as published #by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, but #WITHOUT ANY WARRANTY; without even the implied warranties of #MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR #PURPOSE. See the GNU General Public License for more details. # #You should have received a copy of the GNU General Public License along #with this program. If not, see . ### END LICENSE import sys import os import stat import logging from gi.repository import Gtk, GObject, GLib, Pango from .pithosconfig import get_ui_file from .pandora.data import * pacparser_imported = False try: import pacparser pacparser_imported = True except ImportError: logging.info("Could not import python-pacparser.") config_home = GLib.get_user_config_dir() configfilename = os.path.join(config_home, 'pithos.ini') class PithosPluginRow(Gtk.ListBoxRow): def __init__(self, plugin, enabled): Gtk.ListBoxRow.__init__(self) self.plugin = plugin box = Gtk.Box() label = Gtk.Label() label.set_markup('{}\n{}'.format(plugin.name.title().replace('_', ' '), plugin.description)) label.set_halign(Gtk.Align.START) label.set_ellipsize(Pango.EllipsizeMode.END) label.set_max_width_chars(30) label.set_line_wrap(True) label.set_lines(1) box.pack_start(label, True, True, 4) self.switch = Gtk.Switch() self.switch.set_active(enabled) self.switch.connect('notify::active', self.on_activated) self.switch.set_valign(Gtk.Align.CENTER) box.pack_end(self.switch, False, False, 2) if plugin.prepared and plugin.error: self.set_sensitive(False) self.set_tooltip_text(plugin.error) self.add(box) def on_activated(self, obj, params): if not self.is_selected(): self.get_parent().select_row(self) if self.switch.get_active(): self.plugin.enable() else: self.plugin.disable() if self.plugin.prepared and self.plugin.error: self.get_parent().unselect_row(self) self.set_sensitive(False) self.set_tooltip_text(self.plugin.error) elif self.plugin.prepared: self.get_toplevel().preference_btn.set_sensitive(self.plugin.preferences_dialog != None) class PreferencesPithosDialog(Gtk.Dialog): __gtype_name__ = "PreferencesPithosDialog" prefernces = {} def __init__(self): """__init__ - This function is typically not called directly. Creation of a PreferencesPithosDialog requires reading the associated ui file and parsing the ui definition extrenally, and then calling PreferencesPithosDialog.finish_initializing(). Use the convenience function NewPreferencesPithosDialog to create NewAboutPithosDialog objects. """ pass def finish_initializing(self, builder): """finish_initalizing should be called after parsing the ui definition and creating a AboutPithosDialog object with it in order to finish initializing the start of the new AboutPithosDialog instance. """ # get a reference to the builder and set up the signals self.builder = builder self.builder.connect_signals(self) self.preference_btn = self.builder.get_object('prefs_btn') self.listbox = self.builder.get_object('plugins_listbox') # initialize the "Audio Quality" combobox backing list audio_quality_combo = self.builder.get_object('prefs_audio_quality') fmt_store = Gtk.ListStore(GObject.TYPE_STRING, GObject.TYPE_STRING) for audio_quality in valid_audio_formats: fmt_store.append(audio_quality) audio_quality_combo.set_model(fmt_store) render_text = Gtk.CellRendererText() audio_quality_combo.pack_start(render_text, True) audio_quality_combo.add_attribute(render_text, "text", 1) self.__load_preferences() def set_plugins(self, plugins): if len(self.listbox.set_header_func.get_arguments()) == 3: # pygobject3 3.10 self.listbox.set_header_func(self.on_listbox_update_header, None) else: # pygobject3 3.12+ self.listbox.set_header_func(self.on_listbox_update_header) for plugin in plugins.values(): row = PithosPluginRow(plugin, self.__preferences[plugin.preference]) self.listbox.add(row) self.listbox.show_all() def get_preferences(self): """get_preferences - returns a dictionary object that contains preferences for pithos. """ return self.__preferences def on_plugins_row_selected(self, box, row): if row: self.preference_btn.set_sensitive(row.plugin.preferences_dialog != None) def on_prefs_btn_clicked(self, btn): dialog = self.listbox.get_selected_rows()[0].plugin.preferences_dialog dialog.set_transient_for(self) dialog.set_destroy_with_parent(True) dialog.set_modal(True) dialog.show_all() def on_listbox_update_header(self, row, before, junk = None): if before and not row.get_header(): row.set_header(Gtk.Separator.new(Gtk.Orientation.HORIZONTAL)) def __load_preferences(self): #default preferences that will be overwritten if some are saved self.__preferences = { "username":'', "password":'', "x_pos": None, "y_pos": None, "notify":True, "last_station_id":None, "proxy":'', "control_proxy":'', "control_proxy_pac":'', "show_icon": False, "lastfm_key": False, "enable_mediakeys":True, "enable_screensaverpause":False, "enable_lastfm":False, "enable_mpris":True, "volume": 1.0, # If set, allow insecure permissions. Implements CVE-2011-1500 "unsafe_permissions": False, "audio_quality": default_audio_quality, "pandora_one": False, "force_client": None, } try: f = open(configfilename) except IOError: f = [] for line in f: sep = line.find('=') key = line[:sep] val = line[sep+1:].strip() if val == 'None': val=None elif val == 'False': val=False elif val == 'True': val=True self.__preferences[key]=val if 'audio_format' in self.__preferences: # Pithos <= 0.3.17, replaced by audio_quality del self.__preferences['audio_format'] if not pacparser_imported and self.__preferences['control_proxy_pac'] != '': self.__preferences['control_proxy_pac'] = '' self.setup_fields() def fix_perms(self): """Apply new file permission rules, fixing CVE-2011-1500. If the file is 0644 and if "unsafe_permissions" is not True, chmod 0600 If the file is world-readable (but not exactly 0644) and if "unsafe_permissions" is not True: chmod o-rw """ def complain_unsafe(): # Display this message iff permissions are unsafe, which is why # we don't just check once and be done with it. logging.warning("Ignoring potentially unsafe permissions due to user override.") changed = False if os.path.exists(configfilename): # We've already written the file, get current permissions config_perms = stat.S_IMODE(os.stat(configfilename).st_mode) if config_perms == (stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH): if self.__preferences["unsafe_permissions"]: return complain_unsafe() # File is 0644, set to 0600 logging.warning("Removing world- and group-readable permissions, to fix CVE-2011-1500 in older software versions. To force, set unsafe_permissions to True in pithos.ini.") os.chmod(configfilename, stat.S_IRUSR | stat.S_IWUSR) changed = True elif config_perms & stat.S_IROTH: if self.__preferences["unsafe_permissions"]: return complain_unsafe() # File is o+r, logging.warning("Removing world-readable permissions, configuration should not be globally readable. To force, set unsafe_permissions to True in pithos.ini.") config_perms ^= stat.S_IROTH os.chmod(configfilename, config_perms) changed = True if config_perms & stat.S_IWOTH: if self.__preferences["unsafe_permissions"]: return complain_unsafe() logging.warning("Removing world-writable permissions, configuration should not be globally writable. To force, set unsafe_permissions to True in pithos.ini.") config_perms ^= stat.S_IWOTH os.chmod(configfilename, config_perms) changed = True return changed def save(self): existed = os.path.exists(configfilename) f = open(configfilename, 'w') if not existed: # make the file owner-readable and writable only os.fchmod(f.fileno(), (stat.S_IRUSR | stat.S_IWUSR)) for key in self.__preferences: f.write('%s=%s\n'%(key, self.__preferences[key])) f.close() def setup_fields(self): self.builder.get_object('prefs_username').set_text(self.__preferences["username"]) self.builder.get_object('prefs_password').set_text(self.__preferences["password"]) self.builder.get_object('checkbutton_pandora_one').set_active(self.__preferences["pandora_one"]) self.builder.get_object('prefs_proxy').set_text(self.__preferences["proxy"]) self.builder.get_object('prefs_control_proxy').set_text(self.__preferences["control_proxy"]) self.builder.get_object('prefs_control_proxy_pac').set_text(self.__preferences["control_proxy_pac"]) if not pacparser_imported: self.builder.get_object('prefs_control_proxy_pac').set_sensitive(False) self.builder.get_object('prefs_control_proxy_pac').set_tooltip_text("Please install python-pacparser") audio_quality_combo = self.builder.get_object('prefs_audio_quality') for row in audio_quality_combo.get_model(): if row[0] == self.__preferences["audio_quality"]: audio_quality_combo.set_active_iter(row.iter) break for row in self.listbox.get_children(): row.switch.set_active(self.__preferences[row.plugin.preference]) def ok(self, widget, data=None): """ok - The user has elected to save the changes. Called before the dialog returns Gtk.RESONSE_OK from run(). """ self.__preferences["username"] = self.builder.get_object('prefs_username').get_text() self.__preferences["password"] = self.builder.get_object('prefs_password').get_text() self.__preferences["pandora_one"] = self.builder.get_object('checkbutton_pandora_one').get_active() self.__preferences["proxy"] = self.builder.get_object('prefs_proxy').get_text() self.__preferences["control_proxy"] = self.builder.get_object('prefs_control_proxy').get_text() self.__preferences["control_proxy_pac"] = self.builder.get_object('prefs_control_proxy_pac').get_text() audio_quality = self.builder.get_object('prefs_audio_quality') active_idx = audio_quality.get_active() if active_idx != -1: # ignore unknown format self.__preferences["audio_quality"] = audio_quality.get_model()[active_idx][0] for row in self.listbox.get_children(): self.__preferences[row.plugin.preference] = row.switch.get_active() self.save() def cancel(self, widget, data=None): """cancel - The user has elected cancel changes. Called before the dialog returns Gtk.ResponseType.CANCEL for run() """ self.setup_fields() # restore fields to previous values pass def NewPreferencesPithosDialog(): """NewPreferencesPithosDialog - returns a fully instantiated PreferencesPithosDialog object. Use this function rather than creating a PreferencesPithosDialog instance directly. """ builder = Gtk.Builder() builder.add_from_file(get_ui_file('preferences')) dialog = builder.get_object("preferences_pithos_dialog") dialog.finish_initializing(builder) return dialog if __name__ == "__main__": dialog = NewPreferencesPithosDialog() dialog.show() Gtk.main() pithos-1.1.1/pithos/SearchDialog.py000066400000000000000000000077171252623276000172460ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- ### BEGIN LICENSE # Copyright (C) 2010-2012 Kevin Mehall #This program is free software: you can redistribute it and/or modify it #under the terms of the GNU General Public License version 3, as published #by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, but #WITHOUT ANY WARRANTY; without even the implied warranties of #MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR #PURPOSE. See the GNU General Public License for more details. # #You should have received a copy of the GNU General Public License along #with this program. If not, see . ### END LICENSE import sys import os import html from gi.repository import Gtk from gi.repository import GObject from .pithosconfig import get_ui_file class SearchDialog(Gtk.Dialog): __gtype_name__ = "SearchDialog" def __init__(self): """__init__ - This function is typically not called directly. Creation of a SearchDialog requires redeading the associated ui file and parsing the ui definition extrenally, and then calling SearchDialog.finish_initializing(). Use the convenience function NewSearchDialog to create a SearchDialog object. """ pass def finish_initializing(self, builder, worker_run): """finish_initalizing should be called after parsing the ui definition and creating a SearchDialog object with it in order to finish initializing the start of the new SearchDialog instance. """ #get a reference to the builder and set up the signals self.builder = builder self.builder.connect_signals(self) self.entry = self.builder.get_object('entry') self.treeview = self.builder.get_object('treeview') self.okbtn = self.builder.get_object('okbtn') self.model = Gtk.ListStore(GObject.TYPE_PYOBJECT, str) self.treeview.set_model(self.model) self.worker_run = worker_run self.result = None def ok(self, widget, data=None): """ok - The user has elected to save the changes. Called before the dialog returns Gtk.RESONSE_OK from run(). """ def cancel(self, widget, data=None): """cancel - The user has elected cancel changes. Called before the dialog returns Gtk.ResponseType.CANCEL for run() """ pass def search_clicked(self, widget): self.search(self.entry.get_text()) def search(self, query): if not query: return def callback(results): self.model.clear() for i in results: if i.resultType is 'song': mk = "%s by %s"%(html.escape(i.title), html.escape(i.artist)) elif i.resultType is 'artist': mk = "%s (artist)"%(html.escape(i.name)) self.model.append((i, mk)) self.treeview.show() self.worker_run('search', (query,), callback, "Searching...") def get_selected(self): sel = self.treeview.get_selection().get_selected() if sel[1]: return self.treeview.get_model().get_value(sel[1], 0) def cursor_changed(self, *ignore): self.result = self.get_selected() self.okbtn.set_sensitive(not not self.result) def NewSearchDialog(worker_run): """NewSearchDialog - returns a fully instantiated dialog-camel_case_nameDialog object. Use this function rather than creating SearchDialog instance directly. """ builder = Gtk.Builder() builder.add_from_file(get_ui_file('search')) dialog = builder.get_object("search_dialog") dialog.finish_initializing(builder, worker_run) return dialog if __name__ == "__main__": dialog = NewSearchDialog() dialog.show() Gtk.main() pithos-1.1.1/pithos/StationsDialog.py000066400000000000000000000203411252623276000176310ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- ### BEGIN LICENSE # Copyright (C) 2010-2012 Kevin Mehall #This program is free software: you can redistribute it and/or modify it #under the terms of the GNU General Public License version 3, as published #by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, but #WITHOUT ANY WARRANTY; without even the implied warranties of #MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR #PURPOSE. See the GNU General Public License for more details. # #You should have received a copy of the GNU General Public License along #with this program. If not, see . ### END LICENSE import sys import os from gi.repository import Gtk import logging from .pithosconfig import get_ui_file from .util import open_browser from . import SearchDialog class StationsDialog(Gtk.Dialog): __gtype_name__ = "StationsDialog" def __init__(self): """__init__ - This function is typically not called directly. Creation of a StationsDialog requires redeading the associated ui file and parsing the ui definition extrenally, and then calling StationsDialog.finish_initializing(). Use the convenience function NewStationsDialog to create a StationsDialog object. """ pass def finish_initializing(self, builder, pithos): """finish_initalizing should be called after parsing the ui definition and creating a StationsDialog object with it in order to finish initializing the start of the new StationsDialog instance. """ #get a reference to the builder and set up the signals self.builder = builder self.builder.connect_signals(self) self.pithos = pithos self.model = pithos.stations_model self.worker_run = pithos.worker_run self.quickmix_changed = False self.searchDialog = None self.modelfilter = self.model.filter_new() self.modelfilter.set_visible_func(lambda m, i, d: m.get_value(i, 0) and not m.get_value(i, 0).isQuickMix) self.modelsortable = Gtk.TreeModelSort.sort_new_with_model(self.modelfilter) """ @todo Leaving it as sorting by date added by default. Probably should make a radio select in the window or an option in program options for user preference """ # self.modelsortable.set_sort_column_id(1, Gtk.SortType.ASCENDING) self.treeview = self.builder.get_object("treeview") self.treeview.set_model(self.modelsortable) self.treeview.connect('button_press_event', self.on_treeview_button_press_event) name_col = Gtk.TreeViewColumn() name_col.set_title("Name") render_text = Gtk.CellRendererText() render_text.set_property('editable', True) render_text.connect("edited", self.station_renamed) name_col.pack_start(render_text, True) name_col.add_attribute(render_text, "text", 1) name_col.set_expand(True) name_col.set_sort_column_id(1) self.treeview.append_column(name_col) qm_col = Gtk.TreeViewColumn() qm_col.set_title("In QuickMix") render_toggle = Gtk.CellRendererToggle() qm_col.pack_start(render_toggle, True) def qm_datafunc(column, cell, model, iter, data=None): if model.get_value(iter,0).useQuickMix: cell.set_active(True) else: cell.set_active(False) qm_col.set_cell_data_func(render_toggle, qm_datafunc) render_toggle.connect("toggled", self.qm_toggled) self.treeview.append_column(qm_col) self.station_menu = builder.get_object("station_menu") def qm_toggled(self, renderer, path): station = self.modelfilter[path][0] station.useQuickMix = not station.useQuickMix self.quickmix_changed = True def station_renamed(self, cellrenderertext, path, new_text): station = self.modelfilter[path][0] self.worker_run(station.rename, (new_text,), context='net', message="Renaming Station...") self.model[self.modelfilter.convert_path_to_child_path(Gtk.TreePath(path))][1] = new_text def selected_station(self): sel = self.treeview.get_selection().get_selected() if sel: return self.treeview.get_model().get_value(sel[1], 0) def on_treeview_button_press_event(self, treeview, event): if event.button == 3: x = int(event.x) y = int(event.y) time = event.time pthinfo = treeview.get_path_at_pos(x, y) if pthinfo is not None: path, col, cellx, celly = pthinfo treeview.grab_focus() treeview.set_cursor( path, col, 0) self.station_menu.popup(None, None, None, None, event.button, time) return True def on_menuitem_listen(self, widget): station = self.selected_station() self.pithos.station_changed(station) self.hide() def on_menuitem_info(self, widget): open_browser(self.selected_station().info_url) def on_menuitem_rename(self, widget): sel = self.treeview.get_selection().get_selected() path = self.treeview.get_model().get_path(sel[1]) self.treeview.set_cursor(path, self.treeview.get_column(0) ,True) def on_menuitem_delete(self, widget): station = self.selected_station() dialog = self.builder.get_object("delete_confirm_dialog") dialog.set_property("text", "Are you sure you want to delete the station \"%s\"?"%(station.name)) response = dialog.run() dialog.hide() if response: self.worker_run(station.delete, context='net', message="Deleting Station...") del self.pithos.stations_model[self.pithos.station_index(station)] if self.pithos.current_station is station: self.pithos.station_changed(self.model[0][0]) def add_station(self, widget): if self.searchDialog: self.searchDialog.present() else: self.searchDialog = SearchDialog.NewSearchDialog(self.worker_run) self.searchDialog.set_transient_for(self) self.searchDialog.show_all() self.searchDialog.connect("response", self.add_station_cb) def refresh_stations(self, widget): self.pithos.refresh_stations(self.pithos) def add_station_cb(self, dialog, response): logging.info("in add_station_cb {} {}".format(dialog.result, response)) if response == 1: self.worker_run("add_station_by_music_id", (dialog.result.musicId,), self.station_added, "Creating station...") dialog.hide() dialog.destroy() self.searchDialog = None def station_added(self, station): logging.debug("1 "+ repr(station)) it = self.model.insert_after(self.model.get_iter(1), (station, station.name)) logging.debug("2 "+ repr(it)) self.pithos.station_changed(station) logging.debug("3 ") self.modelfilter.refilter() logging.debug("4") self.treeview.set_cursor(0) logging.debug("5 ") def add_genre_station(self, widget): """ This is just a stub for the non-completed buttn """ def on_close(self, widget, data=None): self.hide() if self.quickmix_changed: self.worker_run("save_quick_mix", message="Saving QuickMix...") self.quickmix_changed = False logging.info("closed dialog") return True def NewStationsDialog(pithos): """NewStationsDialog - returns a fully instantiated Dialog object. Use this function rather than creating StationsDialog instance directly. """ builder = Gtk.Builder() builder.add_from_file(get_ui_file('stations')) dialog = builder.get_object("stations_dialog") dialog.finish_initializing(builder, pithos) return dialog if __name__ == "__main__": dialog = NewStationsDialog() dialog.show() Gtk.main() pithos-1.1.1/pithos/__init__.py000066400000000000000000000000001252623276000164320ustar00rootroot00000000000000pithos-1.1.1/pithos/__main__.py000066400000000000000000000000471252623276000164260ustar00rootroot00000000000000from pithos.pithos import main main() pithos-1.1.1/pithos/data/000077500000000000000000000000001252623276000152445ustar00rootroot00000000000000pithos-1.1.1/pithos/data/media/000077500000000000000000000000001252623276000163235ustar00rootroot00000000000000pithos-1.1.1/pithos/data/media/album_default.png000066400000000000000000000100151252623276000216320ustar00rootroot00000000000000PNG  IHDRsBIT|d pHYs B(xtEXtSoftwarewww.inkscape.org<IDATx]Y=x{Z4q } Hh՗~z _^@w\C@YBe k(8P*F(4r r r  (Ph(E(BC]CE(4TPPPh:B@YBC5ԋ)zUbBC  uPPw  \h(PPPh`BC \h`  *X,4TPP1P\C ꮡPbBC)B@Xh(PPBC 55ԋ)zUbBC5O/Ui/W]CiB}r2E OBA ̳l3MͦpWodY3Ea8Pmd#JpKs٦kJ2çb݂Wgac, Jr o^g,RY13ë14oC3:!><C\X[E+q=EHTN4p2iI1@BR : JQ(>yZf nvlgL " zI9>)gA כh8OS%dRH) /(+H2m/Z9vv{{s-KIȰM:0UJJWJb,Bҩ'^! tJd[1ɚ2OMG}K0 :ͻ+&ev !CY3c_{k.G.X#!lXBbpQӝW<]hHo CS ^M9kr }&p_S-*lz-y + )%}IwC?t:Ľ JEFWk!O^r~O#8+9r|oh= a{A9,^ ~JZt"X7g1;?dfii5\شY; 2IȞp B3QBql\njKt&!>QkhlHpJyA%E 1z.po9,,#j}VU5`09J1۾*h5hXR)Sd=̩fX+u \ailokLaP kk2qvS+KÃJ٩'~?$ҿ:%|^W1,@WV4ߪԸq+ s/{O:ҌF?MdBj(]>8eW3Å>,!*Ƙh^'Î s4o L;u9ƵL}'0 c-'q'=NP|F@8J&~9z?|ދBm819E~wE{)s ~- zVkPB`-ey+X Odz$UbQ@-&`eN:?, ]`Iw\~-B+麖p~%P$Kg= U`ro:§U8ۋ}%}Hm˝8j\U,"fCҷ &(xOPj+R:sE-_),>0c]17?s-Sۼ`YbNZQ:r35uOvw ?L?AuoC;Un7EQ!HKK^騩O%8pJ p7@Jvw@/ZfX#e9>(wʅCYl?U ?{h+a,ܻó_f#y gd¼*LmU~+y7I쉣ϑ @)?tȯ~&H2H)9t=dN\uCb~%x\4&&|Q@ԥ$1@*z4ʧCߺ7WVȎ& Jlp;TW ͘(uFa-y3m;yh(TEL<oS Rv[S~-܀I/BN]R>IRڸsg<Y"K!A7PW]>/ėɖʌbëoq+fU JqVR.XTd2\de~=VϓC+a 8;Dg3 uC%%3]L>@ybBM7B)HB/12v eC}vW\ _R^ܰ<ݭλsB7nEt-C,Unw9̌/T2d<TK5[tGtt<"ͥJH/^ͧϻdo gcQ=Z7GhQ5ן^ 5?+6)V#cicWVq$:4a|?Ny|'TԠcXG sphLfL5U!lEkKpR䁷we ߅NOL8Zzqvs_sq=N Q_ [?ny6j.W( c`QKDHV&a,sBٟBmk~l`[VPz|#|Kps%w~wt;Y \v?ǁBAw >cٴ]cK|">=Eb image/svg+xml pithos-1.1.1/pithos/data/media/icon.svg000066400000000000000000001035771252623276000200110ustar00rootroot00000000000000 image/svg+xml pithos-1.1.1/pithos/data/media/pithos-tray-icon.png000066400000000000000000000052541252623276000222500ustar00rootroot00000000000000PNG  IHDR00WbKGD pHYs B(xtIME`Q 9IDATh{\W}?qgvvfvc7~l؄@d QU ?"Q ^Ti `i*HP@mD:^k>9c֨RMJGwF:~kk Hl;A,8brVG-+e2CS_GF?omCf90+̗>3zq#S''etTg{ӏC: L+"K5nҤ/P8~W~x+],UVW_6{!RJ,K+ 8ӇeɤH iZ^@bRGI&I-%B n|9A8^ TC!I&n7F lF ME4=  阤 ŹZ7)|B(MF8qt'֦埾mk_oޑJ"Npę55Zj-ګCCp,2C* dۖ,Tˋ7niZ)aHT_M=ۓHCFJjB&Bh !0 2I&mܴr\5!a B?'AQ2;n4)F#ЍVZN [ )dPBuyW~=b&mdڟ xGc ~LwC}[:s Z$h)BҴ='jX^9Z-'a#zX:ßp'+k$S6Ch;U*;DfRC7S;E(5BH~/_p c Zڠ|ѷO}Vm*aTeؘ wn C)BBN05d!A#_]x瀹W}n X(KcZ&k̓SIIAti q#{^P Lˡkm&1^KKgE1A|WaW/o<4 44jƱM|3A;⊬M B1HEj%|~qdǔB LM5xW/Y?5~]Nc& 97ɥKFU'SI*o L6,ۤ)o~U?,VEl'H;6BKj,ԕ&Rۅ< W@źRtZa#Tܮql;w_xsaX} ɉy}9D-]L #5BEM_Icv̍ ~mm>>=lMaHNsz1F:ȳˑ".N>IƧw-OMϗ^5!?I*+-Ը c~8YBSQuJytkwa;1~!d_)߻-W/7v& KM 478Hb2F Qs[bg6*d\ZF}khfveMveRBiFc&tL¶*ٙ<̏U9Ͽ[o+f05{i 73مyY'4{ώɄ.tSZmJ+F&M?|rtEXtSoftwarewww.inkscape.org<IDATXr0l5W^0dc9X-ك85XF'IÞC^Vڂs  R t0nQ `ZsX$=%> ] ~~0e‡8 ]9^ z~  E+ qBw-N E @g$@??U`9{ ,3='#wZUp5d{g>oи40<0~6)t !bO0vYTjIP `%\ T`U] IZ `yA: 8CvVC39y\ DdHt%Ϧq(i OS h{oD>IU!{P=y˕ -T䫀8 afIᣤ+n$}?wks;#70Mu|^W,3I4 image/svg+xml pithos-1.1.1/pithos/data/ui/000077500000000000000000000000001252623276000156615ustar00rootroot00000000000000pithos-1.1.1/pithos/data/ui/AboutPithosDialog.ui000066400000000000000000000040171252623276000216030ustar00rootroot00000000000000 False 5 True ../media/icon.svg dialog Pithos 0.3 Copyright © 2012 Kevin Mehall A Pandora Radio client for the GNOME Desktop http://pithos.github.io Kevin Mehall Patrick Griffis Brad Pitcher Christopher Eby Steven Allen Greg Sheremeta Glenn Moss Jason Gray gpl-3-0 True False 2 True False end False True end 0 pithos-1.1.1/pithos/data/ui/PithosWindow.ui000066400000000000000000000617001252623276000206620ustar00rootroot00000000000000 100 1 10 10 False Pithos 500 360 pithos True False vertical True False False 2 True False True False True True False True True False media-playback-start-symbolic 2 False True 0 True False True True False media-skip-forward-symbolic 2 False True 1 True False True none False vertical audio-volume-muted-symbolic audio-volume-high-symbolic audio-volume-low-symbolic audio-volume-medium-symbolic True True center center none True True center center none False True 2 False False True False False True False True False True False True False True right True True False dialog-information-symbolic False True 0 120 True False False False True 1 False False False True 0 True False adjustment1 never True True adjustment1 False True True 1 True False 2 False True 2 False 5 True dialog pithos_window error Pithos Upgrade Required Pithos needs to be updated for compatibility with Pandora's latest changes. True True False vertical 2 True False end Get Help Online True False True False False 0 Quit True False True True False False 1 False True end 0 button4 button5 False 5 True dialog True pithos_window error Error True False 2 True False end Quit True False True True False False 0 False True end 1 button-error-quit False 5 True dialog pithos_window True False vertical 2 True False end False True end 0 False 5 True dialog pithos_window error Error True False 2 True False end Cancel True False True False False 0 Retry True False True False False 1 Preferences True False True True False False 2 False True end 1 button1 button2 button3 True False True False Song _Info... True True False _Love Song True True False _Unlove Song True True False _Ban Song True True False _Unban Song True True False Don't play song for a month _Tired of this song True True False Bookmark True False True False Song True False Artist pithos-1.1.1/pithos/data/ui/PreferencesPithosDialog.ui000066400000000000000000000532551252623276000230020ustar00rootroot00000000000000 333 False 5 Preferences False pithos dialog True False 2 True False end Cancel True False False False False 0 OK True False False False False 1 False True end 0 True True True False 12 18 True False True False start Account 0 0 True False 20 8 20 True False start center Email 0 0 True True True email 1 0 True False Password 0 1 True True False password 1 1 Pandora One Subscriber True True False start True 0 2 2 True True <small><a href='http://pandora.com'>Create an account at pandora.com</a></small> True 0 3 2 0 1 0 0 True False True False start Advanced Settings 0 0 True False 20 8 20 True True False start Audio Quality 0 0 True False 1 0 True False This proxy is used for all HTTP/HTTPS traffic. If empty, http_proxy and https_proxy environment variables will be used. start Proxy URL 0 1 True True url 1 1 True False Proxy for Pandora API requests only (for those outside the US). If unset, the normal proxy is used. start Control Proxy URL 0 2 True True url 1 2 True False Proxy auto-configuration URL. Used only if Control Proxy URL above is unset. start Control Proxy PAC 0 3 True True url 1 3 0 1 0 1 True False Pandora False True False vertical True True never in True False True False True True 0 True False True False False This plugin either must be enabled or does not support preferences. end Preferences True True True False True 1 1 True False Plugins 1 False False True 1 button_cancel button_ok pithos-1.1.1/pithos/data/ui/SearchDialog.ui000066400000000000000000000126271252623276000205550ustar00rootroot00000000000000 380 350 False 5 Search True pithos dialog True False 2 True False end Cancel True False True False False 0 OK True False False True False False 1 False True end 0 True False 4 True True False True 0 True False True False False column 1 True True 1 True True 1 button2 okbtn pithos-1.1.1/pithos/data/ui/StationsDialog.ui000066400000000000000000000233001252623276000211420ustar00rootroot00000000000000 True False True False Listen Now True True False Info True True False Rename True False Delete True 480 420 False 1 Manage Stations True pithos dialog True False vertical 2 True False end Add Station True False True False False 0 True Genre Stations False False True True False False 1 True Refresh Stations True False True False False 2 True Close True False True False False 3 False True end 0 True False True False True True 1 add_station add_genre_station refresh_stations close False 5 True dialog stations_dialog warning True False vertical 2 True False end Cancel True False True False False 0 Delete True False True False False 1 False True end 0 button2 button1 pithos-1.1.1/pithos/data/ui/about_pithos_dialog.xml000066400000000000000000000006131252623276000224220ustar00rootroot00000000000000 pithos-1.1.1/pithos/data/ui/app_menu.ui000066400000000000000000000017011252623276000200230ustar00rootroot00000000000000
app.stations _Stations <Primary>s app.preferences _Preferences <Primary>p
app.about _About app.quit _Quit <Primary>q
pithos-1.1.1/pithos/data/ui/pithos_window.xml000066400000000000000000000005511252623276000213010ustar00rootroot00000000000000 pithos-1.1.1/pithos/data/ui/preferences_pithos_dialog.xml000066400000000000000000000006271252623276000236160ustar00rootroot00000000000000 pithos-1.1.1/pithos/data/ui/search_dialog.xml000066400000000000000000000005621252623276000211720ustar00rootroot00000000000000 pithos-1.1.1/pithos/data/ui/stations_dialog.xml000066400000000000000000000005701252623276000215700ustar00rootroot00000000000000 pithos-1.1.1/pithos/gobject_worker.py000066400000000000000000000045501252623276000177170ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- ### BEGIN LICENSE # Copyright (C) 2010-2012 Kevin Mehall #This program is free software: you can redistribute it and/or modify it #under the terms of the GNU General Public License version 3, as published #by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, but #WITHOUT ANY WARRANTY; without even the implied warranties of #MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR #PURPOSE. See the GNU General Public License for more details. # #You should have received a copy of the GNU General Public License along #with this program. If not, see . ### END LICENSE import logging import threading import queue from gi.repository import GObject, GLib import traceback GObject.threads_init() class GObjectWorker(): def __init__(self): self.thread = threading.Thread(target=self._run) self.thread.daemon = True self.queue = queue.Queue() self.thread.start() def _run(self): while True: command, args, callback, errorback = self.queue.get() try: result = command(*args) if callback: GLib.idle_add(callback, result) except Exception as e: e.traceback = traceback.format_exc() if errorback: GLib.idle_add(errorback, e) def send(self, command, args=(), callback=None, errorback=None): if errorback is None: errorback = self._default_errorback self.queue.put((command, args, callback, errorback)) def _default_errorback(self, error): logging.error("Unhandled exception in worker thread:\n{}".format(error.traceback)) if __name__ == '__main__': worker = GObjectWorker() import time from gi.repository import Gtk def test_cmd(a, b): logging.info("running...") time.sleep(5) logging.info("done") return a*b def test_cb(result): logging.info("got result {}".format(result)) logging.info("sending") worker.send(test_cmd, (3,4), test_cb) worker.send(test_cmd, ((), ()), test_cb) #trigger exception in worker to test error handling Gtk.main() pithos-1.1.1/pithos/pandora/000077500000000000000000000000001252623276000157575ustar00rootroot00000000000000pithos-1.1.1/pithos/pandora/__init__.py000066400000000000000000000016461252623276000200770ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- ### BEGIN LICENSE # Copyright (C) 2010 Kevin Mehall #This program is free software: you can redistribute it and/or modify it #under the terms of the GNU General Public License version 3, as published #by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, but #WITHOUT ANY WARRANTY; without even the implied warranties of #MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR #PURPOSE. See the GNU General Public License for more details. # #You should have received a copy of the GNU General Public License along #with this program. If not, see . ### END LICENSE from .pandora import * def make_pandora(testing=False): if testing: from pithos.pandora.fake import FakePandora return FakePandora() else: return Pandora() pithos-1.1.1/pithos/pandora/blowfish.py000066400000000000000000000514241252623276000201540ustar00rootroot00000000000000# Copyright (C) 2011 Versile AS # # This file is part of Versile Python Open Source Edition. # # Versile Python Open Source Edition is free software: you can # redistribute it and/or modify it under the terms of the GNU Affero # General Public License as published by the Free Software Foundation, # either version 3 of the License, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public # License along with this program. If not, see # . # # Versile Python Open Source Edition implements Versile Platform which # is a copyrighted specification that is not part of this software. # Modification of the software is subject to Versile Platform licensing, # see https://versile.com/ for details. Distribution of unmodified versions # released by Versile AS is not subject to Versile Platform licensing. # """Implementation of the Blowfish cipher. This is an implementation of the `Blowfish `__ cipher, which is in the public domain. Stated on the web site: \"Everyone is welcome to download Blowfish and use it in their application. There are no rules about use, although I would appreciate being notified of any commercial applications using the product so that I can list them on this website.\" The implementation in this module is a python conversion and adaptation of Bruce Schneier's `C implementation `__\ . """ import copy class VCryptoException(Exception): """Exception for crypto operations.""" def __init__(self, *args): super(VCryptoException, self).__init__(*args) class Blowfish(object): """Blowfish cipher. When initialized the object can encrypt and decrypt blocks of data with the :meth:`encrypt` and :meth:`decrypt` methods. :param key: cipher key :type key: bytes Key length must be between 1 byte and 56 bytes (448 bits). """ def __init__(self, key): if not isinstance(key, bytes): raise VCryptoException('Key must be a bytes object') elif len(key) > 56: raise VCryptoException('Max key length is 448 bits (56 bytes)') P, S = copy.deepcopy(_P_INIT), copy.deepcopy(_S_INIT) self.__P, self.__S = P, S keylen = len(key) j = 0 for i in range(len(P)): data = 0 for k in range(4): data = ((data << 8) & 0xffffffff) | key[j] j += 1 if j >= keylen: j = 0 P[i] ^= data data = 8*b'\x00' for i in range(0, len(P), 2): data = self.encrypt(data) P[i] = ((data[0] << 24) + (data[1] << 16) + (data[2] << 8 ) + data[3]) P[i+1] = ((data[4] << 24) + (data[5] << 16) + (data[6] << 8 ) + data[7]) for i in range(4): for j in range(0, 256, 2): data = self.encrypt(data) S[i][j] = ((data[0] << 24) + (data[1] << 16) + (data[2] << 8 ) + data[3]) S[i][j+1] = ((data[4] << 24) + (data[5] << 16) + (data[6] << 8 ) + data[7]) def __feistel(self, x): S = self.__S d = x & 0xff x >>= 8 c = x & 0xff x >>= 8 b = x & 0xff x >>= 8 a = x & 0xff y = (S[0][a] + S[1][b]) & 0xffffffff y ^= S[2][c] y = (y + S[3][d]) & 0xffffffff return y def encrypt(self, data): """Encipher plaintext and return result. :param data: plaintext to encrypt (8 bytes) :type data: bytes :returns: encrypted data (8 bytes) :rtype: bytes The data must align with 8-byte blocksize. .. note:: Enciphering is performed without any kind of chaining, and the same plaintext will always return the same encrypted block of data. In order to use securely as a cipher, it is normally required that the cipher is combined with chaining techniques. """ len_data = len(data) if len_data % 8: raise VCryptoException('Data not aligned with 8-byte blocksize') if len_data == 8: return self._encrypt_block(data) else: result = [] start = 0 while start < len_data: end = start + 8 block = data[start:end] result.append(self._encrypt_block(block)) start += 8 return b''.join(result) def _encrypt_block(self, block): if not isinstance(block, bytes) or len(block) != 8: raise VCryptoException('Data block must be bytes of len 8') b_l = ((block[0] << 24) + (block[1] << 16) + (block[2] << 8 ) + block[3]) b_r = ((block[4] << 24) + (block[5] << 16) + (block[6] << 8 ) + block[7]) P, S = self.__P, self.__S for i in range(16): b_l ^= P[i] b_r ^= self.__feistel(b_l) b_l, b_r = b_r, b_l b_l, b_r = b_r, b_l b_r ^= P[16] b_l ^= P[17] bval = [(b_l >> 24), (b_l >> 16), (b_l >> 8), b_l, (b_r >> 24), (b_r >> 16), (b_r >> 8), b_r] return bytes([b & 0xff for b in bval]) def decrypt(self, data): """Decipher encrypted data and return decrypted plaintext. :param data: encrypted data (8 bytes) :type data: bytes :returns: decrypted plaintext (8 bytes) :rtype: bytes The block of encrypted data must be a multiple of 8 bytes. """ len_data = len(data) if len_data % 8: raise VCryptoException('Data not aligned with 8-byte blocksize') if len_data == 8: return self._decrypt_block(data) else: result = [] start = 0 while start < len_data: end = start + 8 block = data[start:end] result.append(self._decrypt_block(block)) start += 8 return b''.join(result) def _decrypt_block(self, block): if not isinstance(block, bytes) or len(block) != 8: raise VCryptoException('Data block must be bytes of len 8') b_l = ((block[0] << 24) + (block[1] << 16) + (block[2] << 8 ) + block[3]) b_r = ((block[4] << 24) + (block[5] << 16) + (block[6] << 8 ) + block[7]) P, S = self.__P, self.__S for i in range(17, 1, -1): b_l ^= P[i] b_r ^= self.__feistel(b_l) b_l, b_r = b_r, b_l b_l, b_r = b_r, b_l b_r ^= P[1] b_l ^= P[0] bval = [(b_l >> 24), (b_l >> 16), (b_l >> 8), b_l, (b_r >> 24), (b_r >> 16), (b_r >> 8), b_r] return bytes([b & 0xff for b in bval]) # These are the standard initialization valies of P and S blocks for the # cipher. The constants are internal to this module and should not be accessed # directly or modified by outside code. _P_INIT = [0x243f6a88,0x85a308d3,0x13198a2e,0x03707344,0xa4093822,0x299f31d0, 0x082efa98,0xec4e6c89,0x452821e6,0x38d01377,0xbe5466cf,0x34e90c6c, 0xc0ac29b7,0xc97c50dd,0x3f84d5b5,0xb5470917,0x9216d5d9,0x8979fb1b] _S_INIT = [[0xd1310ba6,0x98dfb5ac,0x2ffd72db,0xd01adfb7,0xb8e1afed,0x6a267e96, 0xba7c9045,0xf12c7f99,0x24a19947,0xb3916cf7,0x0801f2e2,0x858efc16, 0x636920d8,0x71574e69,0xa458fea3,0xf4933d7e,0x0d95748f,0x728eb658, 0x718bcd58,0x82154aee,0x7b54a41d,0xc25a59b5,0x9c30d539,0x2af26013, 0xc5d1b023,0x286085f0,0xca417918,0xb8db38ef,0x8e79dcb0,0x603a180e, 0x6c9e0e8b,0xb01e8a3e,0xd71577c1,0xbd314b27,0x78af2fda,0x55605c60, 0xe65525f3,0xaa55ab94,0x57489862,0x63e81440,0x55ca396a,0x2aab10b6, 0xb4cc5c34,0x1141e8ce,0xa15486af,0x7c72e993,0xb3ee1411,0x636fbc2a, 0x2ba9c55d,0x741831f6,0xce5c3e16,0x9b87931e,0xafd6ba33,0x6c24cf5c, 0x7a325381,0x28958677,0x3b8f4898,0x6b4bb9af,0xc4bfe81b,0x66282193, 0x61d809cc,0xfb21a991,0x487cac60,0x5dec8032,0xef845d5d,0xe98575b1, 0xdc262302,0xeb651b88,0x23893e81,0xd396acc5,0x0f6d6ff3,0x83f44239, 0x2e0b4482,0xa4842004,0x69c8f04a,0x9e1f9b5e,0x21c66842,0xf6e96c9a, 0x670c9c61,0xabd388f0,0x6a51a0d2,0xd8542f68,0x960fa728,0xab5133a3, 0x6eef0b6c,0x137a3be4,0xba3bf050,0x7efb2a98,0xa1f1651d,0x39af0176, 0x66ca593e,0x82430e88,0x8cee8619,0x456f9fb4,0x7d84a5c3,0x3b8b5ebe, 0xe06f75d8,0x85c12073,0x401a449f,0x56c16aa6,0x4ed3aa62,0x363f7706, 0x1bfedf72,0x429b023d,0x37d0d724,0xd00a1248,0xdb0fead3,0x49f1c09b, 0x075372c9,0x80991b7b,0x25d479d8,0xf6e8def7,0xe3fe501a,0xb6794c3b, 0x976ce0bd,0x04c006ba,0xc1a94fb6,0x409f60c4,0x5e5c9ec2,0x196a2463, 0x68fb6faf,0x3e6c53b5,0x1339b2eb,0x3b52ec6f,0x6dfc511f,0x9b30952c, 0xcc814544,0xaf5ebd09,0xbee3d004,0xde334afd,0x660f2807,0x192e4bb3, 0xc0cba857,0x45c8740f,0xd20b5f39,0xb9d3fbdb,0x5579c0bd,0x1a60320a, 0xd6a100c6,0x402c7279,0x679f25fe,0xfb1fa3cc,0x8ea5e9f8,0xdb3222f8, 0x3c7516df,0xfd616b15,0x2f501ec8,0xad0552ab,0x323db5fa,0xfd238760, 0x53317b48,0x3e00df82,0x9e5c57bb,0xca6f8ca0,0x1a87562e,0xdf1769db, 0xd542a8f6,0x287effc3,0xac6732c6,0x8c4f5573,0x695b27b0,0xbbca58c8, 0xe1ffa35d,0xb8f011a0,0x10fa3d98,0xfd2183b8,0x4afcb56c,0x2dd1d35b, 0x9a53e479,0xb6f84565,0xd28e49bc,0x4bfb9790,0xe1ddf2da,0xa4cb7e33, 0x62fb1341,0xcee4c6e8,0xef20cada,0x36774c01,0xd07e9efe,0x2bf11fb4, 0x95dbda4d,0xae909198,0xeaad8e71,0x6b93d5a0,0xd08ed1d0,0xafc725e0, 0x8e3c5b2f,0x8e7594b7,0x8ff6e2fb,0xf2122b64,0x8888b812,0x900df01c, 0x4fad5ea0,0x688fc31c,0xd1cff191,0xb3a8c1ad,0x2f2f2218,0xbe0e1777, 0xea752dfe,0x8b021fa1,0xe5a0cc0f,0xb56f74e8,0x18acf3d6,0xce89e299, 0xb4a84fe0,0xfd13e0b7,0x7cc43b81,0xd2ada8d9,0x165fa266,0x80957705, 0x93cc7314,0x211a1477,0xe6ad2065,0x77b5fa86,0xc75442f5,0xfb9d35cf, 0xebcdaf0c,0x7b3e89a0,0xd6411bd3,0xae1e7e49,0x00250e2d,0x2071b35e, 0x226800bb,0x57b8e0af,0x2464369b,0xf009b91e,0x5563911d,0x59dfa6aa, 0x78c14389,0xd95a537f,0x207d5ba2,0x02e5b9c5,0x83260376,0x6295cfa9, 0x11c81968,0x4e734a41,0xb3472dca,0x7b14a94a,0x1b510052,0x9a532915, 0xd60f573f,0xbc9bc6e4,0x2b60a476,0x81e67400,0x08ba6fb5,0x571be91f, 0xf296ec6b,0x2a0dd915,0xb6636521,0xe7b9f9b6,0xff34052e,0xc5855664, 0x53b02d5d,0xa99f8fa1,0x08ba4799,0x6e85076a], [0x4b7a70e9,0xb5b32944,0xdb75092e,0xc4192623,0xad6ea6b0,0x49a7df7d, 0x9cee60b8,0x8fedb266,0xecaa8c71,0x699a17ff,0x5664526c,0xc2b19ee1, 0x193602a5,0x75094c29,0xa0591340,0xe4183a3e,0x3f54989a,0x5b429d65, 0x6b8fe4d6,0x99f73fd6,0xa1d29c07,0xefe830f5,0x4d2d38e6,0xf0255dc1, 0x4cdd2086,0x8470eb26,0x6382e9c6,0x021ecc5e,0x09686b3f,0x3ebaefc9, 0x3c971814,0x6b6a70a1,0x687f3584,0x52a0e286,0xb79c5305,0xaa500737, 0x3e07841c,0x7fdeae5c,0x8e7d44ec,0x5716f2b8,0xb03ada37,0xf0500c0d, 0xf01c1f04,0x0200b3ff,0xae0cf51a,0x3cb574b2,0x25837a58,0xdc0921bd, 0xd19113f9,0x7ca92ff6,0x94324773,0x22f54701,0x3ae5e581,0x37c2dadc, 0xc8b57634,0x9af3dda7,0xa9446146,0x0fd0030e,0xecc8c73e,0xa4751e41, 0xe238cd99,0x3bea0e2f,0x3280bba1,0x183eb331,0x4e548b38,0x4f6db908, 0x6f420d03,0xf60a04bf,0x2cb81290,0x24977c79,0x5679b072,0xbcaf89af, 0xde9a771f,0xd9930810,0xb38bae12,0xdccf3f2e,0x5512721f,0x2e6b7124, 0x501adde6,0x9f84cd87,0x7a584718,0x7408da17,0xbc9f9abc,0xe94b7d8c, 0xec7aec3a,0xdb851dfa,0x63094366,0xc464c3d2,0xef1c1847,0x3215d908, 0xdd433b37,0x24c2ba16,0x12a14d43,0x2a65c451,0x50940002,0x133ae4dd, 0x71dff89e,0x10314e55,0x81ac77d6,0x5f11199b,0x043556f1,0xd7a3c76b, 0x3c11183b,0x5924a509,0xf28fe6ed,0x97f1fbfa,0x9ebabf2c,0x1e153c6e, 0x86e34570,0xeae96fb1,0x860e5e0a,0x5a3e2ab3,0x771fe71c,0x4e3d06fa, 0x2965dcb9,0x99e71d0f,0x803e89d6,0x5266c825,0x2e4cc978,0x9c10b36a, 0xc6150eba,0x94e2ea78,0xa5fc3c53,0x1e0a2df4,0xf2f74ea7,0x361d2b3d, 0x1939260f,0x19c27960,0x5223a708,0xf71312b6,0xebadfe6e,0xeac31f66, 0xe3bc4595,0xa67bc883,0xb17f37d1,0x018cff28,0xc332ddef,0xbe6c5aa5, 0x65582185,0x68ab9802,0xeecea50f,0xdb2f953b,0x2aef7dad,0x5b6e2f84, 0x1521b628,0x29076170,0xecdd4775,0x619f1510,0x13cca830,0xeb61bd96, 0x0334fe1e,0xaa0363cf,0xb5735c90,0x4c70a239,0xd59e9e0b,0xcbaade14, 0xeecc86bc,0x60622ca7,0x9cab5cab,0xb2f3846e,0x648b1eaf,0x19bdf0ca, 0xa02369b9,0x655abb50,0x40685a32,0x3c2ab4b3,0x319ee9d5,0xc021b8f7, 0x9b540b19,0x875fa099,0x95f7997e,0x623d7da8,0xf837889a,0x97e32d77, 0x11ed935f,0x16681281,0x0e358829,0xc7e61fd6,0x96dedfa1,0x7858ba99, 0x57f584a5,0x1b227263,0x9b83c3ff,0x1ac24696,0xcdb30aeb,0x532e3054, 0x8fd948e4,0x6dbc3128,0x58ebf2ef,0x34c6ffea,0xfe28ed61,0xee7c3c73, 0x5d4a14d9,0xe864b7e3,0x42105d14,0x203e13e0,0x45eee2b6,0xa3aaabea, 0xdb6c4f15,0xfacb4fd0,0xc742f442,0xef6abbb5,0x654f3b1d,0x41cd2105, 0xd81e799e,0x86854dc7,0xe44b476a,0x3d816250,0xcf62a1f2,0x5b8d2646, 0xfc8883a0,0xc1c7b6a3,0x7f1524c3,0x69cb7492,0x47848a0b,0x5692b285, 0x095bbf00,0xad19489d,0x1462b174,0x23820e00,0x58428d2a,0x0c55f5ea, 0x1dadf43e,0x233f7061,0x3372f092,0x8d937e41,0xd65fecf1,0x6c223bdb, 0x7cde3759,0xcbee7460,0x4085f2a7,0xce77326e,0xa6078084,0x19f8509e, 0xe8efd855,0x61d99735,0xa969a7aa,0xc50c06c2,0x5a04abfc,0x800bcadc, 0x9e447a2e,0xc3453484,0xfdd56705,0x0e1e9ec9,0xdb73dbd3,0x105588cd, 0x675fda79,0xe3674340,0xc5c43465,0x713e38d8,0x3d28f89e,0xf16dff20, 0x153e21e7,0x8fb03d4a,0xe6e39f2b,0xdb83adf7], [0xe93d5a68,0x948140f7,0xf64c261c,0x94692934,0x411520f7,0x7602d4f7, 0xbcf46b2e,0xd4a20068,0xd4082471,0x3320f46a,0x43b7d4b7,0x500061af, 0x1e39f62e,0x97244546,0x14214f74,0xbf8b8840,0x4d95fc1d,0x96b591af, 0x70f4ddd3,0x66a02f45,0xbfbc09ec,0x03bd9785,0x7fac6dd0,0x31cb8504, 0x96eb27b3,0x55fd3941,0xda2547e6,0xabca0a9a,0x28507825,0x530429f4, 0x0a2c86da,0xe9b66dfb,0x68dc1462,0xd7486900,0x680ec0a4,0x27a18dee, 0x4f3ffea2,0xe887ad8c,0xb58ce006,0x7af4d6b6,0xaace1e7c,0xd3375fec, 0xce78a399,0x406b2a42,0x20fe9e35,0xd9f385b9,0xee39d7ab,0x3b124e8b, 0x1dc9faf7,0x4b6d1856,0x26a36631,0xeae397b2,0x3a6efa74,0xdd5b4332, 0x6841e7f7,0xca7820fb,0xfb0af54e,0xd8feb397,0x454056ac,0xba489527, 0x55533a3a,0x20838d87,0xfe6ba9b7,0xd096954b,0x55a867bc,0xa1159a58, 0xcca92963,0x99e1db33,0xa62a4a56,0x3f3125f9,0x5ef47e1c,0x9029317c, 0xfdf8e802,0x04272f70,0x80bb155c,0x05282ce3,0x95c11548,0xe4c66d22, 0x48c1133f,0xc70f86dc,0x07f9c9ee,0x41041f0f,0x404779a4,0x5d886e17, 0x325f51eb,0xd59bc0d1,0xf2bcc18f,0x41113564,0x257b7834,0x602a9c60, 0xdff8e8a3,0x1f636c1b,0x0e12b4c2,0x02e1329e,0xaf664fd1,0xcad18115, 0x6b2395e0,0x333e92e1,0x3b240b62,0xeebeb922,0x85b2a20e,0xe6ba0d99, 0xde720c8c,0x2da2f728,0xd0127845,0x95b794fd,0x647d0862,0xe7ccf5f0, 0x5449a36f,0x877d48fa,0xc39dfd27,0xf33e8d1e,0x0a476341,0x992eff74, 0x3a6f6eab,0xf4f8fd37,0xa812dc60,0xa1ebddf8,0x991be14c,0xdb6e6b0d, 0xc67b5510,0x6d672c37,0x2765d43b,0xdcd0e804,0xf1290dc7,0xcc00ffa3, 0xb5390f92,0x690fed0b,0x667b9ffb,0xcedb7d9c,0xa091cf0b,0xd9155ea3, 0xbb132f88,0x515bad24,0x7b9479bf,0x763bd6eb,0x37392eb3,0xcc115979, 0x8026e297,0xf42e312d,0x6842ada7,0xc66a2b3b,0x12754ccc,0x782ef11c, 0x6a124237,0xb79251e7,0x06a1bbe6,0x4bfb6350,0x1a6b1018,0x11caedfa, 0x3d25bdd8,0xe2e1c3c9,0x44421659,0x0a121386,0xd90cec6e,0xd5abea2a, 0x64af674e,0xda86a85f,0xbebfe988,0x64e4c3fe,0x9dbc8057,0xf0f7c086, 0x60787bf8,0x6003604d,0xd1fd8346,0xf6381fb0,0x7745ae04,0xd736fccc, 0x83426b33,0xf01eab71,0xb0804187,0x3c005e5f,0x77a057be,0xbde8ae24, 0x55464299,0xbf582e61,0x4e58f48f,0xf2ddfda2,0xf474ef38,0x8789bdc2, 0x5366f9c3,0xc8b38e74,0xb475f255,0x46fcd9b9,0x7aeb2661,0x8b1ddf84, 0x846a0e79,0x915f95e2,0x466e598e,0x20b45770,0x8cd55591,0xc902de4c, 0xb90bace1,0xbb8205d0,0x11a86248,0x7574a99e,0xb77f19b6,0xe0a9dc09, 0x662d09a1,0xc4324633,0xe85a1f02,0x09f0be8c,0x4a99a025,0x1d6efe10, 0x1ab93d1d,0x0ba5a4df,0xa186f20f,0x2868f169,0xdcb7da83,0x573906fe, 0xa1e2ce9b,0x4fcd7f52,0x50115e01,0xa70683fa,0xa002b5c4,0x0de6d027, 0x9af88c27,0x773f8641,0xc3604c06,0x61a806b5,0xf0177a28,0xc0f586e0, 0x006058aa,0x30dc7d62,0x11e69ed7,0x2338ea63,0x53c2dd94,0xc2c21634, 0xbbcbee56,0x90bcb6de,0xebfc7da1,0xce591d76,0x6f05e409,0x4b7c0188, 0x39720a3d,0x7c927c24,0x86e3725f,0x724d9db9,0x1ac15bb4,0xd39eb8fc, 0xed545578,0x08fca5b5,0xd83d7cd3,0x4dad0fc4,0x1e50ef5e,0xb161e6f8, 0xa28514d9,0x6c51133c,0x6fd5c7e7,0x56e14ec4,0x362abfce,0xddc6c837, 0xd79a3234,0x92638212,0x670efa8e,0x406000e0], [0x3a39ce37,0xd3faf5cf,0xabc27737,0x5ac52d1b,0x5cb0679e,0x4fa33742, 0xd3822740,0x99bc9bbe,0xd5118e9d,0xbf0f7315,0xd62d1c7e,0xc700c47b, 0xb78c1b6b,0x21a19045,0xb26eb1be,0x6a366eb4,0x5748ab2f,0xbc946e79, 0xc6a376d2,0x6549c2c8,0x530ff8ee,0x468dde7d,0xd5730a1d,0x4cd04dc6, 0x2939bbdb,0xa9ba4650,0xac9526e8,0xbe5ee304,0xa1fad5f0,0x6a2d519a, 0x63ef8ce2,0x9a86ee22,0xc089c2b8,0x43242ef6,0xa51e03aa,0x9cf2d0a4, 0x83c061ba,0x9be96a4d,0x8fe51550,0xba645bd6,0x2826a2f9,0xa73a3ae1, 0x4ba99586,0xef5562e9,0xc72fefd3,0xf752f7da,0x3f046f69,0x77fa0a59, 0x80e4a915,0x87b08601,0x9b09e6ad,0x3b3ee593,0xe990fd5a,0x9e34d797, 0x2cf0b7d9,0x022b8b51,0x96d5ac3a,0x017da67d,0xd1cf3ed6,0x7c7d2d28, 0x1f9f25cf,0xadf2b89b,0x5ad6b472,0x5a88f54c,0xe029ac71,0xe019a5e6, 0x47b0acfd,0xed93fa9b,0xe8d3c48d,0x283b57cc,0xf8d56629,0x79132e28, 0x785f0191,0xed756055,0xf7960e44,0xe3d35e8c,0x15056dd4,0x88f46dba, 0x03a16125,0x0564f0bd,0xc3eb9e15,0x3c9057a2,0x97271aec,0xa93a072a, 0x1b3f6d9b,0x1e6321f5,0xf59c66fb,0x26dcf319,0x7533d928,0xb155fdf5, 0x03563482,0x8aba3cbb,0x28517711,0xc20ad9f8,0xabcc5167,0xccad925f, 0x4de81751,0x3830dc8e,0x379d5862,0x9320f991,0xea7a90c2,0xfb3e7bce, 0x5121ce64,0x774fbe32,0xa8b6e37e,0xc3293d46,0x48de5369,0x6413e680, 0xa2ae0810,0xdd6db224,0x69852dfd,0x09072166,0xb39a460a,0x6445c0dd, 0x586cdecf,0x1c20c8ae,0x5bbef7dd,0x1b588d40,0xccd2017f,0x6bb4e3bb, 0xdda26a7e,0x3a59ff45,0x3e350a44,0xbcb4cdd5,0x72eacea8,0xfa6484bb, 0x8d6612ae,0xbf3c6f47,0xd29be463,0x542f5d9e,0xaec2771b,0xf64e6370, 0x740e0d8d,0xe75b1357,0xf8721671,0xaf537d5d,0x4040cb08,0x4eb4e2cc, 0x34d2466a,0x0115af84,0xe1b00428,0x95983a1d,0x06b89fb4,0xce6ea048, 0x6f3f3b82,0x3520ab82,0x011a1d4b,0x277227f8,0x611560b1,0xe7933fdc, 0xbb3a792b,0x344525bd,0xa08839e1,0x51ce794b,0x2f32c9b7,0xa01fbac9, 0xe01cc87e,0xbcc7d1f6,0xcf0111c3,0xa1e8aac7,0x1a908749,0xd44fbd9a, 0xd0dadecb,0xd50ada38,0x0339c32a,0xc6913667,0x8df9317c,0xe0b12b4f, 0xf79e59b7,0x43f5bb3a,0xf2d519ff,0x27d9459c,0xbf97222c,0x15e6fc2a, 0x0f91fc71,0x9b941525,0xfae59361,0xceb69ceb,0xc2a86459,0x12baa8d1, 0xb6c1075e,0xe3056a0c,0x10d25065,0xcb03a442,0xe0ec6e0e,0x1698db3b, 0x4c98a0be,0x3278e964,0x9f1f9532,0xe0d392df,0xd3a0342b,0x8971f21e, 0x1b0a7441,0x4ba3348c,0xc5be7120,0xc37632d8,0xdf359f8d,0x9b992f2e, 0xe60b6f47,0x0fe3f11d,0xe54cda54,0x1edad891,0xce6279cf,0xcd3e7e6f, 0x1618b166,0xfd2c1d05,0x848fd2c5,0xf6fb2299,0xf523f357,0xa6327623, 0x93a83531,0x56cccd02,0xacf08162,0x5a75ebb5,0x6e163697,0x88d273cc, 0xde966292,0x81b949d0,0x4c50901b,0x71c65614,0xe6c6c7bd,0x327a140a, 0x45e1d006,0xc3f27b9a,0xc9aa53fd,0x62a80f00,0xbb25bfe2,0x35bdd2f6, 0x71126905,0xb2040222,0xb6cbcf7c,0xcd769c2b,0x53113ec0,0x1640e3d3, 0x38abbd60,0x2547adf0,0xba38209c,0xf746ce76,0x77afa1c5,0x20756060, 0x85cbfe4e,0x8ae88dd8,0x7aaaf9b0,0x4cf9aa7e,0x1948c25c,0x02fb8a8c, 0x01c36ae4,0xd6ebe1f9,0x90d4f869,0xa65cdea0,0x3f09252d,0xc208e69f, 0xb74e6132,0xce77e25b,0x578fdfe3,0x3ac372e6] ]pithos-1.1.1/pithos/pandora/data.py000066400000000000000000000016721252623276000172500ustar00rootroot00000000000000client_keys = { 'android-generic':{ 'deviceModel': 'android-generic', 'username': 'android', 'password': 'AC7IBG09A3DTSYM4R41UJWL07VLN8JI7', 'rpcUrl': '://tuner.pandora.com/services/json/?', 'encryptKey': '6#26FRL$ZWD', 'decryptKey': 'R=U!LH$O2B#', 'version' : '5', }, 'pandora-one':{ 'deviceModel': 'D01', 'username': 'pandora one', 'password': 'TVCKIBGS9AO9TSYLNNFUML0743LH82D', 'rpcUrl': '://internal-tuner.pandora.com/services/json/?', 'encryptKey': '2%3WCL*JU$MP]4', 'decryptKey': 'U#IO$RZPAB%VX2', 'version' : '5', } } default_client_id = "android-generic" default_one_client_id = "pandora-one" # See http://pan-do-ra-api.wikia.com/wiki/Json/5/station.getPlaylist valid_audio_formats = [ ('highQuality', 'High'), ('mediumQuality', 'Medium'), ('lowQuality', 'Low'), ] default_audio_quality = 'mediumQuality' pithos-1.1.1/pithos/pandora/fake.py000066400000000000000000000130151252623276000172370ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- ### BEGIN LICENSE # Copyright (C) 2010 Kevin Mehall #This program is free software: you can redistribute it and/or modify it #under the terms of the GNU General Public License version 3, as published #by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, but #WITHOUT ANY WARRANTY; without even the implied warranties of #MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR #PURPOSE. See the GNU General Public License for more details. # #You should have received a copy of the GNU General Public License along #with this program. If not, see . ### END LICENSE from .pandora import * from gi.repository import Gtk import logging TEST_FILE = "http://pithos.github.io/testfile.aac" class FakePandora(Pandora): def __init__(self): super(FakePandora, self).__init__() self.counter = 0 self.show_fail_window() logging.info("Using test mode") def count(self): self.counter +=1 return self.counter def show_fail_window(self): self.window = Gtk.Window() self.window.set_size_request(200, 100) self.window.set_title("Pithos failure tester") self.window.set_opacity(0.7) self.auth_check = Gtk.CheckButton.new_with_label("Authenticated") self.time_check = Gtk.CheckButton.new_with_label("Be really slow") vbox = Gtk.VBox() self.window.add(vbox) vbox.pack_start(self.auth_check, True, True, 0) vbox.pack_start(self.time_check, True, True, 0) self.window.show_all() def maybe_fail(self): if self.time_check.get_active(): logging.info("fake: Going to sleep for 10s") time.sleep(10) if not self.auth_check.get_active(): logging.info("fake: We're deauthenticated...") raise PandoraAuthTokenInvalid("Auth token invalid", "AUTH_INVALID_TOKEN") def set_authenticated(self): self.auth_check.set_active(True) def json_call(self, method, args={}, https=False, blowfish=True): time.sleep(1) self.maybe_fail() if method == 'user.getStationList': return {'stations': [ {'stationId':'987', 'stationToken':'345434', 'isShared':False, 'isQuickMix':False, 'stationName':"Test Station 1"}, {'stationId':'321', 'stationToken':'453544', 'isShared':False, 'isQuickMix':True, 'stationName':"Fake's QuickMix", 'quickMixStationIds':['987', '343']}, {'stationId':'432', 'stationToken':'345485', 'isShared':False, 'isQuickMix':False, 'stationName':"Test Station 2"}, {'stationId':'254', 'stationToken':'345415', 'isShared':False, 'isQuickMix':False, 'stationName':"Test Station 4 - Out of Order"}, {'stationId':'343', 'stationToken':'345435', 'isShared':False, 'isQuickMix':False, 'stationName':"Test Station 3"}, ]} elif method == 'station.getPlaylist': stationId = self.get_station_by_token(args['stationToken']).id return {'items': [self.makeFakeSong(stationId) for i in range(4)]} elif method == 'music.search': return {'artists': [ {'score':90, 'musicToken':'988', 'artistName':"artistName"}, ], 'songs':[ {'score':80, 'musicToken':'238', 'songName':"SongName", 'artistName':"ArtistName"}, ], } elif method == 'station.createStation': return {'stationId':'999', 'stationToken':'345433', 'isShared':False, 'isQuickMix':False, 'stationName':"Added Station"} elif method == 'station.addFeedback': return {'feedbackId': '1234'} elif method in ('user.setQuickMix', 'station.deleteFeedback', 'station.transformSharedStation', 'station.renameStation', 'station.deleteStation', 'user.sleepSong', 'bookmark.addSongBookmark', 'bookmark.addArtistBookmark', ): return 1 else: logging.error("Invalid method %s" % method) def connect(self, client, user, password): self.set_authenticated() self.get_stations() def get_station_by_token(self, token): for i in self.stations: if i.idToken == token: return i def makeFakeSong(self, stationId): c = self.count() audio_url = TEST_FILE + '?val='+'0'*48 return { 'albumName':"AlbumName", 'artistName':"ArtistName", 'audioUrlMap': { 'highQuality': { 'audioUrl': audio_url }, 'mediumQuality': { 'audioUrl': audio_url }, 'lowQuality': { 'audioUrl': audio_url }, }, 'trackGain':0, 'trackToken':'5908540384', 'songRating': 1 if c%3 == 0 else 0, 'stationId': stationId, 'songName': 'Test song %i'%c, 'songDetailUrl': 'http://pithos.github.io/', 'albumDetailUrl':'http://pithos.github.io/', 'albumArtUrl':'http://pithos.github.io/img/pithos_logo.png', 'songExplorerUrl':'http://pithos.github.io/test-song.xml', } pithos-1.1.1/pithos/pandora/pandora.py000066400000000000000000000415061252623276000177630ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- ### BEGIN LICENSE # Copyright (C) 2010 Kevin Mehall # Copyright (C) 2012 Christopher Eby #This program is free software: you can redistribute it and/or modify it #under the terms of the GNU General Public License version 3, as published #by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, but #WITHOUT ANY WARRANTY; without even the implied warranties of #MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR #PURPOSE. See the GNU General Public License for more details. # #You should have received a copy of the GNU General Public License along #with this program. If not, see . ### END LICENSE """Pandora JSON v5 API See http://6xq.net/playground/pandora-apidoc/json/ for API documentation. """ from .blowfish import Blowfish # from Crypto.Cipher import Blowfish from xml.dom import minidom import re import json import logging import time import urllib.request, urllib.parse, urllib.error import codecs HTTP_TIMEOUT = 30 USER_AGENT = 'pithos' RATE_BAN = 'ban' RATE_LOVE = 'love' RATE_NONE = None API_ERROR_API_VERSION_NOT_SUPPORTED = 11 API_ERROR_COUNTRY_NOT_SUPPORTED = 12 API_ERROR_INSUFFICIENT_CONNECTIVITY = 13 API_ERROR_READ_ONLY_MODE = 1000 API_ERROR_INVALID_AUTH_TOKEN = 1001 API_ERROR_INVALID_LOGIN = 1002 API_ERROR_LISTENER_NOT_AUTHORIZED = 1003 API_ERROR_PARTNER_NOT_AUTHORIZED = 1010 API_ERROR_PLAYLIST_EXCEEDED = 1039 PLAYLIST_VALIDITY_TIME = 60*60*3 NAME_COMPARE_REGEX = re.compile(r'[^A-Za-z0-9]') class PandoraError(IOError): def __init__(self, message, status=None, submsg=None): self.status = status self.message = message self.submsg = submsg class PandoraAuthTokenInvalid(PandoraError): pass class PandoraNetError(PandoraError): pass class PandoraAPIVersionError(PandoraError): pass class PandoraTimeout(PandoraNetError): pass def pad(s, l): return s + b'\0' * (l - len(s)) class Pandora(object): """Access the Pandora API To use the Pandora class, make sure to call :py:meth:`set_audio_quality` and :py:meth:`connect` methods. Get information from Pandora using: - :py:meth:`get_stations` which populates the :py:attr:`stations` attribute - :py:meth:`search` to find songs to add to stations or create a new station with - :py:meth:`json_call` call into the JSON API directly """ def __init__(self): self.opener = urllib.request.build_opener() pass def pandora_encrypt(self, s): return b''.join([codecs.encode(self.blowfish_encode.encrypt(pad(s[i:i+8], 8)), 'hex_codec') for i in range(0, len(s), 8)]) def pandora_decrypt(self, s): return b''.join([self.blowfish_decode.decrypt(pad(codecs.decode(s[i:i+16], 'hex_codec'), 8)) for i in range(0, len(s), 16)]).rstrip(b'\x08') def json_call(self, method, args={}, https=False, blowfish=True): url_arg_strings = [] if self.partnerId: url_arg_strings.append('partner_id=%s'%self.partnerId) if self.userId: url_arg_strings.append('user_id=%s'%self.userId) if self.userAuthToken: url_arg_strings.append('auth_token=%s'%urllib.parse.quote_plus(self.userAuthToken)) elif self.partnerAuthToken: url_arg_strings.append('auth_token=%s'%urllib.parse.quote_plus(self.partnerAuthToken)) url_arg_strings.append('method=%s'%method) protocol = 'https' if https else 'http' url = protocol + self.rpcUrl + '&'.join(url_arg_strings) if self.time_offset: args['syncTime'] = int(time.time()+self.time_offset) if self.userAuthToken: args['userAuthToken'] = self.userAuthToken elif self.partnerAuthToken: args['partnerAuthToken'] = self.partnerAuthToken data = json.dumps(args).encode('utf-8') logging.debug(url) logging.debug(data) if blowfish: data = self.pandora_encrypt(data) try: req = urllib.request.Request(url, data, {'User-agent': USER_AGENT, 'Content-type': 'text/plain'}) response = self.opener.open(req, timeout=HTTP_TIMEOUT) text = response.read().decode('utf-8') except urllib.error.HTTPError as e: logging.error("HTTP error: %s", e) raise PandoraNetError(str(e)) except urllib.error.URLError as e: logging.error("Network error: %s", e) if e.reason.strerror == 'timed out': raise PandoraTimeout("Network error", submsg="Timeout") else: raise PandoraNetError("Network error", submsg=e.reason.strerror) logging.debug(text) tree = json.loads(text) if tree['stat'] == 'fail': code = tree['code'] msg = tree['message'] logging.error('fault code: ' + str(code) + ' message: ' + msg) if code == API_ERROR_INVALID_AUTH_TOKEN: raise PandoraAuthTokenInvalid(msg) elif code == API_ERROR_COUNTRY_NOT_SUPPORTED: raise PandoraError("Pandora not available", code, submsg="Pandora is not available in your country.") elif code == API_ERROR_API_VERSION_NOT_SUPPORTED: raise PandoraAPIVersionError(msg) elif code == API_ERROR_INSUFFICIENT_CONNECTIVITY: raise PandoraError("Out of sync", code, submsg="Correct your system's clock. If the problem persists, a Pithos update may be required") elif code == API_ERROR_READ_ONLY_MODE: raise PandoraError("Pandora maintenance", code, submsg="Pandora is in read-only mode as it is performing maintenance. Try again later.") elif code == API_ERROR_INVALID_LOGIN: raise PandoraError("Login Error", code, submsg="Invalid username or password") elif code == API_ERROR_LISTENER_NOT_AUTHORIZED: raise PandoraError("Pandora Error", code, submsg="A Pandora One account is required to access this feature. Uncheck 'Pandora One' in Settings.") elif code == API_ERROR_PARTNER_NOT_AUTHORIZED: raise PandoraError("Login Error", code, submsg="Invalid Pandora partner keys. A Pithos update may be required.") elif code == API_ERROR_PLAYLIST_EXCEEDED: raise PandoraError("Playlist Error", code, submsg="You have requested too many playlists. Try again later.") else: raise PandoraError("Pandora returned an error", code, "%s (code %d)"%(msg, code)) if 'result' in tree: return tree['result'] def set_audio_quality(self, fmt): """Set the desired audio quality Used by the :py:attr:`Song.audioUrl` property. :param fmt: An audio quality format from :py:data:`pithos.pandora.data.valid_audio_formats` """ self.audio_quality = fmt def set_url_opener(self, opener): self.opener = opener def connect(self, client, user, password): """Connect to the Pandora API and log the user in :param client: The client ID from :py:data:`pithos.pandora.data.client_keys` :param user: The user's login email :param password: The user's login password """ self.partnerId = self.userId = self.partnerAuthToken = None self.userAuthToken = self.time_offset = None self.rpcUrl = client['rpcUrl'] self.blowfish_encode = Blowfish(client['encryptKey'].encode('utf-8')) self.blowfish_decode = Blowfish(client['decryptKey'].encode('utf-8')) partner = self.json_call('auth.partnerLogin', { 'deviceModel': client['deviceModel'], 'username': client['username'], # partner username 'password': client['password'], # partner password 'version': client['version'] },https=True, blowfish=False) self.partnerId = partner['partnerId'] self.partnerAuthToken = partner['partnerAuthToken'] pandora_time = int(self.pandora_decrypt(partner['syncTime'].encode('utf-8'))[4:14]) self.time_offset = pandora_time - time.time() logging.info("Time offset is %s", self.time_offset) user = self.json_call('auth.userLogin', {'username': user, 'password': password, 'loginType': 'user'}, https=True) self.userId = user['userId'] self.userAuthToken = user['userAuthToken'] self.get_stations(self) def get_stations(self, *ignore): stations = self.json_call('user.getStationList')['stations'] self.quickMixStationIds = None self.stations = [Station(self, i) for i in stations] if self.quickMixStationIds: for i in self.stations: if i.id in self.quickMixStationIds: i.useQuickMix = True return self.stations def save_quick_mix(self): stationIds = [] for i in self.stations: if i.useQuickMix: stationIds.append(i.id) self.json_call('user.setQuickMix', {'quickMixStationIds': stationIds}) def search(self, query): results = self.json_call('music.search', {'searchText': query}) l = [SearchResult('artist', i) for i in results['artists']] l += [SearchResult('song', i) for i in results['songs']] l.sort(key=lambda i: i.score, reverse=True) return l def add_station_by_music_id(self, musicid): d = self.json_call('station.createStation', {'musicToken': musicid}) station = Station(self, d) self.stations.append(station) return station def get_station_by_id(self, id): for i in self.stations: if i.id == id: return i def add_feedback(self, trackToken, rating): logging.info("pandora: addFeedback") rating_bool = True if rating == RATE_LOVE else False feedback = self.json_call('station.addFeedback', {'trackToken': trackToken, 'isPositive': rating_bool}) return feedback['feedbackId'] def delete_feedback(self, stationToken, feedbackId): self.json_call('station.deleteFeedback', {'feedbackId': feedbackId, 'stationToken': stationToken}) class Station(object): def __init__(self, pandora, d): self.pandora = pandora self.id = d['stationId'] self.idToken = d['stationToken'] self.isCreator = not d['isShared'] self.isQuickMix = d['isQuickMix'] self.name = d['stationName'] self.useQuickMix = False if self.isQuickMix: self.pandora.quickMixStationIds = d.get('quickMixStationIds', []) def transformIfShared(self): if not self.isCreator: logging.info("pandora: transforming station") self.pandora.json_call('station.transformSharedStation', {'stationToken': self.idToken}) self.isCreator = True def get_playlist(self): logging.info("pandora: Get Playlist") playlist = self.pandora.json_call('station.getPlaylist', {'stationToken': self.idToken}, https=True) songs = [] for i in playlist['items']: if 'songName' in i: # check for ads songs.append(Song(self.pandora, i)) return songs @property def info_url(self): return 'http://www.pandora.com/stations/'+self.idToken def rename(self, new_name): if new_name != self.name: self.transformIfShared() logging.info("pandora: Renaming station") self.pandora.json_call('station.renameStation', {'stationToken': self.idToken, 'stationName': new_name}) self.name = new_name def delete(self): logging.info("pandora: Deleting Station") self.pandora.json_call('station.deleteStation', {'stationToken': self.idToken}) def __repr__(self): return '<{}.{} {} "{}">'.format( __name__, __class__.__name__, self.id, self.name, ) class Song(object): def __init__(self, pandora, d): self.pandora = pandora self.album = d['albumName'] self.artist = d['artistName'] self.audioUrlMap = d['audioUrlMap'] self.trackToken = d['trackToken'] self.rating = RATE_LOVE if d['songRating'] == 1 else RATE_NONE # banned songs won't play, so we don't care about them self.stationId = d['stationId'] self.songName = d['songName'] self.songDetailURL = d['songDetailUrl'] self.songExplorerUrl = d['songExplorerUrl'] self.artRadio = d['albumArtUrl'] self.bitrate = None self.is_ad = None # None = we haven't checked, otherwise True/False self.tired=False self.message='' self.duration = None self.position = None self.start_time = None self.finished = False self.playlist_time = time.time() self.feedbackId = None @property def title(self): if not hasattr(self, '_title'): # the actual name of the track, minus any special characters (except dashes) is stored # as the last part of the songExplorerUrl, before the args. explorer_name = self.songExplorerUrl.split('?')[0].split('/')[-1] clean_expl_name = NAME_COMPARE_REGEX.sub('', explorer_name).lower() clean_name = NAME_COMPARE_REGEX.sub('', self.songName).lower() if clean_name == clean_expl_name: self._title = self.songName else: try: xml_data = urllib.urlopen(self.songExplorerUrl) dom = minidom.parseString(xml_data.read()) attr_value = dom.getElementsByTagName('songExplorer')[0].attributes['songTitle'].value # Pandora stores their titles for film scores and the like as 'Score name: song name' self._title = attr_value.replace('{0}: '.format(self.songName), '', 1) except: self._title = self.songName return self._title @property def audioUrl(self): quality = self.pandora.audio_quality try: q = self.audioUrlMap[quality] logging.info("Using audio quality %s: %s %s", quality, q['bitrate'], q['encoding']) return q['audioUrl'] except KeyError: logging.warn("Unable to use audio format %s. Using %s", quality, list(self.audioUrlMap.keys())[0]) return list(self.audioUrlMap.values())[0]['audioUrl'] @property def station(self): return self.pandora.get_station_by_id(self.stationId) def get_duration_sec (self): if self.duration is not None: return self.duration / 1000000000 def get_position_sec (self): if self.position is not None: return self.position / 1000000000 def rate(self, rating): if self.rating != rating: self.station.transformIfShared() if rating == RATE_NONE: if not self.feedbackId: # We need a feedbackId, get one by re-rating the song. We # could also get one by calling station.getStation, but # that requires transferring a lot of data (all feedback, # seeds, etc for the station). opposite = RATE_BAN if self.rating == RATE_LOVE else RATE_LOVE self.feedbackId = self.pandora.add_feedback(self.trackToken, opposite) self.pandora.delete_feedback(self.station.idToken, self.feedbackId) else: self.feedbackId = self.pandora.add_feedback(self.trackToken, rating) self.rating = rating def set_tired(self): if not self.tired: self.pandora.json_call('user.sleepSong', {'trackToken': self.trackToken}) self.tired = True def bookmark(self): self.pandora.json_call('bookmark.addSongBookmark', {'trackToken': self.trackToken}) def bookmark_artist(self): self.pandora.json_call('bookmark.addArtistBookmark', {'trackToken': self.trackToken}) @property def rating_str(self): return self.rating def is_still_valid(self): return (time.time() - self.playlist_time) < PLAYLIST_VALIDITY_TIME def __repr__(self): return '<{}.{} {} "{}" by "{}" from "{}">'.format( __name__, __class__.__name__, self.trackToken, self.songName, self.artist, self.album, ) class SearchResult(object): def __init__(self, resultType, d): self.resultType = resultType self.score = d['score'] self.musicId = d['musicToken'] if resultType == 'song': self.title = d['songName'] self.artist = d['artistName'] elif resultType == 'artist': self.name = d['artistName'] pithos-1.1.1/pithos/pithos.py000077500000000000000000001256171252623276000162320ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- ### BEGIN LICENSE # Copyright (C) 2010-2012 Kevin Mehall #This program is free software: you can redistribute it and/or modify it #under the terms of the GNU General Public License version 3, as published #by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, but #WITHOUT ANY WARRANTY; without even the implied warranties of #MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR #PURPOSE. See the GNU General Public License for more details. # #You should have received a copy of the GNU General Public License along #with this program. If not, see . ### END LICENSE import argparse import cgi import contextlib import html import json import logging import math import os import re import signal import sys import time import urllib.error import urllib.parse import urllib.request import gi gi.require_version('Gst', '1.0') from gi.repository import Gst, GstPbutils, GObject, Gtk, Gdk, Pango, GdkPixbuf, Gio, GLib if Gtk.get_major_version() < 3 or Gtk.get_minor_version() < 14: sys.exit('Gtk 3.14 is required') from . import AboutPithosDialog, PreferencesPithosDialog, StationsDialog from .gobject_worker import GObjectWorker from .pandora import * from .pandora.data import * from .pithosconfig import get_ui_file, get_media_file, VERSION from .plugin import load_plugins from .util import parse_proxy, open_browser pacparser_imported = False try: import pacparser pacparser_imported = True except ImportError: pass ALBUM_ART_SIZE = 96 ALBUM_ART_X_PAD = 6 class CellRendererAlbumArt(Gtk.CellRenderer): def __init__(self): GObject.GObject.__init__(self) self.icon = None self.pixbuf = None self.rate_bg = GdkPixbuf.Pixbuf.new_from_file(get_media_file('rate')) __gproperties__ = { 'icon': (str, 'icon', 'icon', '', GObject.PARAM_READWRITE), 'pixbuf': (GdkPixbuf.Pixbuf, 'pixmap', 'pixmap', GObject.PARAM_READWRITE) } def do_set_property(self, pspec, value): setattr(self, pspec.name, value) def do_get_property(self, pspec): return getattr(self, pspec.name) def do_get_size(self, widget, cell_area): return (0, 0, ALBUM_ART_SIZE + ALBUM_ART_X_PAD, ALBUM_ART_SIZE) def do_render(self, ctx, widget, background_area, cell_area, flags): if self.pixbuf: Gdk.cairo_set_source_pixbuf(ctx, self.pixbuf, cell_area.x, cell_area.y) ctx.paint() if self.icon: x = cell_area.x+(cell_area.width-self.rate_bg.get_width()) - ALBUM_ART_X_PAD # right y = cell_area.y+(cell_area.height-self.rate_bg.get_height()) # bottom Gdk.cairo_set_source_pixbuf(ctx, self.rate_bg, x, y) ctx.paint() pixbuf = Gtk.IconTheme.get_default().load_icon(self.icon, Gtk.IconSize.MENU, 0) x = cell_area.x+(cell_area.width-pixbuf.get_width())-5 - ALBUM_ART_X_PAD # right y = cell_area.y+(cell_area.height-pixbuf.get_height())-5 # bottom Gdk.cairo_set_source_pixbuf(ctx, pixbuf, x, y) ctx.paint() def get_album_art(url, *extra): try: with urllib.request.urlopen(url) as f: image = f.read() except urllib.error.HTTPError: logging.warn('Invalid image url received') return (None,) + extra with contextlib.closing(GdkPixbuf.PixbufLoader()) as loader: loader.set_size(ALBUM_ART_SIZE, ALBUM_ART_SIZE) loader.write(image) return (loader.get_pixbuf(),) + extra class PlayerStatus (object): def __init__(self): self.reset() def reset(self): self.async_done = False self.began_buffering = None self.buffer_percent = 0 self.pending_duration_query = False class PithosWindow(Gtk.ApplicationWindow): __gtype_name__ = "PithosWindow" __gsignals__ = { "song-changed": (GObject.SignalFlags.RUN_FIRST, None, (GObject.TYPE_PYOBJECT,)), "song-ended": (GObject.SignalFlags.RUN_FIRST, None, (GObject.TYPE_PYOBJECT,)), "song-rating-changed": (GObject.SignalFlags.RUN_FIRST, None, (GObject.TYPE_PYOBJECT,)), "play-state-changed": (GObject.SignalFlags.RUN_FIRST, None, (GObject.TYPE_BOOLEAN,)), "user-changed-play-state": (GObject.SignalFlags.RUN_FIRST, None, (GObject.TYPE_BOOLEAN,)), } def __init__(self): """__init__ - This function is typically not called directly. Creation a PithosWindow requires redeading the associated ui file and parsing the ui definition extrenally, and then calling PithosWindow.finish_initializing(). Use the convenience function NewPithosWindow to create PithosWindow object. """ pass def finish_initializing(self, builder, cmdopts): """finish_initalizing should be called after parsing the ui definition and creating a PithosWindow object with it in order to finish initializing the start of the new PithosWindow instance. """ signal.signal(signal.SIGINT, signal.SIG_DFL) self.cmdopts = cmdopts #get a reference to the builder and set up the signals self.builder = builder self.builder.connect_signals(self) self.prefs_dlg = PreferencesPithosDialog.NewPreferencesPithosDialog() self.prefs_dlg.set_transient_for(self) self.preferences = self.prefs_dlg.get_preferences() if self.prefs_dlg.fix_perms(): # Changes were made, save new config variable self.prefs_dlg.save() self.init_core() self.init_ui() self.plugins = {} load_plugins(self) self.prefs_dlg.set_plugins(self.plugins) if not self.preferences['username']: self.show_preferences(is_startup=True) self.pandora = make_pandora(self.cmdopts.test) self.set_proxy() self.set_audio_quality() self.pandora_connect() def init_core(self): # Song object display text icon album art self.songs_model = Gtk.ListStore(GObject.TYPE_PYOBJECT, str, str, GdkPixbuf.Pixbuf) # Station object station name self.stations_model = Gtk.ListStore(GObject.TYPE_PYOBJECT, str) Gst.init(None) self._query_duration = Gst.Query.new_duration(Gst.Format.TIME) self._query_position = Gst.Query.new_position(Gst.Format.TIME) self.player = Gst.ElementFactory.make("playbin", "player"); bus = self.player.get_bus() bus.add_signal_watch() bus.connect("message::async-done", self.on_gst_async_done) bus.connect("message::duration-changed", self.on_gst_duration_changed) bus.connect("message::eos", self.on_gst_eos) bus.connect("message::buffering", self.on_gst_buffering) bus.connect("message::error", self.on_gst_error) bus.connect("message::element", self.on_gst_element) bus.connect("message::tag", self.on_gst_tag) self.player.connect("notify::volume", self.on_gst_volume) self.player.connect("notify::source", self.on_gst_source) self.player_status = PlayerStatus() self.stations_dlg = None self.playing = None # None is a special "Waiting to play" state self.current_song_index = None self.current_station = None self.current_station_id = self.preferences.get('last_station_id') self.auto_retrying_auth = False self.have_stations = False self.playcount = 0 self.gstreamer_errorcount_1 = 0 self.gstreamer_errorcount_2 = 0 self.gstreamer_error = '' self.waiting_for_playlist = False self.start_new_playlist = False self.ui_loop_timer_id = 0 self.worker = GObjectWorker() self.art_worker = GObjectWorker() aa = GdkPixbuf.Pixbuf.new_from_file(get_media_file('album')) self.default_album_art = aa.scale_simple(ALBUM_ART_SIZE, ALBUM_ART_SIZE, GdkPixbuf.InterpType.BILINEAR) def init_ui(self): GLib.set_application_name("Pithos") Gtk.Window.set_default_icon_name('pithos') os.environ['PULSE_PROP_media.role'] = 'music' self.playpause_image = self.builder.get_object('playpause_image') self.volume = self.builder.get_object('volume') self.volume.set_relief(Gtk.ReliefStyle.NORMAL) # It ignores glade... self.volume.set_property("value", math.pow(float(self.preferences['volume']), 1.0/3.0)) self.statusbar = self.builder.get_object('statusbar1') self.song_menu = self.builder.get_object('song_menu') self.song_menu_love = self.builder.get_object('menuitem_love') self.song_menu_unlove = self.builder.get_object('menuitem_unlove') self.song_menu_ban = self.builder.get_object('menuitem_ban') self.song_menu_unban = self.builder.get_object('menuitem_unban') self.songs_treeview = self.builder.get_object('songs_treeview') self.songs_treeview.set_model(self.songs_model) title_col = Gtk.TreeViewColumn() def bgcolor_data_func(column, cell, model, iter, data=None): if model.get_value(iter, 0) is self.current_song: bgcolor = column.get_tree_view().get_style_context().get_background_color(Gtk.StateFlags.ACTIVE) else: bgcolor = column.get_tree_view().get_style_context().get_background_color(Gtk.StateFlags.NORMAL) cell.set_property("cell-background-rgba", bgcolor) render_icon = CellRendererAlbumArt() title_col.pack_start(render_icon, False) title_col.add_attribute(render_icon, "icon", 2) title_col.add_attribute(render_icon, "pixbuf", 3) title_col.set_cell_data_func(render_icon, bgcolor_data_func) render_text = Gtk.CellRendererText() render_text.props.ellipsize = Pango.EllipsizeMode.END title_col.pack_start(render_text, True) title_col.add_attribute(render_text, "markup", 1) title_col.set_cell_data_func(render_text, bgcolor_data_func) self.songs_treeview.append_column(title_col) self.songs_treeview.connect('button_press_event', self.on_treeview_button_press_event) self.stations_combo = self.builder.get_object('stations') self.stations_combo.set_model(self.stations_model) render_text = Gtk.CellRendererText() self.stations_combo.pack_start(render_text, True) self.stations_combo.add_attribute(render_text, "text", 1) self.stations_combo.set_row_separator_func(lambda model, iter, data=None: model.get_value(iter, 0) is None, None) self.set_initial_pos() def worker_run(self, fn, args=(), callback=None, message=None, context='net'): if context and message: self.statusbar.push(self.statusbar.get_context_id(context), message) if isinstance(fn,str): fn = getattr(self.pandora, fn) def cb(v): if context: self.statusbar.pop(self.statusbar.get_context_id(context)) if callback: callback(v) def eb(e): if context and message: self.statusbar.pop(self.statusbar.get_context_id(context)) def retry_cb(): self.auto_retrying_auth = False if fn is not self.pandora.connect: self.worker_run(fn, args, callback, message, context) if isinstance(e, PandoraAuthTokenInvalid) and not self.auto_retrying_auth: self.auto_retrying_auth = True logging.info("Automatic reconnect after invalid auth token") self.pandora_connect("Reconnecting...", retry_cb) elif isinstance(e, PandoraAPIVersionError): self.api_update_dialog() elif isinstance(e, PandoraError): self.error_dialog(e.message, retry_cb, submsg=e.submsg) else: logging.warn(e.traceback) self.worker.send(fn, args, cb, eb) def get_proxy(self): """ Get HTTP proxy, first trying preferences then system proxy """ if self.preferences['proxy']: return self.preferences['proxy'] system_proxies = urllib.request.getproxies() if 'http' in system_proxies: return system_proxies['http'] return None def set_proxy(self): # proxy preference is used for all Pithos HTTP traffic # control proxy preference is used only for Pandora traffic and # overrides proxy # # If neither option is set, urllib2.build_opener uses urllib.getproxies() # by default handlers = [] global_proxy = self.preferences['proxy'] if global_proxy: handlers.append(urllib.request.ProxyHandler({'http': global_proxy, 'https': global_proxy})) global_opener = urllib.request.build_opener(*handlers) urllib.request.install_opener(global_opener) control_opener = global_opener control_proxy = self.preferences['control_proxy'] control_proxy_pac = self.preferences['control_proxy_pac'] if control_proxy: control_opener = urllib.request.build_opener(urllib.request.ProxyHandler({'http': control_proxy, 'https': control_proxy})) elif control_proxy_pac and pacparser_imported: pacparser.init() with urllib.request.urlopen(control_proxy_pac) as f: pacstring = f.read().decode('utf-8') try: pacparser.parse_pac_string(pacstring) except: logging.warning('Failed to parse PAC.') try: proxies = pacparser.find_proxy("http://pandora.com", "pandora.com").split(";") for proxy in proxies: match = re.search("PROXY (.*)", proxy) if match: control_proxy = match.group(1) break except: logging.warning('Failed to find proxy via PAC.') pacparser.cleanup() elif control_proxy_pac and not pacparser_imported: logging.warning("Disabled proxy auto-config support because python-pacparser module was not found.") self.worker_run('set_url_opener', (control_opener,)) def set_audio_quality(self): self.worker_run('set_audio_quality', (self.preferences['audio_quality'],)) def pandora_connect(self, message="Logging in...", callback=None): if self.preferences['pandora_one']: client = client_keys[default_one_client_id] else: client = client_keys[default_client_id] # Allow user to override client settings force_client = self.preferences['force_client'] if force_client in client_keys: client = client_keys[force_client] elif force_client and force_client[0] == '{': try: client = json.loads(force_client) except: logging.error("Could not parse force_client json") args = ( client, self.preferences['username'], self.preferences['password'], ) def pandora_ready(*ignore): logging.info("Pandora connected") self.process_stations(self) if callback: callback() self.worker_run('connect', args, pandora_ready, message, 'login') def process_stations(self, *ignore): self.stations_model.clear() self.current_station = None selected = None for i in self.pandora.stations: if i.isQuickMix and i.isCreator: self.stations_model.append((i, "QuickMix")) self.stations_model.append((None, 'sep')) for i in self.pandora.stations: if not (i.isQuickMix and i.isCreator): self.stations_model.append((i, i.name)) if i.id == self.current_station_id: logging.info("Restoring saved station: id = %s"%(i.id)) selected = i if not selected: selected=self.stations_model[0][0] self.station_changed(selected, reconnecting = self.have_stations) self.have_stations = True @property def current_song(self): if self.current_song_index is not None: return self.songs_model[self.current_song_index][0] def start_song(self, song_index): songs_remaining = len(self.songs_model) - song_index if songs_remaining <= 0: # We don't have this song yet. Get a new playlist. return self.get_playlist(start = True) elif songs_remaining == 1: # Preload next playlist so there's no delay self.get_playlist() prev = self.current_song self.stop() self.current_song_index = song_index if prev: self.update_song_row(prev) if not self.current_song.is_still_valid(): self.current_song.message = "Playlist expired" self.update_song_row() return self.next_song() if self.current_song.tired or self.current_song.rating == RATE_BAN: return self.next_song() logging.info("Starting song: index = %i"%(song_index)) self.player_status.reset() self.player.set_property("uri", self.current_song.audioUrl) self.player.set_state(Gst.State.PAUSED) self.playing = None self.playcount += 1 self.current_song.start_time = time.time() self.songs_treeview.scroll_to_cell(song_index, use_align=True, row_align = 1.0) self.songs_treeview.set_cursor(song_index, None, 0) self.set_title("Pithos - %s by %s" % (self.current_song.title, self.current_song.artist)) self.emit('song-changed', self.current_song) def next_song(self, *ignore): self.start_song(self.current_song_index + 1) def user_play(self, *ignore): self.play() self.emit('user-changed-play-state', True) def play(self): if not self.playing: self.playing = True self.create_ui_loop() self.player.set_state(Gst.State.PLAYING) self.playpause_image.set_from_icon_name('media-playback-pause-symbolic', Gtk.IconSize.SMALL_TOOLBAR) self.update_song_row() self.emit('play-state-changed', True) def user_pause(self, *ignore): self.pause() self.emit('user-changed-play-state', False) def pause(self): self.playing = False self.destroy_ui_loop() self.player.set_state(Gst.State.PAUSED) self.playpause_image.set_from_icon_name('media-playback-start-symbolic', Gtk.IconSize.SMALL_TOOLBAR) self.update_song_row() self.emit('play-state-changed', False) def stop(self): prev = self.current_song if prev and prev.start_time: prev.finished = True prev.position = self.query_position() self.emit("song-ended", prev) self.playing = False self.destroy_ui_loop() self.player.set_state(Gst.State.NULL) self.emit('play-state-changed', False) def user_playpause(self, *ignore): self.playpause_notify() def playpause(self, *ignore): logging.info("playpause") if self.playing: self.pause() else: self.play() def playpause_notify(self, *ignore): if self.playing: self.user_pause() else: self.user_play() def get_playlist(self, start = False): self.start_new_playlist = self.start_new_playlist or start if self.waiting_for_playlist: return if self.gstreamer_errorcount_1 >= self.playcount and self.gstreamer_errorcount_2 >=1: logging.warn("Too many gstreamer errors. Not retrying") self.waiting_for_playlist = 1 self.error_dialog(self.gstreamer_error, self.get_playlist) return def art_callback(t): pixbuf, song, index = t if index%s" % (description, msg) def song_icon(self, song): if song.tired: return 'go-jump' if song.rating == RATE_LOVE: return 'emblem-favorite' if song.rating == RATE_BAN: return 'dialog-error' def update_song_row(self, song = None): if song is None: song = self.current_song if song: self.songs_model[song.index][1] = self.song_text(song) self.songs_model[song.index][2] = self.song_icon(song) or "" return self.playing def create_ui_loop(self): if not self.ui_loop_timer_id: self.ui_loop_timer_id = GLib.timeout_add_seconds(1, self.update_song_row) def destroy_ui_loop(self): if self.ui_loop_timer_id: GLib.source_remove(self.ui_loop_timer_id) self.ui_loop_timer_id = 0 def stations_combo_changed(self, widget): index = widget.get_active() if index>=0: self.station_changed(self.stations_model[index][0]) def format_time(self, time_int): if time_int is None: return None time_int = time_int // 1000000000 s = time_int % 60 time_int //= 60 m = time_int % 60 time_int //= 60 h = time_int if h: return "%i:%02i:%02i"%(h,m,s) else: return "%i:%02i"%(m,s) def selected_song(self): sel = self.songs_treeview.get_selection().get_selected() if sel: return self.songs_treeview.get_model().get_value(sel[1], 0) def love_song(self, song=None): song = song or self.current_song def callback(l): self.update_song_row(song) self.emit('song-rating-changed', song) self.worker_run(song.rate, (RATE_LOVE,), callback, "Loving song...") def ban_song(self, song=None): song = song or self.current_song def callback(l): self.update_song_row(song) self.emit('song-rating-changed', song) self.worker_run(song.rate, (RATE_BAN,), callback, "Banning song...") if song is self.current_song: self.next_song() def unrate_song(self, song=None): song = song or self.current_song def callback(l): self.update_song_row(song) self.emit('song-rating-changed', song) self.worker_run(song.rate, (RATE_NONE,), callback, "Removing song rating...") def tired_song(self, song=None): song = song or self.current_song def callback(l): self.update_song_row(song) self.emit('song-rating-changed', song) self.worker_run(song.set_tired, (), callback, "Putting song on shelf...") if song is self.current_song: self.next_song() def bookmark_song(self, song=None): song = song or self.current_song self.worker_run(song.bookmark, (), None, "Bookmarking...") def bookmark_song_artist(self, song=None): song = song or self.current_song self.worker_run(song.bookmark_artist, (), None, "Bookmarking...") def on_menuitem_love(self, widget): self.love_song(self.selected_song()) def on_menuitem_ban(self, widget): self.ban_song(self.selected_song()) def on_menuitem_unrate(self, widget): self.unrate_song(self.selected_song()) def on_menuitem_tired(self, widget): self.tired_song(self.selected_song()) def on_menuitem_info(self, widget): song = self.selected_song() open_browser(song.songDetailURL) def on_menuitem_bookmark_song(self, widget): self.bookmark_song(self.selected_song()) def on_menuitem_bookmark_artist(self, widget): self.bookmark_song_artist(self.selected_song()) def on_treeview_button_press_event(self, treeview, event): x = int(event.x) y = int(event.y) time = event.time pthinfo = treeview.get_path_at_pos(x, y) if pthinfo is not None: path, col, cellx, celly = pthinfo treeview.grab_focus() treeview.set_cursor( path, col, 0) if event.button == 3: rating = self.selected_song().rating self.song_menu_love.set_property("visible", rating != RATE_LOVE); self.song_menu_unlove.set_property("visible", rating == RATE_LOVE); self.song_menu_ban.set_property("visible", rating != RATE_BAN); self.song_menu_unban.set_property("visible", rating == RATE_BAN); self.song_menu.popup( None, None, None, None, event.button, time) return True if event.button == 1 and event.type == Gdk.EventType._2BUTTON_PRESS: logging.info("Double clicked on song %s", self.selected_song().index) if self.selected_song().index <= self.current_song_index: return False self.start_song(self.selected_song().index) def set_player_volume(self, value): # Use a cubic scale for volume. This matches what PulseAudio uses. volume = math.pow(value, 3) self.player.set_property("volume", volume) self.preferences['volume'] = volume def adjust_volume(self, amount): old_volume = self.volume.get_property("value") new_volume = max(0.0, min(1.0, old_volume + 0.02 * amount)) if new_volume != old_volume: self.volume.set_property("value", new_volume) def on_volume_change_event(self, volumebutton, value): self.set_player_volume(value) def station_properties(self, *ignore): open_browser(self.current_station.info_url) def show_about(self): """about - display the about box for pithos """ about = AboutPithosDialog.NewAboutPithosDialog() about.set_transient_for(self) about.set_version(VERSION) about.run() about.destroy() def show_preferences(self, is_startup=False): """preferences - display the preferences window for pithos """ if is_startup: self.prefs_dlg.set_type_hint(Gdk.WindowTypeHint.NORMAL) old_prefs = dict(self.preferences) response = self.prefs_dlg.run() self.prefs_dlg.hide() if response == Gtk.ResponseType.OK: self.preferences = self.prefs_dlg.get_preferences() if not is_startup: if ( self.preferences['proxy'] != old_prefs['proxy'] or self.preferences['control_proxy'] != old_prefs['control_proxy']): self.set_proxy() if self.preferences['audio_quality'] != old_prefs['audio_quality']: self.set_audio_quality() if ( self.preferences['username'] != old_prefs['username'] or self.preferences['password'] != old_prefs['password'] or self.preferences['pandora_one'] != old_prefs['pandora_one']): self.pandora_connect() else: self.prefs_dlg.set_type_hint(Gdk.WindowTypeHint.DIALOG) def show_stations(self): if self.stations_dlg: self.stations_dlg.present() else: self.stations_dlg = StationsDialog.NewStationsDialog(self) self.stations_dlg.set_transient_for(self) self.stations_dlg.show_all() def refresh_stations(self, *ignore): self.worker_run(self.pandora.get_stations, (), self.process_stations, "Refreshing stations...") def set_initial_pos(self): """ Moves window to position stored in preferences """ x, y = self.preferences['x_pos'], self.preferences['y_pos'] if not x is None and not y is None: self.move(int(x), int(y)) def bring_to_top(self, *ignore): self.set_initial_pos() self.show() self.present() def on_configure_event(self, widget, event): self.preferences['x_pos'], self.preferences['y_pos'] = event.x, event.y def on_kb_playpause(self, widget=None, data=None): if not isinstance(widget.get_focus(), Gtk.Button) and data.keyval == 32: self.playpause() return True def quit(self, widget=None, data=None): """quit - signal handler for closing the PithosWindow""" self.destroy() def on_destroy(self, widget, data=None): """on_destroy - called when the PithosWindow is close. """ self.stop() self.preferences['last_station_id'] = self.current_station_id self.prefs_dlg.save() self.quit() def NewPithosWindow(app, options): """NewPithosWindow - returns a fully instantiated PithosWindow object. Use this function rather than creating a PithosWindow directly. """ builder = Gtk.Builder() builder.add_from_file(get_ui_file('main')) window = builder.get_object("pithos_window") window.set_application(app) window.finish_initializing(builder, options) return window class PithosApplication(Gtk.Application): def __init__(self): # Use org.gnome to avoid conflict with existing dbus interface net.kevinmehall Gtk.Application.__init__(self, application_id='org.gnome.pithos', flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE) self.window = None self.options = None def do_startup(self): Gtk.Application.do_startup(self) # Setup appmenu builder = Gtk.Builder() builder.add_from_file(get_ui_file('menu')) menu = builder.get_object("app-menu") self.set_app_menu(menu) action = Gio.SimpleAction.new("stations", None) action.connect("activate", self.stations_cb) self.add_action(action) action = Gio.SimpleAction.new("preferences", None) action.connect("activate", self.prefs_cb) self.add_action(action) action = Gio.SimpleAction.new("about", None) action.connect("activate", self.about_cb) self.add_action(action) action = Gio.SimpleAction.new("quit", None) action.connect("activate", self.quit_cb) self.add_action(action) # FIXME: do_local_command_line() segfaults? def do_command_line(self, args): Gtk.Application.do_command_line(self, args) parser = argparse.ArgumentParser() parser.add_argument("-v", "--verbose", action="count", default=0, dest="verbose", help="Show debug messages") parser.add_argument("-t", "--test", action="store_true", dest="test", help="Use a mock web interface instead of connecting to the real Pandora server") self.options = parser.parse_args(args.get_arguments()[1:]) # First, get rid of existing logging handlers due to call in header as per # http://stackoverflow.com/questions/1943747/python-logging-before-you-run-logging-basicconfig logging.root.handlers = [] #set the logging level to show debug messages if self.options.verbose > 1: log_level = logging.DEBUG elif self.options.verbose == 1: log_level = logging.INFO else: log_level = logging.WARN logging.basicConfig(level=log_level, format='%(levelname)s - %(module)s:%(funcName)s:%(lineno)d - %(message)s') self.do_activate() return 0 def do_activate(self): if not self.window: logging.info("Pithos %s" %VERSION) self.window = NewPithosWindow(self, self.options) self.window.present() def do_shutdown(self): Gtk.Application.do_shutdown(self) self.window.destroy() def stations_cb(self, action, param): self.window.show_stations() def prefs_cb(self, action, param): self.window.show_preferences() def about_cb(self, action, param): self.window.show_about() def quit_cb(self, action, param): self.window.destroy() def main(): app = PithosApplication() exit_status = app.run(sys.argv) sys.exit(exit_status) if __name__ == '__main__': main() pithos-1.1.1/pithos/pithosconfig.py000066400000000000000000000051721252623276000174060ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- ### BEGIN LICENSE # Copyright (C) 2010-2012 Kevin Mehall #This program is free software: you can redistribute it and/or modify it #under the terms of the GNU General Public License version 3, as published #by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, but #WITHOUT ANY WARRANTY; without even the implied warranties of #MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR #PURPOSE. See the GNU General Public License for more details. # #You should have received a copy of the GNU General Public License along #with this program. If not, see . ### END LICENSE # where your project will head for your data (for instance, images and ui files) # by default, this is data, relative your trunk layout __pithos_data_directory__ = 'data/' __license__ = 'GPL-3' VERSION = '1.1.1' import os class project_path_not_found(Exception): pass ui_files = { 'about': 'AboutPithosDialog.ui', 'preferences': 'PreferencesPithosDialog.ui', 'search': 'SearchDialog.ui', 'stations': 'StationsDialog.ui', 'main': 'PithosWindow.ui', 'menu': 'app_menu.ui' } media_files = { 'icon': 'icon.svg', 'rate': 'rate_bg.png', 'album': 'album_default.png' } def get_media_file(name): media = os.path.join(getdatapath(), 'media', media_files[name]) if not os.path.exists(media): media = None return media def get_ui_file(name): ui_filename = os.path.join(getdatapath(), 'ui', ui_files[name]) if not os.path.exists(ui_filename): ui_filename = None return ui_filename def get_data_file(*path_segments): """Get the full path to a data file. Returns the path to a file underneath the data directory (as defined by `get_data_path`). Equivalent to os.path.join(get_data_path(), *path_segments). """ return os.path.join(getdatapath(), *path_segments) def getdatapath(): """Retrieve pithos data path This path is by default /../data/ in trunk and /usr/share/pithos in an installed version but this path is specified at installation time. """ # get pathname absolute or relative if __pithos_data_directory__.startswith('/'): pathname = __pithos_data_directory__ else: pathname = os.path.dirname(__file__) + '/' + __pithos_data_directory__ abs_data_path = os.path.abspath(pathname) if os.path.exists(abs_data_path): return abs_data_path else: raise project_path_not_found if __name__=='__main__': print(VERSION) pithos-1.1.1/pithos/plugin.py000066400000000000000000000062061252623276000162070ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- ### BEGIN LICENSE # Copyright (C) 2010-2012 Kevin Mehall #This program is free software: you can redistribute it and/or modify it #under the terms of the GNU General Public License version 3, as published #by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, but #WITHOUT ANY WARRANTY; without even the implied warranties of #MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR #PURPOSE. See the GNU General Public License for more details. # #You should have received a copy of the GNU General Public License along #with this program. If not, see . ### END LICENSE import logging import glob import os class PithosPlugin: _PITHOS_PLUGIN = True # used to find the plugin class in a module preference = None description = "" def __init__(self, name, window): self.name = name self.window = window self.preferences_dialog = None self.prepared = False self.enabled = False def enable(self): if not self.prepared: self.error = self.on_prepare() self.prepared = True if not self.error and not self.enabled: logging.info("Enabling module %s"%(self.name)) self.on_enable() self.enabled = True def disable(self): if self.enabled: logging.info("Disabling module %s"%(self.name)) self.on_disable() self.enabled = False def on_prepare(self): pass def on_enable(self): pass def on_disable(self): pass class ErrorPlugin(PithosPlugin): def __init__(self, name, error): logging.error("Error loading plugin %s: %s"%(name, error)) self.prepared = True self.error = error self.name = name self.enabled = False def load_plugin(name, window): try: module = __import__('pithos.plugins.'+name) module = getattr(module.plugins, name) except ImportError as e: return ErrorPlugin(name, e.msg) # find the class object for the actual plugin for key, item in module.__dict__.items(): if hasattr(item, '_PITHOS_PLUGIN') and key != "PithosPlugin": plugin_class = item break else: return ErrorPlugin(name, "Could not find module class") return plugin_class(name, window) def load_plugins(window): plugins = window.plugins prefs = window.preferences plugins_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "plugins") discovered_plugins = [ fname.replace(".py", "") for fname in glob.glob1(plugins_dir, "*.py") if not fname.startswith("_") ] for name in discovered_plugins: if not name in plugins: plugin = plugins[name] = load_plugin(name, window) else: plugin = plugins[name] if plugin.preference and prefs.get(plugin.preference, False): plugin.enable() else: plugin.disable() pithos-1.1.1/pithos/plugins/000077500000000000000000000000001252623276000160145ustar00rootroot00000000000000pithos-1.1.1/pithos/plugins/__init__.py000066400000000000000000000000001252623276000201130ustar00rootroot00000000000000pithos-1.1.1/pithos/plugins/_dbus_service.py000066400000000000000000000052611252623276000212060ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- ### BEGIN LICENSE # Copyright (C) 2010 Kevin Mehall #This program is free software: you can redistribute it and/or modify it #under the terms of the GNU General Public License version 3, as published #by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, but #WITHOUT ANY WARRANTY; without even the implied warranties of #MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR #PURPOSE. See the GNU General Public License for more details. # #You should have received a copy of the GNU General Public License along #with this program. If not, see . ### END LICENSE import dbus.service DBUS_BUS = "net.kevinmehall.Pithos" DBUS_OBJECT_PATH = "/net/kevinmehall/Pithos" def song_to_dict(song): d = {} if song: for i in ['artist', 'title', 'album', 'songDetailURL']: d[i] = getattr(song, i) return d class PithosDBusProxy(dbus.service.Object): def __init__(self, window): self.bus = dbus.SessionBus() bus_name = dbus.service.BusName(DBUS_BUS, bus=self.bus) dbus.service.Object.__init__(self, bus_name, DBUS_OBJECT_PATH) self.window = window self.window.connect("song-changed", self.songchange_handler) self.window.connect("play-state-changed", self.playstate_handler) def playstate_handler(self, window, state): self.PlayStateChanged(state) def songchange_handler(self, window, song): self.SongChanged(song_to_dict(song)) @dbus.service.method(DBUS_BUS) def PlayPause(self): self.window.playpause_notify() @dbus.service.method(DBUS_BUS) def SkipSong(self): self.window.next_song() @dbus.service.method(DBUS_BUS) def LoveCurrentSong(self): self.window.love_song() @dbus.service.method(DBUS_BUS) def BanCurrentSong(self): self.window.ban_song() @dbus.service.method(DBUS_BUS) def TiredCurrentSong(self): self.window.tired_song() @dbus.service.method(DBUS_BUS) def Present(self): self.window.bring_to_top() @dbus.service.method(DBUS_BUS, out_signature='a{sv}') def GetCurrentSong(self): return song_to_dict(self.window.current_song) @dbus.service.method(DBUS_BUS, out_signature='b') def IsPlaying(self): return self.window.playing @dbus.service.signal(DBUS_BUS, signature='b') def PlayStateChanged(self, state): pass @dbus.service.signal(DBUS_BUS, signature='a{sv}') def SongChanged(self, songinfo): pass pithos-1.1.1/pithos/plugins/_mpris.py000066400000000000000000000247661252623276000176760ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- ### BEGIN LICENSE # Copyright (C) 2011 Rick Spencer # Copyright (C) 2011-2012 Kevin Mehall #This program is free software: you can redistribute it and/or modify it #under the terms of the GNU General Public License version 3, as published #by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, but #WITHOUT ANY WARRANTY; without even the implied warranties of #MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR #PURPOSE. See the GNU General Public License for more details. # #You should have received a copy of the GNU General Public License along #with this program. If not, see . ### END LICENSE import dbus import dbus.service from xml.etree import ElementTree class PithosMprisService(dbus.service.Object): MEDIA_PLAYER2_IFACE = 'org.mpris.MediaPlayer2' MEDIA_PLAYER2_PLAYER_IFACE = 'org.mpris.MediaPlayer2.Player' def __init__(self, window): """ Creates a PithosSoundMenu object. Requires a dbus loop to be created before the gtk mainloop, typically by calling DBusGMainLoop(set_as_default=True). """ bus_str = """org.mpris.MediaPlayer2.pithos""" bus_name = dbus.service.BusName(bus_str, bus=dbus.SessionBus()) dbus.service.Object.__init__(self, bus_name, "/org/mpris/MediaPlayer2") self.window = window self.song_changed() self.window.connect("song-changed", self.songchange_handler) self.window.connect("song-rating-changed", self.ratingchange_handler) self.window.connect("play-state-changed", self.playstate_handler) def playstate_handler(self, window, state): if state: self.signal_playing() else: self.signal_paused() def songchange_handler(self, window, song): self.song_changed([song.artist], song.album, song.title, song.artRadio, song.rating) self.signal_playing() def ratingchange_handler(self, window, song): """Handle rating changes and update MPRIS metadata accordingly""" # Pithos fires rating-changed signals for all songs, not just the # currently playing one, so we need ignore signals for irrelevant songs. if song is not self.window.current_song: return self.__metadata["pithos:rating"] = song.rating or "" self.PropertiesChanged("org.mpris.MediaPlayer2.Player", dbus.Dictionary({"Metadata": self.__metadata}, "sv", variant_level=1), []) def song_changed(self, artists=None, album=None, title=None, artUrl='', rating=None): """song_changed - sets the info for the current song. This method is not typically overriden. It should be called by implementations of this class when the player has changed songs. named arguments: artists - a list of strings representing the artists" album - a string for the name of the album title - a string for the title of the song """ self.__metadata = dbus.Dictionary({ "xesam:title": title or "Title Unknown", "xesam:artist": artists or ["Artist Unknown"], "xesam:album": album or "Album Unknown", "mpris:artUrl": artUrl or "", "pithos:rating": rating or "", }, "sv", variant_level=1) # Properties def _get_playback_status(self): """Current status "Playing", "Paused", or "Stopped".""" if not self.window.current_song: return "Stopped" if self.window.playing: return "Playing" else: return "Paused" def _get_metadata(self): """The info for the current song.""" return self.__metadata def _get_volume(self): return self.window.player.get_property("volume") def _set_volume(self, new_volume): self.window.player.set_property('volume', new_volume) def _get_position(self): return self.window.query_position() / 1000 @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature='ss', out_signature='v') def Get(self, interface_name, property_name): try: return self.GetAll(interface_name)[property_name] except KeyError: raise dbus.exceptions.DBusException( interface_name, 'Property %s was not found.' %property_name) @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature='ssv') def Set(self, interface_name, property_name, new_value): if interface_name == self.MEDIA_PLAYER2_IFACE: pass elif interface_name == self.MEDIA_PLAYER2_PLAYER_IFACE: if property_name == 'Volume': self._set_volume(new_value) else: raise dbus.exceptions.DBusException( 'org.mpris.MediaPlayer2.pithos', 'This object does not implement the %s interface' % interface_name) @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature='s', out_signature='a{sv}') def GetAll(self, interface_name): if interface_name == self.MEDIA_PLAYER2_IFACE: return { 'CanQuit': True, 'CanRaise': True, 'HasTrackList': False, 'Identity': 'Pithos', 'DesktopEntry': 'pithos', 'SupportedUriSchemes': [''], 'SupportedMimeTypes': [''], } elif interface_name == self.MEDIA_PLAYER2_PLAYER_IFACE: return { 'PlaybackStatus': self._get_playback_status(), 'LoopStatus': "None", 'Rate': dbus.Double(1.0), 'Shuffle': False, 'Metadata': dbus.Dictionary(self._get_metadata(), signature='sv'), 'Volume': dbus.Double(self._get_volume()), 'Position': dbus.Int64(self._get_position()), 'MinimumRate': dbus.Double(1.0), 'MaximumRate': dbus.Double(1.0), 'CanGoNext': self.window.waiting_for_playlist is not True, 'CanGoPrevious': False, 'CanPlay': self.window.current_song is not None, 'CanPause': self.window.current_song is not None, 'CanSeek': False, 'CanControl': True, } else: raise dbus.exceptions.DBusException( 'org.mpris.MediaPlayer2.pithos', 'This object does not implement the %s interface' % interface_name) @dbus.service.method(MEDIA_PLAYER2_IFACE) def Raise(self): """Bring the media player to the front when selected by the sound menu""" self.window.bring_to_top() @dbus.service.method(MEDIA_PLAYER2_IFACE) def Quit(self): """Exit the player""" self.window.quit() @dbus.service.method(MEDIA_PLAYER2_PLAYER_IFACE) def Previous(self): """Play prvious song, not implemented""" pass @dbus.service.method(MEDIA_PLAYER2_PLAYER_IFACE) def Next(self): """Play next song""" self.window.next_song() @dbus.service.method(MEDIA_PLAYER2_PLAYER_IFACE) def PlayPause(self): self.window.playpause() @dbus.service.method(MEDIA_PLAYER2_PLAYER_IFACE) def Play(self): self.window.play() @dbus.service.method(MEDIA_PLAYER2_PLAYER_IFACE) def Pause(self): self.window.pause() @dbus.service.method(MEDIA_PLAYER2_PLAYER_IFACE) def Stop(self): self.window.stop() def signal_playing(self): """signal_playing - Tell the Sound Menu that the player has started playing. """ self.__playback_status = "Playing" d = dbus.Dictionary({"PlaybackStatus":self.__playback_status, "Metadata":self.__metadata}, "sv",variant_level=1) self.PropertiesChanged("org.mpris.MediaPlayer2.Player",d,[]) def signal_paused(self): """signal_paused - Tell the Sound Menu that the player has been paused """ self.__playback_status = "Paused" d = dbus.Dictionary({"PlaybackStatus":self.__playback_status}, "sv",variant_level=1) self.PropertiesChanged("org.mpris.MediaPlayer2.Player",d,[]) @dbus.service.signal(dbus.PROPERTIES_IFACE, signature='sa{sv}as') def PropertiesChanged(self, interface_name, changed_properties, invalidated_properties): """PropertiesChanged A function necessary to implement dbus properties. Typically, this function is not overriden or called directly. """ pass # python-dbus does not have our properties for introspection, so we must manually add them @dbus.service.method(dbus.INTROSPECTABLE_IFACE, in_signature="", out_signature="s", path_keyword="object_path", connection_keyword="connection") def Introspect(self, object_path, connection): data = dbus.service.Object.Introspect(self, object_path, connection) xml = ElementTree.fromstring(data) for iface in xml.findall("interface"): name = iface.attrib["name"] if name.startswith(self.MEDIA_PLAYER2_IFACE): for item, value in self.GetAll(name).items(): prop = {"name": item, "access": "read"} if item == "Volume": # Hardcode the only writable property.. prop["access"] = "readwrite" # Ugly mapping of types to signatures, is there a helper for this? # KEEP IN SYNC! if isinstance(value, str): prop["type"] = "s" elif isinstance(value, bool): prop["type"] = "b" elif isinstance(value, float): prop["type"] = "d" elif isinstance(value, int): prop["type"] = "x" elif isinstance(value, list): prop["type"] = "as" elif isinstance(value, dict): prop["type"] = "a{sv}" iface.append(ElementTree.Element("property", prop)) return ElementTree.tostring(xml, encoding="UTF-8") pithos-1.1.1/pithos/plugins/lastfm.py000066400000000000000000000145471252623276000176670ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- ### BEGIN LICENSE # Copyright (C) 2010-2012 Kevin Mehall #This program is free software: you can redistribute it and/or modify it #under the terms of the GNU General Public License version 3, as published #by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, but #WITHOUT ANY WARRANTY; without even the implied warranties of #MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR #PURPOSE. See the GNU General Public License for more details. # #You should have received a copy of the GNU General Public License along #with this program. If not, see . ### END LICENSE from gi.repository import Gtk import logging from pithos.gobject_worker import GObjectWorker from pithos.plugin import PithosPlugin from pithos.util import open_browser #getting an API account: http://www.last.fm/api/account API_KEY = '997f635176130d5d6fe3a7387de601a8' API_SECRET = '3243b876f6bf880b923a3c9fb955720c' #client id, client version info: http://www.last.fm/api/submissions#1.1 CLIENT_ID = 'pth' CLIENT_VERSION = '1.0' _worker = None def get_worker(): # so it can be shared between the plugin and the authorizer global _worker if not _worker: _worker = GObjectWorker() return _worker class LastfmPlugin(PithosPlugin): preference = 'enable_lastfm' description = 'Scrobble tracks listened to on Last.fm' def on_prepare(self): try: import pylast except ImportError: logging.warning("pylast not found.") return "pylast not found" self.pylast = pylast self.worker = get_worker() self.is_really_enabled = False self.preferences_dialog = LastFmAuth(self.pylast, self.window.preferences, "lastfm_key", self.window) self.preferences_dialog.connect('delete-event', self.auth_closed) def on_enable(self): if self.window.preferences['lastfm_key']: self._enable_real() def auth_closed(self, widget, event): if self.window.preferences['lastfm_key']: self._enable_real() else: self.window.preferences['enable_lastfm'] = False widget.hide() return True # Don't delete window def _enable_real(self): self.connect(self.window.preferences['lastfm_key']) self.song_ended_handle = self.window.connect('song-ended', self.song_ended) self.song_changed_handle = self.window.connect('song-changed', self.song_changed) self.is_really_enabled = True def on_disable(self): if self.is_really_enabled: self.window.disconnect(self.song_ended_handle) self.window.disconnect(self.song_changed_handle) self.is_really_enabled = False def song_ended(self, window, song): self.scrobble(song) def connect(self, session_key): self.network = self.pylast.get_lastfm_network( api_key=API_KEY, api_secret=API_SECRET, session_key = session_key ) self.scrobbler = self.network.get_scrobbler(CLIENT_ID, CLIENT_VERSION) def song_changed(self, window, song): self.worker.send(self.scrobbler.report_now_playing, (song.artist, song.title, song.album)) def send_rating(self, song, rating): if song.rating: track = self.network.get_track(song.artist, song.title) if rating == 'love': self.worker.send(track.love) elif rating == 'ban': self.worker.send(track.ban) logging.info("Sending song rating to last.fm") def scrobble(self, song): duration = song.get_duration_sec() position = song.get_position_sec() if duration > 30 and (position > 240 or position > duration/2): logging.info("Scrobbling song") mode = self.pylast.SCROBBLE_MODE_PLAYED source = self.pylast.SCROBBLE_SOURCE_PERSONALIZED_BROADCAST self.worker.send(self.scrobbler.scrobble, (song.artist, song.title, int(song.start_time), source, mode, duration, song.album)) class LastFmAuth(Gtk.Dialog): def __init__(self, pylast, d, prefname, parent): Gtk.Dialog.__init__(self) self.set_default_size(200, -1) self.dict = d self.prefname = prefname self.pylast = pylast self.auth_url= False label = Gtk.Label.new('In order to use LastFM you must authorize this with your account') label.set_line_wrap(True) self.button = Gtk.Button() self.button.set_halign(Gtk.Align.CENTER) self.set_button_text() self.button.connect('clicked', self.clicked) self.get_content_area().add(label) self.get_content_area().show_all() self.get_action_area().add(self.button) self.get_action_area().set_layout(Gtk.ButtonBoxStyle.EXPAND) @property def enabled(self): return self.dict[self.prefname] def setkey(self, key): self.dict[self.prefname] = key self.set_button_text() def set_button_text(self): self.button.set_sensitive(True) if self.auth_url: self.button.set_label("Click once authorized on web site") elif self.enabled: self.button.set_label("Disable") else: self.button.set_label("Authorize") def clicked(self, *ignore): if self.auth_url: def err(e): logging.error(e) self.set_button_text() get_worker().send(self.sg.get_web_auth_session_key, (self.auth_url,), self.setkey, err) self.button.set_label("Checking...") self.button.set_sensitive(False) self.auth_url = False elif self.enabled: self.setkey(False) else: self.network = self.pylast.get_lastfm_network(api_key=API_KEY, api_secret=API_SECRET) self.sg = self.pylast.SessionKeyGenerator(self.network) def callback(url): self.auth_url = url self.set_button_text() open_browser(self.auth_url) get_worker().send(self.sg.get_web_auth_url, (), callback) self.button.set_label("Connecting...") self.button.set_sensitive(False) pithos-1.1.1/pithos/plugins/mediakeys.py000066400000000000000000000107671252623276000203540ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- ### BEGIN LICENSE # Copyright (C) 2010-2012 Kevin Mehall #This program is free software: you can redistribute it and/or modify it #under the terms of the GNU General Public License version 3, as published #by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, but #WITHOUT ANY WARRANTY; without even the implied warranties of #MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR #PURPOSE. See the GNU General Public License for more details. # #You should have received a copy of the GNU General Public License along #with this program. If not, see . ### END LICENSE from pithos.plugin import PithosPlugin import sys import logging APP_ID = 'Pithos' class MediaKeyPlugin(PithosPlugin): preference = 'enable_mediakeys' description = 'Control playback with media keys' def bind_dbus(self): try: import dbus from dbus.mainloop.glib import DBusGMainLoop DBusGMainLoop(set_as_default=True) except ImportError: return False try: bus = dbus.Bus(dbus.Bus.TYPE_SESSION) mk = bus.get_object("org.gnome.SettingsDaemon","/org/gnome/SettingsDaemon/MediaKeys") mk.GrabMediaPlayerKeys(APP_ID, 0, dbus_interface='org.gnome.SettingsDaemon.MediaKeys') mk.connect_to_signal("MediaPlayerKeyPressed", self.mediakey_pressed) logging.info("Bound media keys with DBUS") self.method = 'dbus' return True except dbus.DBusException: return False def mediakey_pressed(self, app, action): if app == APP_ID: if action == 'Play': self.window.playpause_notify() elif action == 'Next': self.window.next_song() elif action == 'Stop': self.window.user_pause() elif action == 'Previous': self.window.bring_to_top() def bind_keybinder(self): try: import gi gi.require_version('Keybinder', '3.0') # Gdk needed for Keybinder from gi.repository import Keybinder, Gdk Keybinder.init() except: return False Keybinder.bind('XF86AudioPlay', self.window.playpause, None) Keybinder.bind('XF86AudioStop', self.window.user_pause, None) Keybinder.bind('XF86AudioNext', self.window.next_song, None) Keybinder.bind('XF86AudioPrev', self.window.bring_to_top, None) logging.info("Bound media keys with keybinder") self.method = 'keybinder' return True def kbevent(self, event): if event.KeyID == 179 or event.Key == 'Media_Play_Pause': self.window.playpause_notify() if event.KeyID == 176 or event.Key == 'Media_Next_Track': self.window.next_song() return True def bind_win32(self): try: import pyHook except ImportError: logging.warning('Please install PyHook: http://www.lfd.uci.edu/~gohlke/pythonlibs/#pyhook') return False self.hookman = pyHook.HookManager() self.hookman.KeyDown = self.kbevent self.hookman.HookKeyboard() return True def osx_playpause_handler(self): self.window.playpause_notify() return False # Don't let others get event def osx_skip_handler(self): self.window.next_song() return False def bind_osx(self): try: import osxmmkeys except ImportError: logging.warning('Please install osxmmkeys: https://github.com/pushrax/osxmmkeys') return False except RuntimeError as e: logging.warning('osxmmkeys failed to import: {}'.format(e)) return False tap = osxmmkeys.Tap() tap.on('play_pause', self.osx_playpause_handler) tap.on('next_track', self.osx_skip_handler) tap.start() return True def on_enable(self): if sys.platform == 'win32': loaded = self.bind_win32() elif sys.platform == 'darwin': loaded = self.bind_osx() else: loaded = self.bind_dbus() or self.bind_keybinder() if not loaded: logging.error("Could not bind media keys") def on_disable(self): logging.error("Not implemented: Can't disable media keys") pithos-1.1.1/pithos/plugins/mpris.py000066400000000000000000000033151252623276000175220ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- ### BEGIN LICENSE # Copyright (C) 2011 Rick Spencer # Copyright (C) 2011-2012 Kevin Mehall #This program is free software: you can redistribute it and/or modify it #under the terms of the GNU General Public License version 3, as published #by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, but #WITHOUT ANY WARRANTY; without even the implied warranties of #MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR #PURPOSE. See the GNU General Public License for more details. # #You should have received a copy of the GNU General Public License along #with this program. If not, see . ### END LICENSE import logging from pithos.plugin import PithosPlugin class MprisPlugin(PithosPlugin): preference = 'enable_mpris' description = 'Allows control with external programs' def on_prepare(self): try: from dbus.mainloop.glib import DBusGMainLoop DBusGMainLoop(set_as_default=True) from . import _mpris from . import _dbus_service except ImportError: return "python-dbus not found" self.PithosMprisService = _mpris.PithosMprisService self.PithosDBusProxy = _dbus_service.PithosDBusProxy self.was_enabled = False def on_enable(self): if not self.was_enabled: self.mpris = self.PithosMprisService(self.window) self.service = self.PithosDBusProxy(self.window) self.was_enabled = True def on_disable(self): logging.error("Not implemented: Can't disable mpris") pithos-1.1.1/pithos/plugins/notification_icon.py000066400000000000000000000137701252623276000220740ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- ### BEGIN LICENSE # Copyright (C) 2010-2012 Kevin Mehall #This program is free software: you can redistribute it and/or modify it #under the terms of the GNU General Public License version 3, as published #by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, but #WITHOUT ANY WARRANTY; without even the implied warranties of #MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR #PURPOSE. See the GNU General Public License for more details. # #You should have received a copy of the GNU General Public License along #with this program. If not, see . ### END LICENSE import os from gi.repository import Gtk from pithos.pithosconfig import get_data_file from pithos.plugin import PithosPlugin # Use appindicator if on Unity and installed try: if os.environ['XDG_CURRENT_DESKTOP'] == 'Unity': from gi.repository import AppIndicator3 as AppIndicator indicator_capable = True else: indicator_capable = False except: indicator_capable = False class PithosNotificationIcon(PithosPlugin): preference = 'show_icon' description = 'Adds pithos icon to system tray' def on_prepare(self): if indicator_capable: self.ind = AppIndicator.Indicator.new_with_path("pithos-tray-icon", \ "pithos-tray-icon", \ AppIndicator.IndicatorCategory.APPLICATION_STATUS, \ get_data_file('media')) def on_enable(self): self.delete_callback_handle = self.window.connect("delete-event", self.toggle_visible) self.state_callback_handle = self.window.connect("play-state-changed", self.play_state_changed) self.song_callback_handle = self.window.connect("song-changed", self.song_changed) if indicator_capable: self.ind.set_status(AppIndicator.IndicatorStatus.ACTIVE) else: icon_info = Gtk.IconTheme.lookup_icon (Gtk.IconTheme.get_default(), 'pithos-tray-icon', 48, 0) if icon_info and Gtk.IconInfo.get_filename (icon_info): filename = Gtk.IconInfo.get_filename (icon_info) else: filename = get_data_file('media', 'pithos-tray-icon.png') self.statusicon = Gtk.StatusIcon.new () self.statusicon.set_from_file (filename) self.statusicon.connect('activate', self.toggle_visible) self.build_context_menu() def scroll(self, steps): if indicator_capable: direction = steps.value_nick else: direction = steps.direction.value_nick if direction == 'down': self.window.adjust_volume(-1) elif direction == 'up': self.window.adjust_volume(+1) def build_context_menu(self): menu = Gtk.Menu() def button(text, action, checked=False): if checked: item = Gtk.CheckMenuItem(text) item.set_active(True) else: item = Gtk.MenuItem(text) item.connect('activate', action) item.show() menu.append(item) return item if indicator_capable: # We have to add another entry for show / hide Pithos window self.visible_check = button("Show Pithos", self._toggle_visible, True) self.playpausebtn = button("Pause", self.window.playpause) button("Skip", self.window.next_song) button("Love", (lambda *i: self.window.love_song())) button("Ban", (lambda *i: self.window.ban_song())) button("Tired", (lambda *i: self.window.tired_song())) button("Quit", self.window.quit) # connect our new menu to the statusicon or the appindicator if indicator_capable: self.ind.set_menu(menu) # Disabled because of https://bugs.launchpad.net/variety/+bug/1071598 #self.ind.connect('scroll-event', lambda _x, _y, steps: self.scroll(steps)) else: self.statusicon.connect('popup-menu', self.context_menu, menu) self.statusicon.connect('scroll-event', lambda _, steps: self.scroll(steps)) self.menu = menu def play_state_changed(self, window, playing): """ play or pause and rotate the text """ button = self.playpausebtn if not playing: button.set_label("Play") else: button.set_label("Pause") if indicator_capable: # menu needs to be reset to get updated icon self.ind.set_menu(self.menu) def song_changed(self, window, song): if not indicator_capable: self.statusicon.set_tooltip_text("%s by %s"%(song.title, song.artist)) def _toggle_visible(self, *args): self.window.set_visible(not self.window.get_visible()) if self.window.get_visible(): # Ensure it's on top self.window.bring_to_top() def toggle_visible(self, *args): if hasattr(self, 'visible_check'): self.visible_check.set_active(not self.window.get_visible()) else: self._toggle_visible() return True def context_menu(self, widget, button, time, data=None): if button == 3: if data: data.show_all() data.popup(None, None, None, None, 3, time) def on_disable(self): if indicator_capable: self.ind.set_status(AppIndicator.IndicatorStatus.PASSIVE) else: self.statusicon.set_visible(False) self.window.disconnect(self.delete_callback_handle) self.window.disconnect(self.state_callback_handle) self.window.disconnect(self.song_callback_handle) # Pithos window needs to be reconnected to on_destro() self.window.connect('delete-event',self.window.on_destroy) pithos-1.1.1/pithos/plugins/notify.py000066400000000000000000000132761252623276000177070ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- ### BEGIN LICENSE # Copyright (C) 2010-2012 Kevin Mehall #This program is free software: you can redistribute it and/or modify it #under the terms of the GNU General Public License version 3, as published #by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, but #WITHOUT ANY WARRANTY; without even the implied warranties of #MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR #PURPOSE. See the GNU General Public License for more details. # #You should have received a copy of the GNU General Public License along #with this program. If not, see . ### END LICENSE import logging import html from sys import platform from pithos.plugin import PithosPlugin from pithos.pithosconfig import get_data_file from gi.repository import (GLib, Gtk) class NotifyPlugin(PithosPlugin): preference = 'notify' description = 'Shows notifications on song change' has_notifications = False supports_actions = False escape_markup = False def on_prepare(self): if platform == 'darwin': return self.prepare_osx() else: return self.prepare_notify() def prepare_osx(self): try: from pync import Notifier self.has_notifications = True except ImportError: logging.warning("pync not found.") return "pync not found" self.notifier = Notifier def prepare_notify(self): try: from gi.repository import Notify self.has_notifications = True except ImportError: logging.warning ("libnotify not found.") return "libnotify not found" # Work-around Ubuntu's incompatible workaround for Gnome's API breaking mistake. # https://bugzilla.gnome.org/show_bug.cgi?id=702390 old_add_action = Notify.Notification.add_action def new_add_action(*args): try: old_add_action(*args) except TypeError: old_add_action(*(args + (None,))) Notify.Notification.add_action = new_add_action Notify.init('Pithos') self.notification = Notify.Notification() self.notification.set_category('x-gnome.music') self.notification.set_hint_string('desktop-icon', 'pithos') caps = Notify.get_server_caps() if 'actions' in caps: logging.info('Notify supports actions') self.supports_actions = True if 'body-markup' in caps: self.escape_markup = True if 'action-icons' in caps: self.notification.set_hint('action-icons', GLib.Variant.new_boolean(True)) # TODO: On gnome this can replace the tray icon, just need to add love/hate buttons #if 'persistence' in caps: # self.notification.set_hint('resident', GLib.Variant.new_boolean(True)) def on_enable(self): if self.has_notifications: self.song_callback_handle = self.window.connect("song-changed", self.song_changed) self.state_changed_handle = self.window.connect("user-changed-play-state", self.playstate_changed) def set_actions(self, playing=True): self.notification.clear_actions() pause_action = 'media-playback-pause' play_action = 'media-playback-start' skip_action = 'media-skip-forward' if Gtk.Widget.get_default_direction() == Gtk.TextDirection.RTL: play_action += '-rtl' skip_action += '-rtl' if playing: self.notification.add_action(pause_action, 'Pause', self.notification_playpause_cb, None) else: self.notification.add_action(play_action, 'Play', self.notification_playpause_cb, None) self.notification.add_action(skip_action, 'Skip', self.notification_skip_cb, None) def set_notification_notify(self, song, playing): if self.supports_actions: self.set_actions(playing) if song.art_pixbuf: self.notification.set_image_from_pixbuf(song.art_pixbuf) else: self.notification.set_hint('image-data', None) msg = 'by {} from {}'.format(song.artist, song.album) if self.escape_markup: msg = html.escape(msg, quote=False) self.notification.update(song.title, msg, 'audio-x-generic') self.notification.show() def set_notification_osx(self, song, playing): # TODO: Icons (buttons not possible?) if playing: self.notifier.notify('by {} from {}'.format(song.artist, song.album), title=song.title) def set_notification(self, song, playing=True): if platform == 'darwin': self.set_notification_osx(song, playing) else: self.set_notification_notify(song, playing) def notification_playpause_cb(self, notification, action, data, ignore=None): self.window.playpause_notify() def notification_skip_cb(self, notification, action, data, ignore=None): self.window.next_song() def song_changed(self, window, song): if not self.window.is_active(): GLib.idle_add(self.set_notification, window.current_song) def playstate_changed(self, window, state): if not self.window.is_active(): GLib.idle_add(self.set_notification, window.current_song, state) def on_disable(self): if self.has_notifications: self.window.disconnect(self.song_callback_handle) self.window.disconnect(self.state_changed_handle) pithos-1.1.1/pithos/plugins/screensaver_pause.py000066400000000000000000000061771252623276000221160ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- ### BEGIN LICENSE # Copyright (C) 2010-2012 Kevin Mehall #This program is free software: you can redistribute it and/or modify it #under the terms of the GNU General Public License version 3, as published #by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, but #WITHOUT ANY WARRANTY; without even the implied warranties of #MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR #PURPOSE. See the GNU General Public License for more details. # #You should have received a copy of the GNU General Public License along #with this program. If not, see . ### END LICENSE from pithos.plugin import PithosPlugin import logging dbus = None class ScreenSaverPausePlugin(PithosPlugin): preference = 'enable_screensaverpause' description = 'Pause playback when screensaver starts' session_bus = None def bind_session_bus(self): global dbus try: import dbus from dbus.mainloop.glib import DBusGMainLoop DBusGMainLoop(set_as_default=True) except ImportError: return False try: self.session_bus = dbus.SessionBus() return True except dbus.DBusException: return False def on_enable(self): if not self.bind_session_bus(): logging.error("Could not bind session bus") return self.connect_events() or logging.error("Could not connect events") self.locked = 0 self.wasplaying = False def on_disable(self): if self.session_bus: self.disconnect_events() self.session_bus = None def connect_events(self): try: self.receivers = [ self.session_bus.add_signal_receiver(*args) for args in ((self.playPause, 'ActiveChanged', 'org.gnome.ScreenSaver'), (self.playPause, 'ActiveChanged', 'org.cinnamon.ScreenSaver'), (self.playPause, 'ActiveChanged', 'org.freedesktop.ScreenSaver'), (self.pause, 'Locked', 'com.canonical.Unity.Session'), (self.play, 'Unlocked', 'com.canonical.Unity.Session'), ) ] return True except dbus.DBusException: logging.info("Enable failed") return False def disconnect_events(self): try: for r in self.receivers: r.remove() return True except dbus.DBusException: return False def play(self): self.locked -= 1 if self.locked < 0: self.locked = 0 if not self.locked and self.wasplaying: self.window.user_play() def pause(self): if not self.locked: self.wasplaying = self.window.playing self.window.pause() self.locked += 1 def playPause(self, screensaver_on): if screensaver_on: self.pause() else: self.play() pithos-1.1.1/pithos/util.py000066400000000000000000000035771252623276000156760ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- ### BEGIN LICENSE # Copyright (C) 2010-2012 Kevin Mehall #This program is free software: you can redistribute it and/or modify it #under the terms of the GNU General Public License version 3, as published #by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, but #WITHOUT ANY WARRANTY; without even the implied warranties of #MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR #PURPOSE. See the GNU General Public License for more details. # #You should have received a copy of the GNU General Public License along #with this program. If not, see . ### END LICENSE import logging import webbrowser from urllib.parse import splittype, splituser, splitpasswd def parse_proxy(proxy): """ _parse_proxy from urllib """ scheme, r_scheme = splittype(proxy) if not r_scheme.startswith("/"): # authority scheme = None authority = proxy else: # URL if not r_scheme.startswith("//"): raise ValueError("proxy URL with no authority: %r" % proxy) # We have an authority, so for RFC 3986-compliant URLs (by ss 3. # and 3.3.), path is empty or starts with '/' end = r_scheme.find("/", 2) if end == -1: end = None authority = r_scheme[2:end] userinfo, hostport = splituser(authority) if userinfo is not None: user, password = splitpasswd(userinfo) else: user = password = None return scheme, user, password, hostport def open_browser(url): logging.info("Opening URL {}".format(url)) webbrowser.open(url) if isinstance(webbrowser.get(), webbrowser.BackgroundBrowser): try: os.wait() # workaround for http://bugs.python.org/issue5993 except: pass pithos-1.1.1/requirements-osx.txt000066400000000000000000000001631252623276000171200ustar00rootroot00000000000000# scrobble pylast # notify pync # mediakeys pyobjc-core pyobjc-framework-Cocoa pyobjc-framework-Quartz osxmmkeys pithos-1.1.1/setup.py000077500000000000000000000070241252623276000145450ustar00rootroot00000000000000#!/usr/bin/env python3 # -*- coding: utf-8 -*- ### BEGIN LICENSE # Copyright (C) 2010 Kevin Mehall #This program is free software: you can redistribute it and/or modify it #under the terms of the GNU General Public License version 3, as published #by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, but #WITHOUT ANY WARRANTY; without even the implied warranties of #MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR #PURPOSE. See the GNU General Public License for more details. # #You should have received a copy of the GNU General Public License along #with this program. If not, see . ### END LICENSE ###################### DO NOT TOUCH THIS (HEAD TO THE SECOND PART) ###################### import sys if sys.version_info[0] != 3: sys.exit("Only python 3 is supported!") try: from setuptools import setup, find_packages, Command except ImportError: import ez_setup ez_setup.use_setuptools() from setuptools import setup, find_packages, Command try: from sphinx.setup_command import BuildDoc except ImportError: class BuildDoc(Command): description = "Build documentation with Sphinx." user_options = [] version = None release = None def initialize_options(self): pass def finalize_options(self): pass def run(self): print("Error: Sphinx not found!") import os import sys from pithos.pithosconfig import VERSION # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # README file and 2) it's easier to type in the README file than to put a raw # string in below ... def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() if sys.platform != 'win32': data_files = [ ('/usr/share/icons/hicolor/scalable/apps', ['data/icons/hicolor/pithos.svg']), ('/usr/share/icons/hicolor/48x48/apps', ['data/icons/hicolor/pithos-tray-icon.png']), ('/usr/share/icons/ubuntu-mono-dark/apps/16', ['data/icons/ubuntu-mono-dark/pithos-tray-icon.svg']), ('/usr/share/icons/ubuntu-mono-light/apps/16', ['data/icons/ubuntu-mono-light/pithos-tray-icon.svg']), ('/usr/share/appdata', ['data/pithos.appdata.xml']), ('/usr/share/applications', ['data/pithos.desktop']) ] else: data_files = [] setup( name='pithos', version=VERSION, ext_modules=[], license='GPL-3', author='Kevin Mehall', author_email='km@kevinmehall.net', description='Pandora.com client for the GNOME desktop', long_description=read('README.md'), url='http://pithos.github.io', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: End Users/Desktop', 'Topic :: Media', 'License :: OSI Approved :: GPL License', 'Programming Language :: Python', 'Programming Language :: Python :: 3' ], cmdclass={ 'build_doc': BuildDoc }, command_options={ 'build_doc': { 'version': ('setup.py', VERSION), 'release': ('setup.py', VERSION) } }, data_files=data_files, package_data={ 'pithos': [ 'data/ui/*.ui', 'data/ui/*.xml', 'data/media/*.png', 'data/media/*.svg' ] }, packages=find_packages(), include_package_data=True, entry_points={ 'gui_scripts': ['pithos = pithos.pithos:main'] } )