pax_global_header00006660000000000000000000000064144317310560014516gustar00rootroot0000000000000052 comment=8be7afd47861228fd0088484ba91b50039e36318 pithos-1.6.1/000077500000000000000000000000001443173105600130315ustar00rootroot00000000000000pithos-1.6.1/.editorconfig000066400000000000000000000004151443173105600155060ustar00rootroot00000000000000root = true [*] end_of_line = lf insert_final_newline = true charset = utf-8 [{*.py,bin/pithos.in}] indent_style = space indent_size = 4 [*.{ui,xml,xml.in}] indent_style = space indent_size = 2 [{meson.build,meson_options.txt}] indent_style = space indent_size = 2 pithos-1.6.1/.github/000077500000000000000000000000001443173105600143715ustar00rootroot00000000000000pithos-1.6.1/.github/FUNDING.yml000066400000000000000000000000401443173105600162000ustar00rootroot00000000000000github: [TingPing, JasonLG1979] pithos-1.6.1/.github/workflows/000077500000000000000000000000001443173105600164265ustar00rootroot00000000000000pithos-1.6.1/.github/workflows/CI.yml000066400000000000000000000010041443173105600174370ustar00rootroot00000000000000on: push: branches: [master] pull_request: name: CI jobs: flatpak-builder: name: "Flatpak Builder" runs-on: ubuntu-latest container: image: docker.io/bilelmoussaoui/flatpak-github-actions options: --privileged steps: - uses: actions/checkout@v2 with: submodules: 'recursive' - uses: bilelmoussaoui/flatpak-github-actions@v2 with: bundle: "pithos-devel.flatpak" manifest-path: "flatpak/io.github.Pithos.json" run-tests: "true" pithos-1.6.1/.github/workflows/codeql.yml000066400000000000000000000015051443173105600204210ustar00rootroot00000000000000name: "CodeQL" on: push: branches: [ "master" ] pull_request: branches: [ "master" ] schedule: - cron: "0 15 * * 0" jobs: analyze: name: Analyze runs-on: ubuntu-latest permissions: actions: read contents: read security-events: write strategy: fail-fast: false matrix: language: [ python ] steps: - name: Checkout uses: actions/checkout@v3 - name: Initialize CodeQL uses: github/codeql-action/init@v2 with: languages: ${{ matrix.language }} queries: +security-and-quality - name: Autobuild uses: github/codeql-action/autobuild@v2 - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v2 with: category: "/language:${{ matrix.language }}" pithos-1.6.1/.gitignore000066400000000000000000000000501443173105600150140ustar00rootroot00000000000000/build/ /po/*.pot *.tar.xz __pycache__/ pithos-1.6.1/.gitmodules000066400000000000000000000000001443173105600151740ustar00rootroot00000000000000pithos-1.6.1/README.md000066400000000000000000000006261443173105600143140ustar00rootroot00000000000000Pithos ------ 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.6.1/bin/000077500000000000000000000000001443173105600136015ustar00rootroot00000000000000pithos-1.6.1/bin/meson.build000066400000000000000000000010211443173105600157350ustar00rootroot00000000000000prefix = get_option('prefix') cdata = configuration_data() cdata.set('VERSION', meson.project_version()) cdata.set('localedir', join_paths(prefix, get_option('localedir'))) cdata.set('pkgdatadir', join_paths(prefix, pkgdatadir)) configure_file( input: 'pithos.in', output: 'pithos', configuration: cdata, install: true, install_dir: get_option('bindir') ) pithos = join_paths(meson.build_root(), 'bin/pithos') run_target('run', command: [pithos, '-v'], depends: [ pithos_resources, pithos_settings ] ) pithos-1.6.1/bin/pithos.in000077500000000000000000000025661443173105600154530ustar00rootroot00000000000000#!/usr/bin/env python3 import os import sys import locale import gettext from gi.repository import Gio # gst-python changes behavior if installed so just # avoid loading it since we don't require their additions # https://bugzilla.gnome.org/show_bug.cgi?id=736260 sys.modules['gi.overrides.Gst'] = None sys.modules['gi.overrides.GstPbutils'] = None VERSION = '@VERSION@' pkgdatadir = '@pkgdatadir@' localedir = '@localedir@' srcdir = pkgdatadir builddir = os.environ.get('MESON_BUILD_ROOT') if builddir: pkgdatadir = os.path.join(builddir, 'data') localedir = os.path.join(builddir, 'po') srcdir = os.environ.get('MESON_SOURCE_ROOT') os.environ['GSETTINGS_SCHEMA_DIR'] = pkgdatadir sys.dont_write_bytecode = True import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk theme = Gtk.IconTheme.get_default() theme.append_search_path(os.path.join(pkgdatadir, 'icons')) sys.path.insert(1, srcdir) try: locale.bindtextdomain('pithos', localedir) locale.textdomain('pithos') except AttributeError: print("Could not bind to locale translation domain. Some translations won't work") gettext.install('pithos', localedir) resource = Gio.resource_load(os.path.join(pkgdatadir, 'pithos.gresource')) Gio.Resource._register(resource) if __name__ == "__main__": from pithos import application application.main(version=VERSION) pithos-1.6.1/data/000077500000000000000000000000001443173105600137425ustar00rootroot00000000000000pithos-1.6.1/data/gtk/000077500000000000000000000000001443173105600145275ustar00rootroot00000000000000pithos-1.6.1/data/gtk/help-overlay.ui000066400000000000000000000075121443173105600175020ustar00rootroot00000000000000 1 1 Playback 1 space Play/Pause 1 <Primary>Right Skip song 1 <Primary>Up Volume up 1 <Primary>Down Volume down 1 Pandora 1 <Primary>l Love song 1 <Primary>u Unrate song 1 <Primary>b Ban song 1 <Primary>t Tired Song 1 <Primary>d Bookmark song 1 <Primary>i Open song information pithos-1.6.1/data/icons/000077500000000000000000000000001443173105600150555ustar00rootroot00000000000000pithos-1.6.1/data/icons/hicolor/000077500000000000000000000000001443173105600165145ustar00rootroot00000000000000pithos-1.6.1/data/icons/hicolor/48x48/000077500000000000000000000000001443173105600173135ustar00rootroot00000000000000pithos-1.6.1/data/icons/hicolor/48x48/apps/000077500000000000000000000000001443173105600202565ustar00rootroot00000000000000pithos-1.6.1/data/icons/hicolor/48x48/apps/io.github.Pithos-tray.png000066400000000000000000000052541443173105600251040ustar00rootroot00000000000000PNG  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.6.1/data/icons/hicolor/scalable/apps/io.github.Pithos.svg000066400000000000000000001035771443173105600251200ustar00rootroot00000000000000 image/svg+xml pithos-1.6.1/data/icons/hicolor/symbolic/000077500000000000000000000000001443173105600203355ustar00rootroot00000000000000pithos-1.6.1/data/icons/hicolor/symbolic/apps/000077500000000000000000000000001443173105600213005ustar00rootroot00000000000000pithos-1.6.1/data/icons/hicolor/symbolic/apps/io.github.Pithos-symbolic.svg000066400000000000000000000060651443173105600270040ustar00rootroot00000000000000 image/svg+xml pithos-1.6.1/data/icons/meson.build000066400000000000000000000013611443173105600172200ustar00rootroot00000000000000themes = [ ['hicolor', [ ['48x48', [ 'io.github.Pithos-tray.png' ]], ['scalable', [ 'io.github.Pithos-tray.svg', 'io.github.Pithos.svg' ]], ['symbolic', [ 'io.github.Pithos-symbolic.svg' ]] ]], ['ubuntu-mono-dark', [ ['16x16', [ 'io.github.Pithos-tray.svg' ]] ]], ['ubuntu-mono-light', [ ['16x16', [ 'io.github.Pithos-tray.svg' ]] ]] ] foreach i : themes theme = i[0] sizes = i[1] foreach i : sizes size = i[0] icons = i[1] foreach icon : icons install_data('@0@/@1@/apps/@2@'.format(theme, size, icon), install_dir: '@0@/icons/@1@/@2@/apps'.format(get_option('datadir'), theme, size) ) endforeach endforeach endforeach pithos-1.6.1/data/icons/ubuntu-mono-dark/000077500000000000000000000000001443173105600202645ustar00rootroot00000000000000pithos-1.6.1/data/icons/ubuntu-mono-dark/16x16/000077500000000000000000000000001443173105600210515ustar00rootroot00000000000000pithos-1.6.1/data/icons/ubuntu-mono-dark/16x16/apps/000077500000000000000000000000001443173105600220145ustar00rootroot00000000000000pithos-1.6.1/data/icons/ubuntu-mono-dark/16x16/apps/io.github.Pithos-tray.svg000066400000000000000000000053311443173105600266510ustar00rootroot00000000000000 image/svg+xml pithos-1.6.1/data/icons/ubuntu-mono-light/000077500000000000000000000000001443173105600204525ustar00rootroot00000000000000pithos-1.6.1/data/icons/ubuntu-mono-light/16x16/000077500000000000000000000000001443173105600212375ustar00rootroot00000000000000pithos-1.6.1/data/icons/ubuntu-mono-light/16x16/apps/000077500000000000000000000000001443173105600222025ustar00rootroot00000000000000pithos-1.6.1/data/icons/ubuntu-mono-light/16x16/apps/io.github.Pithos-tray.svg000066400000000000000000000050571443173105600270440ustar00rootroot00000000000000 image/svg+xml pithos-1.6.1/data/io.github.Pithos.appdata.xml.in000066400000000000000000000175121443173105600216450ustar00rootroot00000000000000 io.github.Pithos io.github.Pithos.desktop pithos Pithos Pithos Pandora radio client CC0-1.0 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://github.com/pithos/pithos/issues https://github.com/pithos/pithos/wiki/Contributing https://goo.gl/StrKkg https://github.com/pithos/pithos/wiki http://i.imgur.com/2U2ce8v.png Main Window

This is a small bugfix release

  • Fix Python 3.11 support
  • Fix incorrectly labeling very short songs as ads

This is a fairly small release with some UI tweaks and bug fixes

  • Use a headerbar for main window
  • Add Ctrl+r shortcut to open stations popover
  • Remove access to host keyring when in flatpak
  • notification_icon: Remove dependency on libappindicator. StatusNotifier is directly supported but XEmbed trays are no longer supported

This is yet another minor bug fix release.

  • Add Quit to the app menu
  • Remove the limit of 95 stations
  • Handle Enter keypress in stations search
  • Fix app menu keybindings failing to work
  • Fix syntax error on Python 3.8
  • Fix an exception on newer versions of pygobject
  • Fix album art downloads in Flatpak
  • MPRIS: Fix media keys failing to bind on KDE

This is a relatively small release fixing appmenu integration on modern versions of GNOME as well as using more sandbox (Flatpak) friendly APIs. Note that this move may introduce behavior changes on some platforms.

  • Remove appmenu and move into a menu button in the toolbar
  • Fix preference dialog accidentally getting destroyed
  • Notify: Migrate to GNotification
  • MPRIS: Rename name to match app-id (org.mpris.MediaPlayer2.io.github.Pithos)
  • Screensaver Pause: Remove platform specific screensaver support and use GTK's built-in detection

This is a minor release fixing up some bugs:

  • Change default quality to high (mp3)
  • Mark application as DBusActivatable
  • MPRIS: Fix potential unhandled exception
  • Mediakeys: Handle keyboards with a dedicated pause key
  • Mediakeys: Fix support on GNOME-Shell 3.26+ and MATE
  • Notify: Improve behavior on various notification servers

This is a major release with some useful new plugin additions:

  • Add new plugin that inhibits screensaver/suspend during playback
  • Add new plugin adding a 10-band equalizer
  • Add new plugin that automatically normalizes volume between tracks
  • Add help entry (F1) that opens the wiki
  • Replace build system with Meson
  • Automatically detect if the user has Pandora One
  • Improve saving and restoring window position
  • Improve plugin loading performance and error reporting
  • Notification Icon: Improve detecting if a tray is available
  • Notification Icon: Add option to use symbolic icon

This is a minor release with some bug fixes and minor additions:

  • Fix exception on Python 3.6+
  • Add ability to create stations based upon current song/artist
  • Show useful error on renaming Thumbprint Radio
  • Show useful error on creating already existing station
  • Minor buffering improvements
  • Lastfm: Improve preferences and offer to deauthorize account
  • Mpris: Add extension for ratings and remove legacy interface
  • Mediakeys: Fix on future versions of GNOME 3.24.2+
  • Mediakeys: Avoid using keybinder on Wayland (old keybinder would crash)

This is a new major release with numerous improvements:

  • Add support for MPRIS TrackList and PlayList interface
  • Add dynamic rating and cover icons based upon theme colors
  • Add plugin for logging to systemd journal
  • Add symbolic application icon
  • Add man page for pithos
  • Improve handling playlist expiration
  • Improve search in stations list
  • Improve accessibility of UI
  • Improve buffering behavior
  • Improve libsecret support
  • Remove dependency on libnotify
  • Fix disabling keybindings plugin when using keybinder
  • Fix notification icon trying to load on Wayland
  • Fix failure to reconnect on login expiration
  • Fix some plugins not being enabled by default
  • Fix handling error on MPRIS plugin failure
  • Fix migrating configs from < 0.3.18

This is a minor bug fix release just cleaning up a few issues:

  • Show a useful error dialog if no secret service found
  • Improvements to handling login credential changes
  • Fix icon name for main window
  • In plugin notification_icon: Fix visible toggle with AppIndicator going out of sync
  • In plugin mpris: Fix GetCurrentSong() in legacy interface
AppMenu HiDpiIcon ModernToolkit Notifications UserDocs tingping_at_fedoraproject.org
pithos-1.6.1/data/io.github.Pithos.desktop.in000066400000000000000000000003151443173105600210760ustar00rootroot00000000000000[Desktop Entry] Name=Pithos Comment=Play music from Pandora Radio Keywords=Music; Categories=GNOME;AudioVideo;Player; Exec=pithos Icon=io.github.Pithos Terminal=false Type=Application DBusActivatable=true pithos-1.6.1/data/io.github.Pithos.gresource.xml000066400000000000000000000011211443173105600216110ustar00rootroot00000000000000 gtk/help-overlay.ui ui/PithosWindow.ui ui/AboutPithosDialog.ui ui/PreferencesPithosDialog.ui ui/SearchDialog.ui ui/StationsDialog.ui ui/EqDialog.ui pithos-1.6.1/data/io.github.Pithos.gschema.xml000066400000000000000000000057761443173105600212460ustar00rootroot00000000000000 "" Email address for Pandora account false If account has subscribed to Pandora One false Sort the stations list in the popup is sorted alphabetically "" ID of last station played "" Proxy address for all connections "" Proxy address for pandora connection (not data) "" Address to PAC "" Custom JSON to send to Pandora for client info (0,0) Position of window 0.7 Volume of player "highQuality" Quality of songs false If the plugin is loaded "" Custom data set by plugin true If the plugin is loaded "" Custom data set by plugin pithos-1.6.1/data/io.github.Pithos.service.in000066400000000000000000000001221443173105600210610ustar00rootroot00000000000000[D-BUS Service] Name=io.github.Pithos Exec=@bindir@/pithos --gapplication-service pithos-1.6.1/data/meson.build000066400000000000000000000044301443173105600161050ustar00rootroot00000000000000gnome = import('gnome') bindir = join_paths(get_option('prefix'), get_option('bindir')) service_conf = configuration_data() service_conf.set('bindir', bindir) configure_file( input: 'io.github.Pithos.service.in', output: 'io.github.Pithos.service', configuration: service_conf, install: true, install_dir: join_paths(get_option('datadir'), 'dbus-1/services') ) pithos_resources = gnome.compile_resources('pithos', 'io.github.Pithos.gresource.xml', gresource_bundle: true, install: true, install_dir: pkgdatadir ) install_data('io.github.Pithos.gschema.xml', install_dir: join_paths(get_option('datadir'), 'glib-2.0/schemas') ) pithos_desktop = i18n.merge_file( input: 'io.github.Pithos.desktop.in', output: 'io.github.Pithos.desktop', type: 'desktop', po_dir: '../po', install: true, install_dir: join_paths(get_option('datadir'), 'applications') ) pithos_appstream = i18n.merge_file( input: 'io.github.Pithos.appdata.xml.in', output: 'io.github.Pithos.appdata.xml', po_dir: '../po', install: true, install_dir: join_paths(get_option('datadir'), 'metainfo') ) pithos_settings = gnome.compile_schemas() appstream_util = find_program('appstream-util', required: false) if appstream_util.found() test('Validate appstream file', appstream_util, args: ['validate', '--nonet', pithos_appstream] ) endif desktop_utils = find_program('desktop-file-validate', required: false) if desktop_utils.found() test('Validate desktop file', desktop_utils, args: [pithos_desktop] ) endif compile_schemas = find_program('glib-compile-schemas', required: false) if compile_schemas.found() test('Validate schema file', compile_schemas, args: ['--strict', '--dry-run', meson.current_source_dir()] ) endif gtk_builder_tool = find_program('gtk-builder-tool', required: false) if gtk_builder_tool.found() ui_files = [ ['ui', 'AboutPithosDialog.ui'], ['ui', 'PithosWindow.ui'], ['ui', 'PreferencesPithosDialog.ui'], ['ui', 'SearchDialog.ui'], ['ui', 'StationsDialog.ui'], ['ui', 'EqDialog.ui'], ['gtk', 'help-overlay.ui'], ] foreach ui_file : ui_files test('Validate @0@'.format(ui_file[1]), gtk_builder_tool, args: ['validate', join_paths(meson.current_source_dir(), ui_file[0], ui_file[1])] ) endforeach endif subdir('icons') pithos-1.6.1/data/ui/000077500000000000000000000000001443173105600143575ustar00rootroot00000000000000pithos-1.6.1/data/ui/AboutPithosDialog.ui000066400000000000000000000014251443173105600203010ustar00rootroot00000000000000 pithos-1.6.1/data/ui/EqDialog.ui000066400000000000000000000552211443173105600164100ustar00rootroot00000000000000 -24 12 0.10000000000000001 0.10000000000000001 -24 12 0.10000000000000001 0.10000000000000001 -24 12 0.10000000000000001 0.10000000000000001 -24 12 0.10000000000000001 0.10000000000000001 -24 12 0.10000000000000001 0.10000000000000001 -24 12 0.10000000000000001 0.10000000000000001 -24 12 0.10000000000000001 0.10000000000000001 -24 12 0.10000000000000001 0.10000000000000001 -24 12 0.10000000000000001 0.10000000000000001 -24 12 0.10000000000000001 0.10000000000000001 pithos-1.6.1/data/ui/PithosWindow.ui000066400000000000000000000444451443173105600173670ustar00rootroot00000000000000
app.stations _Stations
app.preferences _Preferences win.show-help-overlay _Keyboard Shortcuts app.help _Help F1 app.about _About
app.quit _Quit
100 1 10 10 1 PithosWindow error Pithos Upgrade Required Pithos needs to be updated for compatibility with Pandora's latest changes. 1 Get Help Online 1 Quit 1 1 button_help button_quit 1 PithosWindow error Error Cancel 1 Retry 1 Preferences 1 1 button_cancel button_retry button_preferences 1 1 PithosWindow error Error Quit 1 1 button-error-quit 1 1 Song _Info... 1 1 _Love Song 1 1 _Unlove Song 1 1 _Ban Song 1 1 _Unban Song 1 1 Don't play song for a month _Tired of this song 1 1 Create a New Station 1 1 Based on this Song 1 Based on this Artist 1 Bookmark 1 1 Song 1 Artist
pithos-1.6.1/data/ui/PreferencesPithosDialog.ui000066400000000000000000000447501443173105600215000ustar00rootroot00000000000000 pithos-1.6.1/data/ui/SearchDialog.ui000066400000000000000000000067751443173105600172620ustar00rootroot00000000000000 pithos-1.6.1/data/ui/StationsDialog.ui000066400000000000000000000112461443173105600176460ustar00rootroot00000000000000 StationsDialog warning Yes 1 1 No 1 button_no button_yes 1 Listen Now 1 Info 1 Rename 1 Delete pithos-1.6.1/docs/000077500000000000000000000000001443173105600137615ustar00rootroot00000000000000pithos-1.6.1/docs/conf.py000066400000000000000000000164521443173105600152700ustar00rootroot00000000000000#!/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 = 'alabaster' # 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.6.1/docs/index.rst000066400000000000000000000013671443173105600156310ustar00rootroot00000000000000.. 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.6.1/docs/meson.build000066400000000000000000000015161443173105600161260ustar00rootroot00000000000000sphinx_build = find_program(['sphinx-build-3', 'sphinx-build'], required: false) if sphinx_build.found() custom_target('Pithos docs', output: ['html'], command: [ sphinx_build, meson.current_source_dir(), '@OUTPUT@' ], # https://github.com/mesonbuild/meson/issues/1942 # build_always: true ) endif help2man = find_program('help2man', required: false) if help2man.found() # Target only for maintainers custom_target('Pithos man page', depend_files: files('../pithos/application.py'), output: 'pithos.1', # TODO: Output into source dir.. command: [ # https://github.com/mesonbuild/meson/issues/266 'env', 'MESON_SOURCE_ROOT=' + meson.source_root(), 'MESON_BUILD_ROOT=' + meson.build_root(), help2man, '--no-info', '--output=@OUTPUT@', pithos ] ) endif install_man('pithos.1') pithos-1.6.1/docs/pithos.1000066400000000000000000000015121443173105600153500ustar00rootroot00000000000000.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.14. .TH PITHOS "1" "October 2020" "Pithos 1.5.1" "User Commands" .SH NAME Pithos \- manual page for Pithos 1.5.1 .SH DESCRIPTION .SS "Usage:" .IP pithos [OPTION\&.] .SS "Help Options:" .TP \fB\-h\fR, \fB\-\-help\fR Show help options .TP \fB\-\-help\-all\fR Show all help options .TP \fB\-\-help\-gapplication\fR Show GApplication options .TP \fB\-\-help\-gtk\fR Show GTK+ Options .SS "Application Options:" .TP \fB\-v\fR, \fB\-\-verbose\fR Show info messages .TP \fB\-d\fR, \fB\-\-debug\fR Show debug messages .TP \fB\-t\fR, \fB\-\-test\fR Use a mock service instead of connecting to the real Pandora server .TP \fB\-\-version\fR Show the version .TP \fB\-\-last\-logs\fR Show the logs for Pithos since the last reboot .TP \fB\-\-display\fR=\fI\,DISPLAY\/\fR X display to use pithos-1.6.1/flatpak/000077500000000000000000000000001443173105600144535ustar00rootroot00000000000000pithos-1.6.1/flatpak/io.github.Pithos.json000066400000000000000000000022121443173105600205000ustar00rootroot00000000000000{ "app-id": "io.github.Pithos", "runtime": "org.gnome.Platform", "runtime-version": "41", "sdk": "org.gnome.Sdk", "command": "pithos", "finish-args": [ "--share=ipc", "--share=network", "--socket=fallback-x11", "--socket=x11", "--socket=wayland", "--socket=pulseaudio", "--metadata=X-DConf=migrate-path=/io/github/Pithos/", "--talk-name=org.gnome.SettingsDaemon.MediaKeys", "--talk-name=org.mate.SettingsDaemon", "--talk-name=org.kde.StatusNotifierWatcher" ], "modules": [ "python3-pylast.json", { "name": "keybinder", "cleanup": ["/lib/*.la", "/include", "/share", "/lib/pkgconfig"], "sources": [{ "type": "archive", "url": "https://github.com/kupferlauncher/keybinder/releases/download/keybinder-3.0-v0.3.2/keybinder-3.0-0.3.2.tar.gz", "sha256": "e6e3de4e1f3b201814a956ab8f16dfc8a262db1937ff1eee4d855365398c6020" }] }, { "name": "pithos", "builddir": true, "buildsystem": "meson", "cleanup": ["/share/man"], "sources": [ { "type": "dir", "path": "../" } ] } ] } pithos-1.6.1/flatpak/python3-pylast.json000066400000000000000000000014201443173105600202610ustar00rootroot00000000000000{ "name": "python3-pylast", "buildsystem": "simple", "build-commands": [ "pip3 install --no-index --find-links=\"file://${PWD}\" --prefix=${FLATPAK_DEST} pylast" ], "sources": [ { "type": "file", "url": "https://files.pythonhosted.org/packages/16/d8/bc6316cf98419719bd59c91742194c111b6f2e85abac88e496adefaf7afe/six-1.11.0.tar.gz", "sha256": "70e8a77beed4562e7f14fe23a786b54f6296e34344c23bc42f07b15018ff98e9" }, { "type": "file", "url": "https://files.pythonhosted.org/packages/8a/1a/ece4ef4ebf51236ac25e9708fb3e1e70b6447e01262f8b156ccbda894fa9/pylast-2.2.0.tar.gz", "sha256": "a21a10e559cbb80db5eb72e20a22740496a292977ed3568c937560b8d6885ab4" } ] }pithos-1.6.1/license000066400000000000000000001045061443173105600144040ustar00rootroot00000000000000 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.6.1/meson.build000066400000000000000000000005001443173105600151660ustar00rootroot00000000000000project('pithos', version: '1.6.1', meson_version: '>= 0.50.0' ) i18n = import('i18n') pkgdatadir = join_paths(get_option('datadir'), meson.project_name()) install_subdir('pithos', install_dir: pkgdatadir) subdir('data') subdir('bin') subdir('docs') subdir('po') meson.add_install_script('meson_post_install.py') pithos-1.6.1/meson_post_install.py000066400000000000000000000013521443173105600173200ustar00rootroot00000000000000#!/usr/bin/env python3 from compileall import compile_dir from os import environ, path from subprocess import call prefix = environ.get('MESON_INSTALL_PREFIX', '/usr/local') datadir = path.join(prefix, 'share') destdir = environ.get('DESTDIR', '') # Package managers set this so we don't need to run if not destdir: print('Updating icon cache...') for theme in ('hicolor', 'ubuntu-mono-dark', 'ubuntu-mono-light'): call(['gtk-update-icon-cache', '-qtf', path.join(datadir, 'icons', theme)]) print('Compiling GSettings schemas...') call(['glib-compile-schemas', path.join(datadir, 'glib-2.0', 'schemas')]) print('Compiling python bytecode...') compile_dir(destdir + path.join(datadir, 'pithos', 'pithos'), optimize=2) pithos-1.6.1/pithos/000077500000000000000000000000001443173105600143375ustar00rootroot00000000000000pithos-1.6.1/pithos/AboutPithosDialog.py000066400000000000000000000021541443173105600202740ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- # 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 . from gi.repository import Gtk @Gtk.Template(resource_path='/io/github/Pithos/ui/AboutPithosDialog.ui') class AboutPithosDialog(Gtk.AboutDialog): __gtype_name__ = "AboutPithosDialog" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.init_template() theme = Gtk.IconTheme.get_default() self.set_logo(theme.load_icon('io.github.Pithos', 96, 0)) pithos-1.6.1/pithos/PreferencesPithosDialog.py000066400000000000000000000175341443173105600214730ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- # 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 . import logging from gi.repository import Gio, Gtk, GObject, Pango from .util import SecretService try: import pacparser except ImportError: pacparser = None logging.info("Could not import python-pacparser.") class PithosPluginRow(Gtk.ListBoxRow): def __init__(self, plugin): super().__init__() self.plugin = plugin self._friendly_name = plugin.name.title().replace('_', ' ') box = Gtk.Box() label = Gtk.Label() label.set_markup('{}\n{}'.format(self._friendly_name, 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() plugin.settings.bind('enabled', self.switch, 'active', Gio.SettingsBindFlags.DEFAULT) self.switch.connect('notify::active', self.on_activated) self.switch.set_valign(Gtk.Align.CENTER) box.pack_end(self.switch, False, False, 2) self.connect('grab-focus', self.set_prefs_btn) self.plugin.connect('notify::enabled', self.on_enabled) if plugin.prepared and plugin.error: self.set_sensitive(False) self.set_tooltip_text(plugin.error) self.add(box) def on_enabled(self, *ignore): if self.is_selected(): self.set_prefs_btn() def set_prefs_btn(self, *ignore): prefs_btn = self.get_toplevel().preference_btn if self.plugin.enabled: sensitive = self.plugin.preferences_dialog is not None else: sensitive = False prefs_btn.set_sensitive(sensitive) if sensitive: tooltip = _('Click to change the {} plugin\'s settings.'.format(self._friendly_name)) else: tooltip = _('This plugin either must be enabled or does not support preferences.') prefs_btn.set_tooltip_text(tooltip) 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.set_prefs_btn() @Gtk.Template(resource_path='/io/github/Pithos/ui/PreferencesPithosDialog.ui') class PreferencesPithosDialog(Gtk.Dialog): __gtype_name__ = "PreferencesPithosDialog" __gsignals__ = { 'login-changed': (GObject.SignalFlags.RUN_FIRST, None, (GObject.TYPE_PYOBJECT,)), } preference_btn = Gtk.Template.Child() plugins_listbox = Gtk.Template.Child() email_entry = Gtk.Template.Child() password_entry = Gtk.Template.Child() audio_quality_combo = Gtk.Template.Child() proxy_entry = Gtk.Template.Child() control_proxy_entry = Gtk.Template.Child() control_proxy_pac_entry = Gtk.Template.Child() explicit_content_filter_checkbutton = Gtk.Template.Child() def __init__(self, *args, **kwargs): super().__init__(*args, use_header_bar=1, **kwargs) self.init_template() self.last_password = None self.settings = Gio.Settings.new('io.github.Pithos') if not pacparser: self.control_proxy_pac_entry.set_sensitive(False) self.control_proxy_pac_entry.set_tooltip_text("Please install python-pacparser") settings_mapping = { 'email': (self.email_entry, 'text'), 'proxy': (self.proxy_entry, 'text'), 'control-proxy': (self.control_proxy_entry, 'text'), 'control-proxy-pac': (self.control_proxy_pac_entry, 'text'), 'audio-quality': (self.audio_quality_combo, 'active-id'), } for key, val in settings_mapping.items(): self.settings.bind(key, val[0], val[1], Gio.SettingsBindFlags.DEFAULT|Gio.SettingsBindFlags.NO_SENSITIVITY) def set_plugins(self, plugins): self.plugins_listbox.set_header_func(self.on_listbox_update_header) for plugin in plugins.values(): row = PithosPluginRow(plugin) self.plugins_listbox.add(row) self.plugins_listbox.show_all() @Gtk.Template.Callback() def on_plugins_row_selected(self, box, row): if row: self.preference_btn.set_sensitive(row.plugin.preferences_dialog is not None) @Gtk.Template.Callback() def on_prefs_btn_clicked(self, btn): dialog = self.plugins_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() @Gtk.Template.Callback() def on_account_changed(self, *ignore): if not self.email_entry.get_text() or not self.password_entry.get_text(): self.set_response_sensitive(Gtk.ResponseType.APPLY, False) else: self.set_response_sensitive(Gtk.ResponseType.APPLY, True) 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)) @Gtk.Template.Callback() def on_show(self, widget): def cb(password): self.last_password = password self.password_entry.set_text(password) self.settings.delay() self.on_account_changed() self.last_email = self.settings['email'] SecretService.get_account_password(self.last_email, cb) @Gtk.Template.Callback() def on_delete_event(self, *ignore): self.hide() self.settings.revert() return True def do_response(self, response_id): if response_id == Gtk.ResponseType.APPLY: def cb(success): if success: self.settings.apply() self.emit('login-changed', (email, password)) else: # Should never really ever happen... # But just in case. self.settings.revert() self.show() dialog = Gtk.MessageDialog( parent=self, flags=Gtk.DialogFlags.MODAL, type=Gtk.MessageType.WARNING, buttons=Gtk.ButtonsType.OK, text=_('Failed to Store Your Pandora Credentials'), secondary_text=_('Please re-enter your email and password.'), ) dialog.connect('response', lambda *ignore: dialog.destroy()) dialog.show() email = self.email_entry.get_text() password = self.password_entry.get_text() if self.last_email != email or self.last_password != password: SecretService.set_account_password(self.last_email, email, password, cb) else: self.settings.apply() else: self.settings.revert() pithos-1.6.1/pithos/SearchDialog.py000066400000000000000000000050511443173105600172370ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- # 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 . import html from gi.repository import GObject, Gtk @Gtk.Template(resource_path='/io/github/Pithos/ui/SearchDialog.ui') class SearchDialog(Gtk.Dialog): __gtype_name__ = "SearchDialog" entry = Gtk.Template.Child() treeview = Gtk.Template.Child() def __init__(self, *args, **kwargs): self.worker_run = kwargs["worker"] del kwargs["worker"] super().__init__(*args, use_header_bar=1, **kwargs) self.init_template() self.model = Gtk.ListStore(GObject.TYPE_PYOBJECT, str) self.treeview.set_model(self.model) self.query = '' self.result = None @Gtk.Template.Callback() def search_clicked(self, widget): self.search(self.entry.get_text()) 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 search(self, query): self.query = query self.model.clear() if not self.query: return def callback(results): self.model.clear() if not self.query: return for i in results: if i.resultType == 'song': mk = '{} by {}'.format(html.escape(i.title), html.escape(i.artist)) elif i.resultType == 'artist': mk = '{} (artist)'.format(html.escape(i.name)) elif i.resultType == 'genre': mk = '{} (genre)'.format(html.escape(i.stationName)) self.model.append((i, mk)) self.treeview.show() self.worker_run('search', (self.query,), callback, "Searching...") def cursor_changed(self, *ignore): self.result = self.get_selected() self.set_response_sensitive(Gtk.ResponseType.OK, not not self.result) pithos-1.6.1/pithos/StationsDialog.py000066400000000000000000000231261443173105600176410ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- # 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 . import html import logging from gi.repository import Gtk, GObject from .util import open_browser, popup_at_pointer from . import SearchDialog @Gtk.Template(resource_path='/io/github/Pithos/ui/StationsDialog.ui') class StationsDialog(Gtk.Dialog): __gtype_name__ = "StationsDialog" __gsignals__ = { "station-renamed": (GObject.SignalFlags.RUN_FIRST, None, (GObject.TYPE_PYOBJECT,)), "station-added": (GObject.SignalFlags.RUN_FIRST, None, (GObject.TYPE_PYOBJECT,)), "station-removed": (GObject.SignalFlags.RUN_FIRST, None, (GObject.TYPE_PYOBJECT,)), } treeview = Gtk.Template.Child() delete_confirm_dialog = Gtk.Template.Child() station_menu = Gtk.Template.Child() def __init__(self, pithos, *args, **kwargs): super().__init__(*args, use_header_bar=1, **kwargs) self.init_template() 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() def visible_func(m, i, d): return m.get_value(i, 0) and not (m.get_value(i, 0).isQuickMix or m.get_value(i, 0).isThumbprint) self.modelfilter.set_visible_func(visible_func) self.modelsortable = Gtk.TreeModelSort.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.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) 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] old_station_name = station.name def errorback(e): self.pithos.statusbar.pop(self.pithos.statusbar.get_context_id('net')) if hasattr(e, 'status') and e.status == 1008: dialog = Gtk.MessageDialog( parent=self, flags=Gtk.DialogFlags.MODAL, type=Gtk.MessageType.WARNING, buttons=Gtk.ButtonsType.OK, text='Could Not Rename {}'.format(old_station_name), secondary_text='Pandora does not permit renaming {}.'.format(old_station_name), ) dialog.connect('response', lambda *ignore: dialog.destroy()) dialog.show() elif hasattr(e, 'message') and hasattr(e, 'submsg'): self.window.error_dialog(e.message, None, submsg=e.submsg) else: logging.warning(e.traceback) self.model[self.modelfilter.convert_path_to_child_path(Gtk.TreePath(path))][1] = old_station_name def success(*ignore): self.emit('station-renamed', (station.id, new_text)) self.worker_run( station.rename, (new_text,), callback=success, errorback=errorback, 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) 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) popup_at_pointer(self.station_menu, event) return True @Gtk.Template.Callback() def on_menuitem_listen(self, widget): station = self.selected_station() self.pithos.station_changed(station) self.hide() @Gtk.Template.Callback() def on_menuitem_info(self, widget): open_browser(self.selected_station().info_url, parent=self) @Gtk.Template.Callback() 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) @Gtk.Template.Callback() def on_menuitem_delete(self, widget): station = self.selected_station() dialog = self.delete_confirm_dialog dialog.set_property('text', 'Are you sure you want to delete the station "{}"?'.format(station.name)) response = dialog.run() dialog.hide() if response == Gtk.ResponseType.YES: self.worker_run(station.delete, context='net', message="Deleting Station...") self.pithos.remove_station(station) if self.pithos.current_station is station: self.pithos.station_changed(self.model[0][0]) self.emit('station-removed', station) @Gtk.Template.Callback() def add_station(self, widget): if self.searchDialog: self.searchDialog.present() else: self.searchDialog = SearchDialog.SearchDialog(worker=self.worker_run, transient_for=self) self.searchDialog.show_all() self.searchDialog.connect("response", self.add_station_cb) @Gtk.Template.Callback() def refresh_stations(self, widget): self.pithos.refresh_stations(self.pithos) def add_station_cb(self, dialog, response): result = dialog.result if result is not None: if result.resultType == 'song': description = '{} by {}'.format(html.escape(result.title), html.escape(result.artist)) elif result.resultType == 'artist': description = html.escape(result.name) else: description = html.escape(result.stationName) user_data = result.resultType, description logging.info("in add_station_cb {} {}".format(result, response)) if response == Gtk.ResponseType.OK: self.worker_run( "add_station_by_music_id", (result.musicId,), self.station_added, "Creating station...", user_data=user_data, ) dialog.hide() dialog.destroy() self.searchDialog = None def station_added(self, station, user_data): music_type, description = user_data for existing_station in self.model: if existing_station[0].id == station.id: self.pithos.station_already_exists(existing_station[0], description, music_type, self) return logging.debug("1 " + repr(station)) # We shouldn't actually add the station to the pandora stations list # until we know it's not a duplicate. self.pithos.pandora.stations.append(station) it = self.model.insert_with_valuesv(0, (0, 1, 2), (station, station.name, 0)) logging.debug("2 " + repr(it)) self.emit('station-added', station) self.pithos.station_changed(station) logging.debug("3 ") self.modelfilter.refilter() logging.debug("4") self.treeview.set_cursor(0) logging.debug("5 ") @Gtk.Template.Callback() 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 pithos-1.6.1/pithos/StationsPopover.py000066400000000000000000000146431443173105600201000ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- # Copyright (C) 2015 Patrick Griffis # # 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 . import logging from gi.repository import GLib, Gio, Gtk, Gdk, Pango from .util import open_browser, popup_at_pointer class StationsPopover(Gtk.Popover): __gtype_name__ = "StationsPopover" def __init__(self): super().__init__() box2 = Gtk.Box() self.search = Gtk.SearchEntry(can_default=True, placeholder_text=_('Search stations…')) self.sorted = False self.sort = Gtk.ToggleButton.new() self.sort.get_accessible().props.accessible_description = _('sort button') self.sort.add(Gtk.Image.new_from_icon_name("view-sort-ascending-symbolic", Gtk.IconSize.BUTTON)) self.sort.connect("toggled", self.sort_changed) box2.pack_start(self.search, True, True, 0) box2.add(self.sort) self.listbox = Gtk.ListBox() self.listbox.connect('button-press-event', self.on_button_press) self.listbox.connect('row-activated', self.on_row_activated) self.listbox.set_sort_func(self.listbox_sort) self.listbox.set_header_func(self.listbox_header) sw = Gtk.ScrolledWindow() sw.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC) sw.set_size_request(-1, 200) sw.add(self.listbox) self.search.connect("search-changed", self.search_changed) self.listbox.set_filter_func(self.listbox_filter, self.search) box = Gtk.Box.new(Gtk.Orientation.VERTICAL, 0) box.props.margin = 3 box.pack_start(box2, True, False, 3) box.pack_start(sw, True, True, 0) settings = Gio.Settings.new('io.github.Pithos') settings.bind('sort-stations', self.sort, 'active', Gio.SettingsBindFlags.DEFAULT) box.show_all() self.add(box) def on_button_press(self, widget, event): def open_info(item, station): open_browser(station.info_url, parent=self.get_toplevel(), timestamp=event.time) if event.button != Gdk.BUTTON_SECONDARY: return False row = self.listbox.get_row_at_y(event.y) if not row: return False item = Gtk.MenuItem.new_with_label('Station Info…') item.connect('activate', open_info, row.station) item.show() menu = Gtk.Menu.new() menu.append(item) menu.attach_to_widget(widget) popup_at_pointer(menu, event) return True def on_row_activated(self, listbox, row): self.hide() self.search.set_text('') def sort_changed(self, widget): self.sorted = widget.get_active() self.listbox.invalidate_sort() def search_changed(self, entry): self.listbox.invalidate_filter() def listbox_header(self, row, before): if before and before.station.isThumbprint and not row.get_header(): row.set_header(Gtk.Separator.new(Gtk.Orientation.HORIZONTAL)) elif row.get_header(): row.set_header(None) def listbox_filter(self, row, entry): search_text = entry.get_text().lower() if search_text == '': return True station_name = row.station.name.lower() if station_name.startswith(search_text): return True for word in station_name.split(): if word.startswith(search_text): return True return False def listbox_sort(self, row1, row2): if row1.station.isQuickMix or row1.station.isThumbprint: # Always first return -1 if not self.sorted: # This is the order Pandora lists it (aka create date) if row1.index < row2.index: return -1 else: return 1 else: return GLib.ascii_strcasecmp(row1.name, row2.name) def insert_row(self, model, path, iter): station, name, index = model.get(iter, 0, 1, 2) row = StationListBoxRow(station, name, index) row.show_all() self.listbox.add(row) def change_row(self, model, path, iter, data=None): station, name, index = model.get(iter, 0, 1, 2) for row in self.listbox.get_children(): if row.station == station: row.name, row.index = name, index self.listbox.invalidate_sort() break else: logging.warning('Row changed on unknown station') def clear(self): for row in self.listbox.get_children(): row.destroy() def toggle_visibility(self, *ignore): if self.props.visible: self.hide() else: self.show_all() def set_model(self, model): model.connect('row-inserted', self.insert_row) model.connect('row-changed', self.change_row) def select_station(self, station): for row in self.listbox.get_children(): if row.station == station: self.listbox.select_row(row) break def remove_station(self, station): for row in self.listbox.get_children(): if row.station == station: self.listbox.remove(row) break class StationListBoxRow(Gtk.ListBoxRow): def __init__(self, station, name, index): super().__init__() self.station = station self.index = index box = Gtk.Box() self.label = Gtk.Label() self.label.set_alignment(0, .5) self.label.set_ellipsize(Pango.EllipsizeMode.END) self.label.set_max_width_chars(15) self.label.set_text(name) box.pack_start(self.label, True, True, 0) # TODO: Modify quickmix from here self.add(box) @property def name(self): return self.label.get_text() @name.setter def name(self, name): self.label.set_text(name) pithos-1.6.1/pithos/__init__.py000066400000000000000000000000001443173105600164360ustar00rootroot00000000000000pithos-1.6.1/pithos/__main__.py000066400000000000000000000000541443173105600164300ustar00rootroot00000000000000from pithos.application import main main() pithos-1.6.1/pithos/application.py000066400000000000000000000176601443173105600172260ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- # 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 . import os import sys import signal import logging import gi gi.require_version('Gtk', '3.0') from gi.repository import GLib, Gio, Gtk from .pithos import PithosWindow from .util import open_browser class PithosApplication(Gtk.Application): __gtype_name__ = 'PithosApplication' def __init__(self, version=''): super().__init__(application_id='io.github.Pithos', flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE) if hasattr(self.props, 'register_session'): self.props.register_session = True # 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 = [] os.environ['PULSE_PROP_application.name'] = 'Pithos' os.environ['PULSE_PROP_application.id'] = 'io.github.Pithos' os.environ['PULSE_PROP_application.version'] = version os.environ['PULSE_PROP_application.icon_name'] = 'io.github.Pithos' os.environ['PULSE_PROP_media.role'] = 'music' self.window = None self.test_mode = False self.version = version self.add_main_option('verbose', ord('v'), GLib.OptionFlags.NONE, GLib.OptionArg.NONE, _('Show info messages'), None) self.add_main_option('debug', ord('d'), GLib.OptionFlags.NONE, GLib.OptionArg.NONE, _('Show debug messages'), None) self.add_main_option('test', ord('t'), GLib.OptionFlags.NONE, GLib.OptionArg.NONE, _('Use a mock service instead of connecting to the real Pandora server'), None) self.add_main_option('version', 0, GLib.OptionFlags.NONE, GLib.OptionArg.NONE, _('Show the version'), None) self.add_main_option('last-logs', 0, GLib.OptionFlags.NONE, GLib.OptionArg.NONE, _('Show the logs for Pithos since the last reboot'), None) def do_startup(self): Gtk.Application.do_startup(self) signal.signal(signal.SIGINT, signal.SIG_DFL) action = Gio.SimpleAction.new("stations", None) action.connect("activate", self.stations_cb) self.add_action(action) self.set_accels_for_action('app.stations', ['s']) action = Gio.SimpleAction.new("preferences", None) action.connect("activate", self.prefs_cb) self.add_action(action) self.set_accels_for_action('app.preferences', ['p']) action = Gio.SimpleAction.new("help", None) action.connect("activate", self.help_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) self.set_accels_for_action('app.quit', ['q']) action = Gio.SimpleAction.new("next-song", None) action.connect("activate", lambda action, param: self.window.next_song()) self.add_action(action) # Needed for notifications to function as expected in KDE. action = Gio.SimpleAction.new("activate", None) action.connect("activate", lambda action, param: self.activate()) self.add_action(action) def do_command_line(self, command_line): options = command_line.get_options_dict() # Show the Pithos log since last reboot and exit if options.contains('last-logs'): try: from systemd import journal from os.path import basename except ImportError: self._print(command_line, _('Systemd Python module not found')) return 1 # We want the version also since the logging plugin misses # logging messages before it's enabled. self._print(command_line, 'Pithos {}'.format(self.version)) reader = journal.Reader() reader.this_boot() reader.add_match(SYSLOG_IDENTIFIER='io.github.Pithos') _PRIORITY_TO_LEVEL = { journal.LOG_DEBUG: 'DEBUG', journal.LOG_INFO: 'INFO', journal.LOG_WARNING: 'WARNING', journal.LOG_ERR: 'ERROR', journal.LOG_CRIT: 'CRTICIAL', journal.LOG_ALERT: 'ALERT', } got_logs = False for entry in reader: try: got_logs = True level = _PRIORITY_TO_LEVEL[entry['PRIORITY']] line = entry['CODE_LINE'] function = entry['CODE_FUNC'] module = basename(entry['CODE_FILE'])[:-3] message = entry['MESSAGE'] except KeyError: self._print(command_line, _('Error Reading log entry, printing complete entry')) log_line = '\n'.join(('{}: {}'.format(k, v) for k, v in entry.items())) else: log_line = '{} - {}:{}:{} - {}'.format(level, module, function, line, message) self._print(command_line, log_line) if not got_logs: self._print(command_line, _('No logs for Pithos present for this boot.')) return 0 # Show the version on local instance and exit if options.contains('version'): self._print(command_line, 'Pithos {}'.format(self.version)) return 0 # Set the logging level to show debug messages if options.contains('debug'): log_level = logging.DEBUG elif options.contains('verbose'): log_level = logging.INFO else: log_level = logging.WARN stream = logging.StreamHandler() stream.setLevel(log_level) stream.setFormatter(logging.Formatter(fmt='%(levelname)s - %(module)s:%(funcName)s:%(lineno)d - %(message)s')) logging.basicConfig(level=logging.NOTSET, handlers=[stream]) self.test_mode = options.lookup_value('test') self.do_activate() return 0 @staticmethod def _print(command_line, string): # Workaround broken pygobject bindings type(command_line).do_print_literal(command_line, string + '\n') def do_activate(self): if not self.window: logging.info('Pithos {}'.format(self.version)) self.window = PithosWindow(self, self.test_mode) self.window.present() def do_shutdown(self): Gtk.Application.do_shutdown(self) if self.window: self.window.destroy() def stations_cb(self, action, param): self.window.show_stations() def prefs_cb(self, action, param): self.window.show_preferences() def help_cb(self, action, param): open_browser("https://github.com/pithos/pithos/wiki", self.window) def about_cb(self, action, param): self.window.show_about(self.version) def quit_cb(self, action, param): self.window.destroy() def main(version=''): app = PithosApplication(version=version) exit_status = app.run(sys.argv) sys.exit(exit_status) if __name__ == '__main__': main() pithos-1.6.1/pithos/gobject_worker.py000066400000000000000000000041471443173105600177250ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- # 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 . import logging import threading from gi.repository import GLib import traceback class GObjectWorker: def send(self, command, args=(), callback=None, errorback=None): def run(data): command, args, callback, errorback = data 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) if errorback is None: errorback = self._default_errorback data = command, args, callback, errorback thread = threading.Thread(target=run, args=(data,)) thread.daemon = True thread.start() 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.6.1/pithos/migrate_settings.py000066400000000000000000000061311443173105600202620ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- # Copyright (C) 2015 Patrick Griffis # 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 . import os import logging from gi.repository import GLib, Gio from .util import SecretService def _get_plugin_settings(name): return Gio.Settings.new_with_path('io.github.Pithos.plugin', '/io/github/Pithos/{}/'.format(name)) def maybe_migrate_settings(): config_file = os.path.join(GLib.get_user_config_dir(), 'pithos.ini') prefs = {} try: with open(config_file) as 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 prefs[key] = val except IOError: logging.debug('Not migrating old config') return migration_map = { 'username': 'email', } plugin_migration = { 'notify': 'notify', 'enable_screesaverpause': 'screensaver_pause', 'show_icon': 'notification_icon', } ignore_migration = ( 'unsafe_permissions', 'x_pos', 'y_pos', 'audio_format' # Pre 0.3.18 ) settings = Gio.Settings.new('io.github.Pithos') for key, val in prefs.items(): logging.debug('migrating {}: {}'.format(key, val)) if not val: continue if key in ignore_migration: continue if key == 'lastfm_key' and val: s = _get_plugin_settings('lastfm') s.set_string('data', val) elif key in migration_map: settings.set_string(migration_map[key], val) elif key in plugin_migration: s = _get_plugin_settings(plugin_migration[key]) s.set_boolean('enabled', val) elif key.startswith('enable_'): s = _get_plugin_settings(key[7:]) s.set_boolean('enabled', val) elif key == 'password': if 'username' in prefs: SecretService.set_account_password(None, prefs['username'], val, None) elif key == 'volume': settings.set_double(key, float(val)) else: key = key.replace('_', '-') if isinstance(val, bool): settings.set_boolean(key, val) else: settings.set_string(key, val) os.remove(config_file) logging.debug('Migrated old config') pithos-1.6.1/pithos/pandora/000077500000000000000000000000001443173105600157635ustar00rootroot00000000000000pithos-1.6.1/pithos/pandora/__init__.py000066400000000000000000000016071443173105600201000ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- # 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 . from .pandora import * def make_pandora(testing=False): if testing: from pithos.pandora.fake import FakePandora return FakePandora() else: return Pandora() pithos-1.6.1/pithos/pandora/blowfish.py000066400000000000000000000514141443173105600201570ustar00rootroot00000000000000# 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: """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 values 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.6.1/pithos/pandora/data.py000066400000000000000000000062101443173105600172450ustar00rootroot00000000000000client_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" # The CA used by internal-tuner.pandora.com is untrusted by most machines so we will just directly # trust it. # VeriSign Class 3 International Server CA - G3: # https://knowledge.symantec.com/support/ssl-certificates-support/index?page=content&id=SO26896 internal_cert = '''-----BEGIN CERTIFICATE----- MIIGKTCCBRGgAwIBAgIQZBvoIM4CCBPzLU0tldZ+ZzANBgkqhkiG9w0BAQUFADCB yjELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQL ExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJp U2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxW ZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0 aG9yaXR5IC0gRzUwHhcNMTAwMjA4MDAwMDAwWhcNMjAwMjA3MjM1OTU5WjCBvDEL MAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZW ZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTswOQYDVQQLEzJUZXJtcyBvZiB1c2UgYXQg aHR0cHM6Ly93d3cudmVyaXNpZ24uY29tL3JwYSAoYykxMDE2MDQGA1UEAxMtVmVy aVNpZ24gQ2xhc3MgMyBJbnRlcm5hdGlvbmFsIFNlcnZlciBDQSAtIEczMIIBIjAN BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmdacYvAV9IGaQQhZjxOdF8mfUdza sVLv/+NB3eDfxCjG4615HycQmLi7IJfBKERBD+qpqFLPTU4bi7u1xHbZzFYG7rNV ICreFY1xy1TIbxfNiQDk3P/hwB9ocenHKS5+vDv85burJlSLZpDN9pK5MSSAvJ5s 1fx+0uFLjNxC+kRLX/gYtS4w9D0SmNNiBXNUppyiHb5SgzoHRsQ7AlYhv/JRT9Cm mTnprqU/iZucff5NYAclIPe712mDK4KTQzfZg0EbawurSmaET0qO3n40mY5o1so5 BptMs5pITRNGtFghBMT7oE2sLktiEuP7TfbJUQABH/weaoEqOOC5T9YtRQIDAQAB o4ICFTCCAhEwEgYDVR0TAQH/BAgwBgEB/wIBADBwBgNVHSAEaTBnMGUGC2CGSAGG +EUBBxcDMFYwKAYIKwYBBQUHAgEWHGh0dHBzOi8vd3d3LnZlcmlzaWduLmNvbS9j cHMwKgYIKwYBBQUHAgIwHhocaHR0cHM6Ly93d3cudmVyaXNpZ24uY29tL3JwYTAO BgNVHQ8BAf8EBAMCAQYwbQYIKwYBBQUHAQwEYTBfoV2gWzBZMFcwVRYJaW1hZ2Uv Z2lmMCEwHzAHBgUrDgMCGgQUj+XTGoasjY5rw8+AatRIGCx7GS4wJRYjaHR0cDov L2xvZ28udmVyaXNpZ24uY29tL3ZzbG9nby5naWYwNAYDVR0lBC0wKwYIKwYBBQUH AwEGCCsGAQUFBwMCBglghkgBhvhCBAEGCmCGSAGG+EUBCAEwNAYIKwYBBQUHAQEE KDAmMCQGCCsGAQUFBzABhhhodHRwOi8vb2NzcC52ZXJpc2lnbi5jb20wNAYDVR0f BC0wKzApoCegJYYjaHR0cDovL2NybC52ZXJpc2lnbi5jb20vcGNhMy1nNS5jcmww KAYDVR0RBCEwH6QdMBsxGTAXBgNVBAMTEFZlcmlTaWduTVBLSS0yLTcwHQYDVR0O BBYEFNebfNgioBX33a1fzimbWMO8RgC1MB8GA1UdIwQYMBaAFH/TZafC3ey78DAJ 80M5+gKvMzEzMA0GCSqGSIb3DQEBBQUAA4IBAQBxtX1zUkrd1000Ky6vlEalSVAC T/gvF3DyE9wfIYaqwk98NzzURniuXXhv0bpavBCrWDbFjGIVRWAXIeLVQqh3oVXY QwRR9m66SOZdTLdE0z6k1dYzmp8N5tdOlkSVWmzWoxZTDphDzqS4w2Z6BVxiEOgb Ett9LnZQ/9/XaxvMisxx+rNAVnwzeneUW/ULU/sOX7xo+68q7jA3eRaTJX9NEP9X +79uOzMh3nnchhdZLUNkt6Zmh+q8lkYZGoaLb9e3SQBb26O/KZru99MzrqP0nkzK XmnUG623kHdq2FlveasB+lXwiiFm5WVu/XzT3x7rfj8GkPsZC9MGAht4Q5mo -----END CERTIFICATE----- ''' pithos-1.6.1/pithos/pandora/fake.py000066400000000000000000000133641443173105600172520ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- # 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 . 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=None, 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': { 'encoding': 'aac', 'bitrate': '32', 'audioUrl': audio_url }, 'mediumQuality': { 'encoding': 'aac', 'bitrate': '32', 'audioUrl': audio_url }, 'lowQuality': { 'encoding': 'aac', 'bitrate': '32', 'audioUrl': audio_url }, }, 'trackLength':121, '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.6.1/pithos/pandora/pandora.py000066400000000000000000000565061443173105600177750ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- # 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 . """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 import ssl import os from enum import IntEnum from socket import error as SocketError from . import data HTTP_TIMEOUT = 30 USER_AGENT = 'pithos' RATE_BAN = 'ban' RATE_LOVE = 'love' RATE_NONE = None class ApiError(IntEnum): INTERNAL_ERROR = 0 MAINTENANCE_MODE = 1 URL_PARAM_MISSING_METHOD = 2 URL_PARAM_MISSING_AUTH_TOKEN = 3 URL_PARAM_MISSING_PARTNER_ID = 4 URL_PARAM_MISSING_USER_ID = 5 SECURE_PROTOCOL_REQUIRED = 6 CERTIFICATE_REQUIRED = 7 PARAMETER_TYPE_MISMATCH = 8 PARAMETER_MISSING = 9 PARAMETER_VALUE_INVALID = 10 API_VERSION_NOT_SUPPORTED = 11 COUNTRY_NOT_SUPPORTED = 12 INSUFFICIENT_CONNECTIVITY = 13 UNKNOWN_METHOD_NAME = 14 WRONG_PROTOCOL = 15 READ_ONLY_MODE = 1000 INVALID_AUTH_TOKEN = 1001 INVALID_LOGIN = 1002 LISTENER_NOT_AUTHORIZED = 1003 USER_NOT_AUTHORIZED = 1004 MAX_STATIONS_REACHED = 1005 STATION_DOES_NOT_EXIST = 1006 COMPLIMENTARY_PERIOD_ALREADY_IN_USE = 1007 CALL_NOT_ALLOWED = 1008 DEVICE_NOT_FOUND = 1009 PARTNER_NOT_AUTHORIZED = 1010 INVALID_USERNAME = 1011 INVALID_PASSWORD = 1012 USERNAME_ALREADY_EXISTS = 1013 DEVICE_ALREADY_ASSOCIATED_TO_ACCOUNT = 1014 UPGRADE_DEVICE_MODEL_INVALID = 1015 EXPLICIT_PIN_INCORRECT = 1018 EXPLICIT_PIN_MALFORMED = 1020 DEVICE_MODEL_INVALID = 1023 ZIP_CODE_INVALID = 1024 BIRTH_YEAR_INVALID = 1025 BIRTH_YEAR_TOO_YOUNG = 1026 # FIXME: They can't both be 1027? # INVALID_COUNTRY_CODE = 1027 # INVALID_GENDER = 1027 DEVICE_DISABLED = 1034 DAILY_TRIAL_LIMIT_REACHED = 1035 INVALID_SPONSOR = 1036 USER_ALREADY_USED_TRIAL = 1037 PLAYLIST_EXCEEDED = 1039 # Catch all for undocumented error codes UNKNOWN_ERROR = 100000 @property def title(self): # Turns RANDOM_ERROR into Pandora Error: Random Error return 'Pandora Error: {}'.format(self.name.replace('_', ' ').title()) @property def sub_message(self): value = self.value if value == 1: return 'Pandora is performing maintenance.\nTry again later.' elif value == 12: return ('Pandora is not available in your country.\n' 'If you wish to use Pandora you must configure your system or Pithos proxy accordingly.') elif value == 13: return ('Out of sync. Correct your system\'s clock.\n' 'If the problem persists it may indicate a Pandora API change.\nA Pithos update may be required.') if value == 1000: return 'Pandora is in read-only mode.\nTry again later.' elif value == 1002: return 'Invalid username or password.' elif value == 1003: return 'A Pandora One account is required to access this feature.\nUncheck "Pandora One" in Settings.' elif value == 1005: return ('You have reached the maximum number of stations.\n' 'To add a new station you must first delete an existing station.') elif value == 1010: return 'Invalid Pandora partner keys.\nA Pithos update may be required.' elif value == 1023: return 'Invalid Pandora device model.\nA Pithos update may be required.' elif value == 1039: return 'You have requested too many playlists.\nTry again later.' else: return None PLAYLIST_VALIDITY_TIME = 60*60 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: """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 = self.build_opener() self.connected = False self.isSubscriber = False 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=None, https=False, blowfish=True): if not args: args = {} 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'}) with self.opener.open(req, timeout=HTTP_TIMEOUT) as response: 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) except SocketError as e: try: error_string = os.strerror(e.errno) except (TypeError, ValueError): error_string = "Unknown Error" logging.error("Network Socket Error: %s", error_string) raise PandoraNetError("Network Socket Error", submsg=error_string) logging.debug(text) tree = json.loads(text) if tree['stat'] == 'fail': code = tree['code'] msg = tree['message'] try: error_enum = ApiError(code) except ValueError: error_enum = ApiError.UNKNOWN_ERROR logging.error('fault code: {} {} message: {}'.format(code, error_enum.name, msg)) if error_enum is ApiError.INVALID_AUTH_TOKEN: raise PandoraAuthTokenInvalid(msg) elif error_enum is ApiError.API_VERSION_NOT_SUPPORTED: raise PandoraAPIVersionError(msg) elif error_enum is ApiError.UNKNOWN_ERROR: submsg = 'Undocumented Error Code: {}\n{}'.format(code, msg) raise PandoraError(error_enum.title, code, submsg) else: submsg = error_enum.sub_message or 'Error Code: {}\n{}'.format(code, msg) raise PandoraError(error_enum.title, code, submsg) 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 @staticmethod def build_opener(*handlers): """Creates a new opener Wrapper around urllib.request.build_opener() that adds a custom ssl.SSLContext for use with internal-tuner.pandora.com """ ctx = ssl.create_default_context() ctx.load_verify_locations(cadata=data.internal_cert) https = urllib.request.HTTPSHandler(context=ctx) return urllib.request.build_opener(https, *handlers) 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.connected = False 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) auth_args = {'username': user, 'password': password, 'loginType': 'user', 'returnIsSubscriber': True} user = self.json_call('auth.userLogin', auth_args, https=True) self.userId = user['userId'] self.userAuthToken = user['userAuthToken'] self.connected = True self.isSubscriber = user['isSubscriber'] @property def explicit_content_filter_state(self): """The User must already be authenticated before this is called. returns the state of Explicit Content Filter and if the Explicit Content Filter is PIN protected """ get_filter_state = self.json_call('user.getSettings', https=True) filter_state = get_filter_state.get('isExplicitContentFilterEnabled', False) pin_protected = get_filter_state.get('isExplicitContentFilterPINProtected', False) logging.info('Explicit Content Filter state: %s' %filter_state) logging.info('PIN protected: %s' %pin_protected) return filter_state, pin_protected def set_explicit_content_filter(self, state): """The User must already be authenticated before this is called. Does not take effect until the next playlist. Valid desired states are True to enable and False to disable the Explicit Content Filter. """ self.json_call('user.setExplicitContentFilter', {'isExplicitContentFilterEnabled': state}) logging.info('Explicit Content Filter set to: %s' %(state)) def get_stations(self, *ignore): stations = self.json_call( 'user.getStationList', {'returnAllStations': True} )['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', {'includeGenreStations': True, 'includeNearMatches': True, 'searchText': query}, ) l = [SearchResult('artist', i) for i in results['artists'] if i['score'] >= 80] l += [SearchResult('song', i) for i in results['songs'] if i['score'] >= 80] l += [SearchResult('genre', i) for i in results['genreStations']] 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) if not self.get_station_by_id(station.id): self.stations.append(station) return station def add_station_by_track_token(self, trackToken, musicType): d = self.json_call('station.createStation', {'trackToken': trackToken, 'musicType': musicType}) station = Station(self, d) if not self.get_station_by_id(station.id): self.stations.append(station) return station def delete_station(self, station): if self.get_station_by_id(station.id): logging.info("pandora: Deleting Station") self.json_call('station.deleteStation', {'stationToken': station.idToken}) self.stations.remove(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: 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.isThumbprint = d.get('isThumbprint', False) 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") # Set the playlist time to the time we requested a playlist. # It is better that a playlist be considered invalid a fraction # of a sec early than be considered valid any longer than it actually is. playlist_time = time.time() playlist = self.pandora.json_call('station.getPlaylist', { 'stationToken': self.idToken, 'includeTrackLength': True, 'additionalAudioUrl': 'HTTP_32_AACPLUS,HTTP_128_MP3', }, https=True)['items'] return [Song(self.pandora, i, playlist_time) for i in playlist if 'songName' in i] @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): self.pandora.delete_station(self) def __repr__(self): return '<{}.{} {} "{}">'.format( __name__, __class__.__name__, self.id, self.name, ) class Song: def __init__(self, pandora, d, playlist_time): self.pandora = pandora self.playlist_time = playlist_time self.is_ad = None # None = we haven't checked, otherwise True/False self.tired = False self.message = '' self.duration = None self.position = None self.bitrate = None self.start_time = None self.finished = False self.feedbackId = None self.bitrate = None self.artUrl = None self.album = d['albumName'] self.artist = d['artistName'] 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.trackLength = d['trackLength'] self.trackGain = float(d.get('trackGain', '0.0')) self.audioUrlMap = d['audioUrlMap'] # Optionally we requested more URLs if len(d.get('additionalAudioUrl', [])) == 2: if int(self.audioUrlMap['highQuality']['bitrate']) < 128: # We can use the higher quality mp3 stream for non-one users self.audioUrlMap['mediumQuality'] = self.audioUrlMap['highQuality'] self.audioUrlMap['highQuality'] = { 'encoding': 'mp3', 'bitrate': '128', 'audioUrl': d['additionalAudioUrl'][1], } else: # And we can offer a lower bandwidth option for one users self.audioUrlMap['lowQuality'] = { 'encoding': 'aacplus', 'bitrate': '32', 'audioUrl': d['additionalAudioUrl'][0], } # 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: with urllib.request.urlopen(self.songExplorerUrl) as x, minidom.parseString(x.read()) as dom: 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 @property def audioUrl(self): quality = self.pandora.audio_quality try: q = self.audioUrlMap[quality] self.bitrate = q['bitrate'] logging.info("Using audio quality %s: %s %s", quality, q['bitrate'], q['encoding']) return q['audioUrl'] except KeyError: logging.warning("Unable to use audio format %s. Using %s", quality, list(self.audioUrlMap.keys())[0]) self.bitrate = list(self.audioUrlMap.values())[0]['bitrate'] 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 else: return self.trackLength def get_position_sec(self): if self.position is not None: return self.position // 1000000000 else: return 0 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): # Playlists are valid for 1 hour. A song is considered valid if there is enough time # to play the remaining duration of the song before the playlist expires. return ((time.time() + (self.get_duration_sec() - self.get_position_sec())) - self.playlist_time) < PLAYLIST_VALIDITY_TIME def __repr__(self): return '<{}.{} {} "{}" by "{}" from "{}">'.format( __name__, __class__.__name__, self.trackToken, self.title, self.artist, self.album, ) class SearchResult: 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'] elif resultType == 'genre': self.stationName = d['stationName'] pithos-1.6.1/pithos/pithos.py000066400000000000000000001675321443173105600162350ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- # 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 . import contextlib import html import json import logging import math import re import os import sys import time import tempfile import urllib.error import urllib.parse import urllib.request from enum import Enum import gi gi.require_version('Gst', '1.0') gi.require_version('GstAudio', '1.0') gi.require_version('GstPbutils', '1.0') from gi.repository import Gst, GstAudio, 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 .StationsPopover import StationsPopover from .gobject_worker import GObjectWorker from .pandora import * from .pandora.data import * from .plugin import load_plugins from .util import parse_proxy, open_browser, SecretService, popup_at_pointer, is_flatpak from .migrate_settings import maybe_migrate_settings try: import pacparser except ImportError: pacparser = None # Older versions of Gstreamer may not have these constants try: RESAMPLER_QUALITY_MAX = GstAudio.AUDIO_RESAMPLER_QUALITY_MAX RESAMPLER_FILTER_MODE_FULL = GstAudio.AudioResamplerFilterMode.FULL except AttributeError: RESAMPLER_QUALITY_MAX = 10 RESAMPLER_FILTER_MODE_FULL = 1 ALBUM_ART_SIZE = 96 TEXT_X_PADDING = 12 FALLBACK_BLACK = Gdk.RGBA(red=0.0, green=0.0, blue=0.0, alpha=1.0) FALLBACK_WHITE = Gdk.RGBA(red=1.0, green=1.0, blue=1.0, alpha=1.0) RATING_BG_SVG = ''' ''' BACKGROUND_SVG = ''' ''' class PseudoGst(Enum): """Create aliases to Gst.State so that we can add our own BUFFERING Pseudo state""" PLAYING = 1 PAUSED = 2 BUFFERING = 3 STOPPED = 4 @property def state(self): value = self.value if value == 1: return Gst.State.PLAYING elif value == 2: return Gst.State.PAUSED elif value == 3: return Gst.State.PAUSED elif value == 4: return Gst.State.NULL class CellRendererAlbumArt(Gtk.CellRenderer): def __init__(self): super().__init__(height=ALBUM_ART_SIZE, width=ALBUM_ART_SIZE) self.icon = None self.pixbuf = None self.love_icon = None self.ban_icon = None self.tired_icon = None self.generic_audio_icon = None self.background = None self.rate_bg = None __gproperties__ = { 'icon': (str, 'icon', 'icon', '', GObject.ParamFlags.READWRITE), 'pixbuf': (GdkPixbuf.Pixbuf, 'pixmap', 'pixmap', GObject.ParamFlags.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_render(self, ctx, widget, background_area, cell_area, flags): if self.pixbuf is not None: Gdk.cairo_set_source_pixbuf(ctx, self.pixbuf, cell_area.x, cell_area.y) ctx.paint() else: Gdk.cairo_set_source_pixbuf(ctx, self.background, cell_area.x, cell_area.y) ctx.paint() x = cell_area.x + (ALBUM_ART_SIZE - self.generic_audio_icon.get_width()) // 2 y = cell_area.y + (ALBUM_ART_SIZE - self.generic_audio_icon.get_height()) // 2 Gdk.cairo_set_source_pixbuf(ctx, self.generic_audio_icon, x, y) ctx.paint() if self.icon is not None: x = cell_area.x + (cell_area.width - self.rate_bg.get_width()) # 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() if self.icon == 'love': rating_icon = self.love_icon elif self.icon == 'tired': rating_icon = self.tired_icon elif self.icon == 'ban': rating_icon = self.ban_icon x = x + (rating_icon.get_width() // 2) y = y + (rating_icon.get_height() // 2) Gdk.cairo_set_source_pixbuf(ctx, rating_icon, x, y) ctx.paint() def update_icons(self, style_context): # Dynamically change the color of backgrounds and icons # to match the current theme at theme changes. # Attempt to look up the background and foreground colors # in the theme's CSS file. Otherwise if they aren't found # fallback to black and white. *Most* new themes use 'theme_bg_color' and 'theme_fg_color'. # Some(older) themes use 'bg_color' and 'fg_color'.(like Ubuntu light themes) for key in ('theme_bg_color', 'bg_color'): bg_bool, bg_color = style_context.lookup_color(key) if bg_bool: break if not bg_bool: bg_color = FALLBACK_BLACK logging.debug("Could not find theme's background color falling back to black.") for key in ('theme_fg_color', 'fg_color'): fg_bool, fg_color = style_context.lookup_color(key) if fg_bool: break if not fg_bool: fg_color = FALLBACK_WHITE logging.debug("Could not find theme's foreground color falling back to white.") fg_rgb = fg_color.to_string() bg_rgb = bg_color.to_string() # Use our color values to create strings representing valid SVG's # for background and rate_bg, then load them with PixbufLoader. background = BACKGROUND_SVG.format(px=ALBUM_ART_SIZE, fg=fg_rgb).encode() rating_bg = RATING_BG_SVG.format(bg=bg_rgb).encode() with contextlib.closing(GdkPixbuf.PixbufLoader()) as loader: loader.write(background) self.background = loader.get_pixbuf() with contextlib.closing(GdkPixbuf.PixbufLoader()) as loader: loader.write(rating_bg) self.rate_bg = loader.get_pixbuf() current_theme = Gtk.IconTheme.get_default() # Pithos requires an icon theme with symbolic icons. # Manually color audio-x-generic-symbolic 48px icon to be used as part of the "default cover". info = current_theme.lookup_icon('audio-x-generic-symbolic', 48, 0) self.generic_audio_icon, was_symbolic = info.load_symbolic(bg_color, bg_color, bg_color, bg_color) # We request 24px icons because what we really want is 12px icons, # and they doesn't exist in many(or any?) icon themes. We then manually color # and scale them down to 12px. info = current_theme.lookup_icon('emblem-favorite-symbolic', 24, 0) icon, was_symbolic = info.load_symbolic(fg_color, fg_color, fg_color, fg_color) self.love_icon = icon.scale_simple(12, 12, GdkPixbuf.InterpType.BILINEAR) info = current_theme.lookup_icon('dialog-error-symbolic', 24, 0) icon, was_symbolic = info.load_symbolic(fg_color, fg_color, fg_color, fg_color) self.ban_icon = icon.scale_simple(12, 12, GdkPixbuf.InterpType.BILINEAR) info = current_theme.lookup_icon('go-jump-symbolic', 24, 0) icon, was_symbolic = info.load_symbolic(fg_color, fg_color, fg_color, fg_color) self.tired_icon = icon.scale_simple(12, 12, GdkPixbuf.InterpType.BILINEAR) @Gtk.Template(resource_path='/io/github/Pithos/ui/PithosWindow.ui') 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,)), "play-state-changed": (GObject.SignalFlags.RUN_FIRST, None, (GObject.TYPE_BOOLEAN,)), "user-changed-play-state": (GObject.SignalFlags.RUN_FIRST, None, (GObject.TYPE_BOOLEAN,)), "metadata-changed": (GObject.SignalFlags.RUN_FIRST, None, (GObject.TYPE_PYOBJECT,)), "buffering-finished": (GObject.SignalFlags.RUN_FIRST, None, (GObject.TYPE_PYOBJECT,)), "station-changed": (GObject.SignalFlags.RUN_FIRST, None, (GObject.TYPE_PYOBJECT,)), "stations-processed": (GObject.SignalFlags.RUN_FIRST, None, (GObject.TYPE_PYOBJECT,)), "station-added": (GObject.SignalFlags.RUN_FIRST, None, (GObject.TYPE_PYOBJECT,)), "stations-dlg-ready": (GObject.SignalFlags.RUN_FIRST, None, (GObject.TYPE_BOOLEAN,)), "songs-added": (GObject.SignalFlags.RUN_FIRST, None, (GObject.TYPE_INT,)), "player-ready": (GObject.SignalFlags.RUN_FIRST, None, (GObject.TYPE_BOOLEAN,)), } volume = Gtk.Template.Child() playpause_image = Gtk.Template.Child() statusbar = Gtk.Template.Child() song_menu = Gtk.Template.Child() song_menu_love = Gtk.Template.Child() song_menu_unlove = Gtk.Template.Child() song_menu_ban = Gtk.Template.Child() song_menu_unban = Gtk.Template.Child() song_menu_create_station = Gtk.Template.Child() song_menu_create_song_station = Gtk.Template.Child() song_menu_create_artist_station = Gtk.Template.Child() songs_treeview = Gtk.Template.Child() stations_button = Gtk.Template.Child() stations_label = Gtk.Template.Child() api_update_dialog_real = Gtk.Template.Child() error_dialog_real = Gtk.Template.Child() fatal_error_dialog_real = Gtk.Template.Child() def __init__(self, app, test_mode): super().__init__(application=app) self.init_template() self.settings = Gio.Settings.new('io.github.Pithos') self.settings.connect('changed::audio-quality', self.set_audio_quality) self.settings.connect('changed::proxy', self.set_proxy) self.settings.connect('changed::control-proxy', self.set_proxy) self.settings.connect('changed::control-proxy-pac', self.set_proxy) self.prefs_dlg = PreferencesPithosDialog.PreferencesPithosDialog(transient_for=self) self.prefs_dlg.connect_after('response', self.on_prefs_response) self.prefs_dlg.connect('login-changed', self.pandora_reconnect) self.init_core() self.init_ui() self.init_actions(app) self.plugins = {} load_plugins(self) self.pandora = make_pandora(test_mode) self.set_proxy(reconnect=False) self.set_audio_quality() SecretService.unlock_keyring(self.on_keyring_unlocked) def on_keyring_unlocked(self, error): if error: logging.error('You need to install a service such as gnome-keyring. Error: {}'.format(error)) self.fatal_error_dialog( error.message, _('You need to install a service such as gnome-keyring.'), ) else: maybe_migrate_settings() 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 index self.stations_model = Gtk.ListStore(GObject.TYPE_PYOBJECT, str, int) Gst.init(None) self._query_duration = Gst.Query.new_duration(Gst.Format.TIME) self._query_position = Gst.Query.new_position(Gst.Format.TIME) self._query_buffer = Gst.Query.new_buffering(Gst.Format.PERCENT) self.player = Gst.ElementFactory.make("playbin", "player") self.player.set_property('buffer-duration', 3 * Gst.SECOND) self.rgvolume = Gst.ElementFactory.make("rgvolume", "rgvolume") self.rgvolume.set_property("album-mode", False) self.rglimiter = Gst.ElementFactory.make("rglimiter", "rglimiter") self.rglimiter.set_property("enabled", False) self.equalizer = Gst.ElementFactory.make("equalizer-10bands", "equalizer-10bands") audioconvert = Gst.ElementFactory.make("audioconvert", "audioconvert") audioresample = Gst.ElementFactory.make("audioresample", "audioresample") audioresample.set_property("quality", RESAMPLER_QUALITY_MAX) audioresample.set_property("sinc-filter-mode", RESAMPLER_FILTER_MODE_FULL) audiosink = Gst.ElementFactory.make("autoaudiosink", "audiosink") sinkbin = Gst.Bin() sinkbin.add(self.rgvolume) sinkbin.add(self.rglimiter) sinkbin.add(self.equalizer) sinkbin.add(audioconvert) sinkbin.add(audioresample) sinkbin.add(audiosink) self.rgvolume.link(self.rglimiter) self.rglimiter.link(self.equalizer) self.equalizer.link(audioconvert) audioconvert.link(audioresample) audioresample.link(audiosink) sinkbin.add_pad(Gst.GhostPad.new("sink", self.rgvolume.get_static_pad("sink"))) self.player.set_property("audio-sink", sinkbin) self.emit('player-ready', True) bus = self.player.get_bus() bus.add_signal_watch() bus.connect("message::stream-start", self.on_gst_stream_start) 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) self.player.connect("notify::volume", self.on_gst_volume) self.player.connect("notify::source", self.on_gst_source) self.stations_dlg = None self._current_state = PseudoGst.STOPPED self._buffer_recovery_state = PseudoGst.STOPPED self.current_song_index = None self.current_station = None self.current_station_id = self.settings['last-station-id'] self.filter_state = None 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.buffering_timer_id = 0 self.ui_loop_timer_id = 0 self.playlist_update_timer_id = 0 display = self.props.screen.get_display() self.not_in_x = not type(display).__name__.endswith('X11Display') self.worker = GObjectWorker() try: tempdir_base = '/var/tmp' # Preferred over /tmp as lots of icons can be large in size. if is_flatpak(): # However in flatpak that path is not readable by the host. tempdir_base = os.path.join(GLib.get_user_cache_dir(), 'tmp') self.tempdir = tempfile.TemporaryDirectory(prefix='pithos-', dir=tempdir_base) logging.info("Created temporary directory {}".format(self.tempdir.name)) except IOError as e: self.tempdir = None logging.warning('Failed to create a temporary directory: {}'.format(e)) @property def playing(self): # Recreate the old "playing" attribute as a property. # Track self._buffer_recovery_state because that's the state # we wish we were in. return self._buffer_recovery_state is not PseudoGst.PAUSED def init_ui(self): GLib.set_application_name("Pithos") Gtk.Window.set_default_icon_name('pithos') self.volume.set_relief(Gtk.ReliefStyle.NORMAL) # It ignores glade... self.settings.bind('volume', self.volume, 'value', Gio.SettingsBindFlags.DEFAULT) self.songs_treeview.set_model(self.songs_model) title_col = Gtk.TreeViewColumn() render_cover_art = CellRendererAlbumArt() title_col.pack_start(render_cover_art, False) title_col.add_attribute(render_cover_art, "icon", 2) title_col.add_attribute(render_cover_art, "pixbuf", 3) render_text = Gtk.CellRendererText(xpad=TEXT_X_PADDING) render_text.props.ellipsize = Pango.EllipsizeMode.END title_col.pack_start(render_text, True) title_col.set_sizing(Gtk.TreeViewColumnSizing.FIXED) title_col.add_attribute(render_text, "markup", 1) self.songs_treeview.append_column(title_col) self.get_style_context().connect('changed', lambda sc: render_cover_art.update_icons(sc)) self.songs_treeview.connect('button_press_event', self.on_treeview_button_press_event) self.stations_popover = StationsPopover() self.stations_popover.set_relative_to(self.stations_button) self.stations_popover.set_model(self.stations_model) self.stations_popover.listbox.connect('row-activated', self.active_station_changed) self.stations_button.set_popover(self.stations_popover) self.stations_popover.search.connect('activate', self.search_activate_handler) def init_actions(self, app): action = Gio.SimpleAction.new('playpause', None) self.add_action(action) app.add_accelerator('space', 'win.playpause', None) action.connect('activate', self.user_playpause) action = Gio.SimpleAction.new('playselected', None) self.add_action(action) app.add_accelerator('Return', 'win.playselected', None) action.connect('activate', self.start_selected_song) action = Gio.SimpleAction.new('songinfo', None) self.add_action(action) app.add_accelerator('i', 'win.songinfo', None) action.connect('activate', self.info_song) action = Gio.SimpleAction.new('volumeup', None) self.add_action(action) app.add_accelerator('Up', 'win.volumeup', None) action.connect('activate', self.volume_up) action = Gio.SimpleAction.new('volumedown', None) self.add_action(action) app.add_accelerator('Down', 'win.volumedown', None) action.connect('activate', self.volume_down) action = Gio.SimpleAction.new('skip', None) self.add_action(action) app.add_accelerator('Right', 'win.skip', None) action.connect('activate', self.next_song) action = Gio.SimpleAction.new('love', None) self.add_action(action) app.add_accelerator('l', 'win.love', None) action.connect('activate', self.love_song) action = Gio.SimpleAction.new('ban', None) self.add_action(action) app.add_accelerator('b', 'win.ban', None) action.connect('activate', self.ban_song) action = Gio.SimpleAction.new('tired', None) self.add_action(action) app.add_accelerator('t', 'win.tired', None) action.connect('activate', self.tired_song) action = Gio.SimpleAction.new('unrate', None) self.add_action(action) app.add_accelerator('u', 'win.unrate', None) action.connect('activate', self.unrate_song) action = Gio.SimpleAction.new('bookmark', None) self.add_action(action) app.add_accelerator('d', 'win.bookmark', None) action.connect('activate', self.bookmark_song) action = Gio.SimpleAction.new('toggle-station-popover', None) self.add_action(action) app.add_accelerator('r', 'win.toggle-station-popover', None) action.connect('activate', self.stations_popover.toggle_visibility) def worker_run(self, fn, args=(), callback=None, message=None, context='net', errorback=None, user_data=None): 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: if user_data: callback(v, user_data) else: 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(message="Reconnecting...", callback=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.warning(e.traceback) err = errorback or eb self.worker.send(fn, args, cb, err) def get_proxy(self): """ Get HTTP proxy, first trying preferences then system proxy """ proxy = self.settings['proxy'] if proxy: return proxy system_proxies = urllib.request.getproxies() if 'http' in system_proxies: return system_proxies['http'] return None def on_explicit_content_filter_checkbox(self, *ignore): if self.pandora.connected: current_checkbox_state = self.prefs_dlg.explicit_content_filter_checkbutton.get_active() def set_content_filter(current_state): self.pandora.set_explicit_content_filter(current_state) def get_new_playlist(*ignore): if current_checkbox_state: logging.info('Getting a new playlist.') self.waiting_for_playlist = False self.stop() self.current_song_index = None self.songs_model.clear() self.get_playlist(start = True) if self.filter_state is not None and self.filter_state != current_checkbox_state: self.worker_run(set_content_filter, (current_checkbox_state, ), get_new_playlist) def set_proxy(self, *ignore, reconnect=True): # 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.settings['proxy'] if global_proxy: handlers.append(urllib.request.ProxyHandler({'http': global_proxy, 'https': global_proxy})) global_opener = pandora.Pandora.build_opener(*handlers) urllib.request.install_opener(global_opener) control_opener = global_opener control_proxy = self.settings['control-proxy'] control_proxy_pac = self.settings['control-proxy-pac'] if not control_proxy and (control_proxy_pac and pacparser): pacparser.init() with urllib.request.urlopen(control_proxy_pac) as f: pacstring = f.read().decode('utf-8') try: pacparser.parse_pac_string(pacstring) except pacparser._pacparser.error: 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 pacparser._pacparser.error: logging.warning('Failed to find proxy via PAC.') pacparser.cleanup() elif not control_proxy and (control_proxy_pac and not pacparser): logging.warning("Disabled proxy auto-config support because python-pacparser module was not found.") if control_proxy: control_opener = pandora.Pandora.build_opener(urllib.request.ProxyHandler({'http': control_proxy, 'https': control_proxy})) self.pandora.set_url_opener(control_opener) if reconnect: self.pandora_connect() def set_audio_quality(self, *ignore): self.pandora.set_audio_quality(self.settings['audio-quality']) def pandora_connect(self, *ignore, message="Logging in...", callback=None): def cb(password): if not password: self.show_preferences() else: self._pandora_connect_real(message, callback, email, password) email = self.settings['email'] if not email: self.show_preferences() else: SecretService.get_account_password(email, cb) def _pandora_connect_real(self, message, callback, email, password): if self.settings['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.settings['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 json.JSONDecodeError: logging.error("Could not parse force_client json") args = ( client, email, password, ) def on_got_stations(*ignore): self.process_stations(self) if callback: callback() def pandora_ready(*ignore): logging.info("Pandora connected") if self.settings['pandora-one'] != self.pandora.isSubscriber: self.settings['pandora-one'] = self.pandora.isSubscriber self._pandora_connect_real(message, callback, email, password) else: self.worker_run('get_stations', (), on_got_stations, 'Getting stations...', 'login') self.worker_run('connect', args, pandora_ready, message, 'login') def pandora_reconnect(self, prefs_dialog, email_password): ''' Stop everything and reconnect ''' email, password = email_password self.stop() self.waiting_for_playlist = False self.current_song_index = None self.start_new_playlist = False self.current_station = None self.current_station_id = None self.have_stations = False self.playcount = 0 self.songs_model.clear() self._pandora_connect_real("Logging in...", None, email, password) def sync_explicit_content_filter_setting(self, *ignore): #reset checkbox to default state self.prefs_dlg.explicit_content_filter_checkbutton.set_label(_('Explicit Content Filter')) self.prefs_dlg.explicit_content_filter_checkbutton.set_sensitive(False) self.prefs_dlg.explicit_content_filter_checkbutton.set_active(False) self.prefs_dlg.explicit_content_filter_checkbutton.set_inconsistent(True) self.filter_state = None if self.pandora.connected: def get_filter_and_pin_protected_state(*ignore): return self.pandora.explicit_content_filter_state def sync_checkbox(current_state): self.filter_state, pin_protected = current_state[0], current_state[1] self.prefs_dlg.explicit_content_filter_checkbutton.set_inconsistent(False) self.prefs_dlg.explicit_content_filter_checkbutton.set_active(self.filter_state) if pin_protected: self.prefs_dlg.explicit_content_filter_checkbutton.set_label(_('Explicit Content Filter - PIN Protected')) else: self.prefs_dlg.explicit_content_filter_checkbutton.set_sensitive(True) self.worker_run(get_filter_and_pin_protected_state, (), sync_checkbox) def process_stations(self, *ignore): self.stations_model.clear() self.stations_popover.clear() self.current_station = None selected = None # Make sure that the Thumprint Radio Station is always 2nd. for i, s in enumerate(self.pandora.stations): if s.isThumbprint: self.pandora.stations.insert(1, self.pandora.stations.pop(i)) break for i, s in enumerate(self.pandora.stations): if s.isQuickMix and s.isCreator: self.stations_model.append((s, "QuickMix", i)) else: self.stations_model.append((s, s.name, i)) if s.id == self.current_station_id: logging.info("Restoring saved station: id = %s"%(s.id)) selected = s if not selected and len(self.stations_model): selected=self.stations_model[0][0] if selected: self.station_changed(selected, reconnecting = self.have_stations) self.have_stations = True self.emit('stations-processed', self.pandora.stations) else: # User has no stations, open dialog self.show_stations() @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 = 'Song 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)) song = self.current_song audioUrl = song.audioUrl os.environ['PULSE_PROP_media.title'] = song.title os.environ['PULSE_PROP_media.artist'] = song.artist os.environ['PULSE_PROP_media.name'] = '{}: {}'.format(song.artist, song.title) os.environ['PULSE_PROP_media.filename'] = audioUrl self.player.set_property('buffer-size', int(song.bitrate) * 375) self.player.set_property('connection-speed', int(song.bitrate)) self.player.set_property("uri", audioUrl) self._set_player_state(PseudoGst.BUFFERING) 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("%s by %s - Pithos" % (song.title, song.artist)) self.update_song_row() self.emit('song-changed', song) self.emit('metadata-changed', song) def next_song(self, *ignore): if self.current_song_index is not None: self.start_song(self.current_song_index + 1) def _set_player_state(self, target, change_gst_state=False): change_gst_state = change_gst_state or self._current_state is not PseudoGst.BUFFERING if change_gst_state: ret = self.player.set_state(target.state) if ret == Gst.StateChangeReturn.FAILURE: current_state = self.player.state_get_name(self._current_state.state) target_state = self.player.state_get_name(target.state) logging.warning('Error changing player state from: {} to: {}'.format(current_state, target_state)) return False self._current_state = target if self._current_state is PseudoGst.PLAYING: self.create_ui_loop() else: self.destroy_ui_loop() if target is not PseudoGst.BUFFERING: self._buffer_recovery_state = target self.update_song_row() return True def user_play(self, *ignore): if self.play(): self.emit('user-changed-play-state', True) def play(self, change_gst_state=False): # Edge case. If we try to go to Play while we're reconnecting # to Pandora self.current_song will be None. if self.current_song is None: return False if not self.current_song.is_still_valid(): self.current_song.message = 'Song expired' self.update_song_row() return self.next_song() if self._set_player_state(PseudoGst.PLAYING, change_gst_state=change_gst_state): self.playpause_image.set_from_icon_name('media-playback-pause-symbolic', Gtk.IconSize.SMALL_TOOLBAR) self.emit('play-state-changed', True) return True def user_pause(self, *ignore): self.pause() self.emit('user-changed-play-state', False) def pause(self): if self._set_player_state(PseudoGst.PAUSED): self.playpause_image.set_from_icon_name('media-playback-start-symbolic', Gtk.IconSize.SMALL_TOOLBAR) 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) if self._set_player_state(PseudoGst.STOPPED, change_gst_state=True): # We need to reset the icon at song changes since our default # desired state is playing when going to a new song. self.playpause_image.set_from_icon_name('media-playback-pause-symbolic', Gtk.IconSize.SMALL_TOOLBAR) 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): if self.playlist_update_timer_id: GLib.source_remove(self.playlist_update_timer_id) self.playlist_update_timer_id = 0 songs_left_to_process = 0 song_count = 0 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.warning("Too many gstreamer errors. Not retrying") self.waiting_for_playlist = 1 self.error_dialog(self.gstreamer_error, self.get_playlist) return def emit_songs_added(song_count): self.playlist_update_timer_id = 0 self.emit('songs-added', song_count) return False def get_album_art(url, tmpdir, *extra): try: with urllib.request.urlopen(url) as f: image = f.read() except urllib.error.HTTPError: logging.warning('Invalid image url received') return (None, None,) + extra file_url = None if tmpdir: try: with tempfile.NamedTemporaryFile(prefix='art-', suffix='.jpeg', dir=tmpdir.name, delete=False) as f: f.write(image) file_url = urllib.parse.urljoin('file://', urllib.parse.quote(f.name)) except IOError: logging.warning("Failed to write art tempfile") with contextlib.closing(GdkPixbuf.PixbufLoader()) as loader: loader.set_size(ALBUM_ART_SIZE, ALBUM_ART_SIZE) loader.write(image) return (loader.get_pixbuf(), file_url,) + extra def art_callback(t): nonlocal songs_left_to_process pixbuf, file_url, song, index = t songs_left_to_process -= 1 if index%s" % (description, msg) @staticmethod def song_icon(song): if song.tired: return 'tired' if song.rating == RATE_LOVE: return 'love' if song.rating == RATE_BAN: return 'ban' return None 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) return True 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 search_activate_handler(self,station): row = self.stations_popover.listbox.get_row_at_y(0) if not row: return self.station_changed(row.station) self.stations_popover.on_row_activated(self.stations_popover.listbox, row) def active_station_changed(self, listbox, row): self.station_changed(row.station) @staticmethod def format_time(time_int): if time_int is None: return None 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 start_selected_song(self, *ignore): playable = self.selected_song().index > self.current_song_index if playable: self.start_song(self.selected_song().index) return playable def love_song(self, *ignore, song=None): song = song or self.current_song def callback(l): self.update_song_row(song) self.emit('metadata-changed', song) self.worker_run(song.rate, (RATE_LOVE,), callback, "Loving song...") def ban_song(self, *ignore, song=None): song = song or self.current_song def callback(l): self.update_song_row(song) self.emit('metadata-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, *ignore, song=None): song = song or self.current_song def callback(l): self.update_song_row(song) self.emit('metadata-changed', song) self.worker_run(song.rate, (RATE_NONE,), callback, "Removing song rating...") def tired_song(self, *ignore, song=None): song = song or self.current_song def callback(l): self.update_song_row(song) self.emit('metadata-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, *ignore, song=None): song = song or self.current_song self.worker_run(song.bookmark, (), None, "Bookmarking...") def bookmark_song_artist(self, *ignore, song=None): song = song or self.current_song self.worker_run(song.bookmark_artist, (), None, "Bookmarking...") def info_song(self, *ignore, song=None): song = song or self.current_song open_browser(song.songDetailURL) @Gtk.Template.Callback() def on_menuitem_love(self, widget): self.love_song(song=self.selected_song()) @Gtk.Template.Callback() def on_menuitem_ban(self, widget): self.ban_song(song=self.selected_song()) @Gtk.Template.Callback() def on_menuitem_unrate(self, widget): self.unrate_song(song=self.selected_song()) @Gtk.Template.Callback() def on_menuitem_tired(self, widget): self.tired_song(song=self.selected_song()) @Gtk.Template.Callback() def on_menuitem_info(self, widget): self.info_song(song=self.selected_song()) @Gtk.Template.Callback() def on_menuitem_bookmark_song(self, widget): self.bookmark_song(song=self.selected_song()) @Gtk.Template.Callback() def on_menuitem_bookmark_artist(self, widget): self.bookmark_song_artist(self.selected_song()) @Gtk.Template.Callback() def on_menuitem_create_artist_station(self, widget): user_date = 'artist', html.escape(self.selected_song().artist) self.worker_run( 'add_station_by_track_token', (self.selected_song().trackToken, 'artist'), self.station_added, user_data=user_date, ) @Gtk.Template.Callback() def on_menuitem_create_song_station(self, widget): title = html.escape(self.selected_song().title) artist = html.escape(self.selected_song().artist) user_date = 'song', '{} by {}'.format(title, artist) self.worker_run( 'add_station_by_track_token', (self.selected_song().trackToken, 'song'), self.station_added, user_data=user_date, ) def on_treeview_button_press_event(self, treeview, event): x = int(event.x) y = int(event.y) 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) popup_at_pointer(self.song_menu, event) return True if event.button == 1 and event.type == Gdk.EventType.DOUBLE_BUTTON_PRESS: logging.info("Double clicked on song %s", self.selected_song().index) return self.start_selected_song() 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) 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 volume_up(self, *ignore): self.adjust_volume(+2) def volume_down(self, *ignore): self.adjust_volume(-2) @Gtk.Template.Callback() def on_volume_change_event(self, volumebutton, value): self.set_player_volume(value) def show_about(self, version): """about - display the about box for pithos """ about = AboutPithosDialog.AboutPithosDialog(transient_for=self) about.set_version(version) about.run() about.destroy() def on_prefs_response(self, widget, response): self.prefs_dlg.hide() if response == Gtk.ResponseType.APPLY: self.on_explicit_content_filter_checkbox() else: if not self.settings['email']: self.quit() def show_preferences(self): """preferences - display the preferences window for pithos """ self.sync_explicit_content_filter_setting() self.prefs_dlg.show() def show_stations(self): if self.stations_dlg: self.stations_dlg.present() else: self.stations_dlg = StationsDialog.StationsDialog(self, transient_for=self) self.stations_dlg.show_all() self.emit('stations-dlg-ready', True) def refresh_stations(self, *ignore): self.worker_run(self.pandora.get_stations, (), self.process_stations, "Refreshing stations...") def remove_station(self, station): def station_index(model, s): return [i[0] for i in model].index(s) del self.stations_model[station_index(self.stations_model, station)] self.stations_popover.remove_station(station) def restore_position(self): """ Moves window to position stored in preferences """ # Getting and setting window position does not work in Wayland. if self.not_in_x: return x, y = self.settings['win-pos'] self.handler_block_by_func(self.on_configure_event) self.move(x, y) self.handler_unblock_by_func(self.on_configure_event) def bring_to_top(self, *ignore): timestamp = Gtk.get_current_event_time() self.present_with_time(timestamp) def present_with_time(self, timestamp): self.restore_position() Gtk.Window.present_with_time(self, timestamp) def present(self): self.restore_position() Gtk.Window.present(self) @Gtk.Template.Callback() def on_configure_event(self, *ignore): # Getting and setting window position does not work in Wayland. if self.not_in_x: return x, y = self.get_position() # This can return None self.settings.set_value('win-pos', GLib.Variant('(ii)', (x or 0, y or 0))) def quit(self, widget=None, data=None): """quit - signal handler for closing the PithosWindow""" Gio.Application.get_default().quit() @Gtk.Template.Callback() def on_destroy(self, widget, data=None): """on_destroy - called when the PithosWindow is close. """ self.stop() self.quit() pithos-1.6.1/pithos/plugin.py000066400000000000000000000120751443173105600162140ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- # 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 . import logging import glob import os from gi.repository import ( GLib, Gio, GObject ) class PithosPlugin(GObject.Object): __gtype_name__ = 'PithosPlugin' _PITHOS_PLUGIN = True # used to find the plugin class in a module preference = None description = "" def __init__(self, name, window, bus): super().__init__() self.name = name self.window = window self.bus = bus self.preferences_dialog = None self.prepared = False self._enabled = False self.error = None @GObject.Property def enabled(self): return self._enabled @enabled.setter def enabled(self, enabled): self._enabled = enabled def enable(self): if not self.prepared: logging.info('Preparing module {}'.format(self.name)) self.on_prepare() elif not self.error and not self.enabled: self._enable() def _enable(self): logging.info('Enabling module {}'.format(self.name)) self.on_enable() self.enabled = True def disable(self): if self.enabled: logging.info('Disabling module {}'.format(self.name)) self.on_disable() self.enabled = False def prepare_complete(self, error=None): self.prepared = True if error: self.on_error(error) else: self._enable() def on_error(self, error): self.error = error self.settings['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 {}: {}'.format(name, error)) self.prepared = True self.error = error self.name = name self.enabled = False def load_plugin(name, window, bus): 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, bus) def _maybe_migrate_setting(new_setting, name): if name != 'notification_icon': return old_setting = Gio.Settings.new_with_path('io.github.Pithos.plugin', '/io/github/Pithos/{}/'.format(name)) if old_setting['enabled']: new_setting['enabled'] = True old_setting.reset('enabled') def load_plugins(window): def on_got_bus(source, result, userdata): try: bus = Gio.bus_get_finish(result) logging.info('Got session bus') except GLib.Error as e: logging.warning('Failed to connect to session bus, some plugins will not function: {}'.format(e)) bus = None plugins = window.plugins settings = window.settings in_tree_plugins = settings.props.settings_schema.list_children() plugins_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "plugins") discovered_plugins = [fname[:-3] for fname in glob.glob1(plugins_dir, "*.py") if not fname.startswith("_")] discovered_plugins.sort() for name in discovered_plugins: if name not in plugins: plugin = plugins[name] = load_plugin(name, window, bus) else: plugin = plugins[name] settings_name = name.replace('_', '-') if settings_name in in_tree_plugins: plugin.settings = settings.get_child(settings_name) _maybe_migrate_setting(plugin.settings, name) else: # Out of tree plugin plugin.settings = Gio.Settings.new_with_path('io.github.Pithos.plugin', '/io/github/Pithos/{}/'.format(settings_name)) if plugin.settings['enabled']: plugin.enable() else: plugin.disable() window.prefs_dlg.set_plugins(window.plugins) Gio.bus_get( Gio.BusType.SESSION, None, on_got_bus, None, ) pithos-1.6.1/pithos/plugins/000077500000000000000000000000001443173105600160205ustar00rootroot00000000000000pithos-1.6.1/pithos/plugins/10_band_equalizer.py000066400000000000000000000072411443173105600216630ustar00rootroot00000000000000# # Copyright (C) 2017 Jason Gray # # 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 from pithos.plugin import PithosPlugin class TenBandEqPlugin(PithosPlugin): preference = 'enable_10bandeq' description = '-24 to +12dB' def on_prepare(self): self.preferences_dialog = EqDialog(self) self.prepare_complete() @Gtk.Template(resource_path='/io/github/Pithos/ui/EqDialog.ui') class EqDialog(Gtk.Dialog): __gtype_name__ = 'EqDialog' band0 = Gtk.Template.Child() band1 = Gtk.Template.Child() band2 = Gtk.Template.Child() band3 = Gtk.Template.Child() band4 = Gtk.Template.Child() band5 = Gtk.Template.Child() band6 = Gtk.Template.Child() band7 = Gtk.Template.Child() band8 = Gtk.Template.Child() band9 = Gtk.Template.Child() def __init__(self, plugin): super().__init__( _('Logging Level'), plugin.window, 0, ('_Reset', Gtk.ResponseType.CANCEL, '_Close', Gtk.ResponseType.CLOSE), use_header_bar=1, ) self.init_template() self.set_title(_('10 Band Equalizer')) self.set_default_size(200, 200) self.set_resizable(False) self.connect('response', self.on_response) self.connect('delete-event', lambda *ignore: self.hide_on_delete()) self.plugin = plugin self.plugin.window.connect('player-ready', self.on_enabled) self.plugin.connect('notify::enabled', self.on_enabled) def on_response(self, dialog, response): if response == Gtk.ResponseType.CLOSE: self.hide() elif response == Gtk.ResponseType.CANCEL: self.zero_eq() self.plugin.settings['data'] = self.get_eq_values() def on_enabled(self, *ignore): if not hasattr(self.plugin.window, 'player'): return if self.plugin.enabled: if not self.plugin.settings['data']: self.plugin.settings['data'] = self.get_eq_values() else: self.load_eq_values() else: self.zero_eq() @Gtk.Template.Callback() def on_scale_value_changed(self, scale): value = scale.get_value() name = scale.get_name() self.plugin.window.equalizer.set_property(name, value) self.plugin.settings['data'] = self.get_eq_values() def zero_eq(self): for i in range(10): self.set_eq_values(i) def get_eq_values(self): return ' '.join([str(self.plugin.window.equalizer.get_property('band{}'.format(i))) for i in range(10)]) def load_eq_values(self, *ignore): values = self.plugin.settings['data'].split(' ') for i, v in enumerate(values): self.set_eq_values(i, float(v)) def set_eq_values(self, index, value=0.0): name = 'band{}'.format(index) scale = getattr(self, name) scale.handler_block_by_func(self.on_scale_value_changed) scale.set_value(value) scale.handler_unblock_by_func(self.on_scale_value_changed) self.plugin.window.equalizer.set_property(name, value) pithos-1.6.1/pithos/plugins/__init__.py000066400000000000000000000000001443173105600201170ustar00rootroot00000000000000pithos-1.6.1/pithos/plugins/auto_volume_normalization.py000066400000000000000000000046331443173105600237050ustar00rootroot00000000000000# # Copyright (C) 2017 Jason Gray # # 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 from pithos.plugin import PithosPlugin class AutoVolumeNormalization(PithosPlugin): preference = 'enable_autovolume' description = _('Normalize apparent volume') _song_change_handler = None def on_prepare(self): self.prepare_complete() def on_enable(self): self._song_change_handler = self.window.connect('song-changed', self._on_song_changed) self.window.rglimiter.set_property('enabled', True) if self.window.current_song is not None: self._on_song_changed(self.window, self.window.current_song) def on_disable(self): if self._song_change_handler is not None: self.window.disconnect(self._song_change_handler) self._song_change_handler = None self._volume_warning_dialog() def _on_song_changed(self, window, song): window.rgvolume.set_property('fallback-gain', song.trackGain) def _volume_warning_dialog(self): if self.window.playing: self.window.pause() text = _('Pithos Has Been Paused') else: text = _('Pithos Is Paused') self.window.rgvolume.set_property('fallback-gain', 0.0) self.window.rglimiter.set_property('enabled', False) dialog = Gtk.MessageDialog( parent=self.window.prefs_dlg, flags=Gtk.DialogFlags.MODAL, type=Gtk.MessageType.WARNING, buttons=Gtk.ButtonsType.OK, text=text, secondary_text=_( 'Please lower the volume before resuming playback,\n' 'as you may notice a sudden volume increase upon disabling this plugin.' ), ) dialog.connect('response', lambda d, r: d.destroy()) dialog.show() pithos-1.6.1/pithos/plugins/dbus_util/000077500000000000000000000000001443173105600200125ustar00rootroot00000000000000pithos-1.6.1/pithos/plugins/dbus_util/DBusServiceObject.py000066400000000000000000000321161443173105600236740ustar00rootroot00000000000000# # Copyright (C) 2010 Martin Pitt # Copyright (C) 2016 Patrick Griffis # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser 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 . # import inspect import logging import subprocess from xml.etree import ElementTree from gi.repository import ( GLib, GObject, Gio ) __all__ = ['dbus_method', 'dbus_property', 'dbus_signal', 'DBusServiceObject'] class DBusAnnotationInfo: def __init__(self): key = None value = None annotations = [] class DBusArgInfo: def __init__(self, name="", signature=""): self.name = name self.signature = signature class DBusMethodInfo: def __init__(self, name="", interface=None, in_args=[], out_args=[], annotations=[]): self.name = name self.interface = interface self.in_args = in_args self.out_args = out_args self.annotations = annotations def generate_xml(self): method = ElementTree.Element('method', {'name': self.name}) for arg in self.in_args: ElementTree.SubElement(method, 'arg', {'name': arg.name, 'type': arg.signature, 'direction': 'in'}) for arg in self.out_args: ElementTree.SubElement(method, 'arg', {'name': arg.name, 'type': arg.signature, 'direction': 'out'}) return method class DBusSignalInfo: def __init__(self, name="", args=[], annotations=[], interface=None): self.name = name self.args = args self.annotations = annotations self.interface = interface def generate_xml(self): signal = ElementTree.Element('signal', {'name': self.name}) for arg in self.args: ElementTree.SubElement(signal, 'arg', {'name': arg.name, 'type': arg.signature}) return signal class DBusPropertyInfo: def __init__(self, name="", interface=None, signature=[], flags=Gio.DBusPropertyInfoFlags.NONE, annotations=[]): self.name = name self.interface = interface self.signature = signature self.flags = flags self.annotations = annotations def generate_xml(self): access = '' if self.flags & Gio.DBusPropertyInfoFlags.READABLE: access += 'read' if self.flags & Gio.DBusPropertyInfoFlags.WRITABLE: access += 'write' prop = ElementTree.Element('property', {'name': self.name, 'type': self.signature, 'access': access}) return prop class DBusInterfaceInfo: def __init__(self, name=''): self.name = name self.methods = [] self.signals = [] self.properties = [] self.annotations = [] def generate_xml(self, indent=0): interface = ElementTree.Element('interface', {'name': self.name}) for member in self.methods + self.properties + self.annotations + self.signals: interface.append(member.generate_xml()) return interface class DBusNodeInfo: def __init__(self, path=""): self.path = path self.interfaces = {} self.nodes = [] self.annotations = [] def generate_xml(self, indent=0): node = ElementTree.Element('node', {'name': self.path}) for interface in self.interfaces.values(): node.append(interface.generate_xml()) return node def _create_arginfo_list(func, signature): arg_names = inspect.getfullargspec(func).args signature_list = GLib.Variant.split_signature('(%s)' %signature) if signature else [] arg_names.pop(0) # eat "self" argument if len(signature_list) != len(arg_names): raise TypeError('Specified signature %s for method %s does not match length of arguments' %(str(signature_list), func.__name__)) args = [] for arg_signature, arg_name in zip(signature_list, arg_names): args.append(DBusArgInfo(name=arg_name, signature=arg_signature)) return args def dbus_method(interface, in_signature=None, out_signature=None): def decorator(func): in_args = _create_arginfo_list(func, in_signature) out_args = [DBusArgInfo(name='return', signature=out_signature),] if out_signature else [] func._dbus_info = DBusMethodInfo(name=func.__name__, interface=interface, in_args=in_args, out_args=out_args) return func return decorator def dbus_signal(interface, signature=None): def decorator(func): args = _create_arginfo_list(func, signature) info = DBusSignalInfo(name=func.__name__, interface=interface, args=args) def wrapper(self, *args): params = GLib.Variant('(%s)' %signature, args) if signature else None try: self.connection.emit_signal(None, self.object_path, interface, func.__name__, params) except GLib.Error as e: logging.warning('Failed to emit signal:', e) func(self, *args) wrapper._dbus_info = info return wrapper return decorator class dbus_property(object): def __init__(self, interface, signature, fget=None, fset=None): # check if fget is a data descriptor => a property if hasattr(fget, '__set__') and hasattr(fget, '__get__'): self.fget = None self.wrapped = fget prop = self.wrapped else: self.fget = fget self.wrapped = None prop = self self.fset = fset flags = Gio.DBusPropertyInfoFlags.NONE if prop.fget is not None: flags |= Gio.DBusPropertyInfoFlags.READABLE if prop.fset is not None: flags |= Gio.DBusPropertyInfoFlags.WRITABLE self._dbus_info = DBusPropertyInfo(interface=interface, signature=signature, flags=flags) def __call__(self, arg): # check if we're decorating a data descriptor => a property if hasattr(arg, '__set__') and hasattr(arg, '__get__'): self.wrapped = arg return self return self.getter(arg) def __get__(self, obj, type): if obj is None: return self if self.wrapped is not None: return self.wrapped.__get__(obj, type) if self.fget is None: raise AttributeError('unreadable attribute') return self.fget(obj) def __set__(self, obj, value): if self.wrapped is not None: return self.wrapped.__set__(obj, value) if self.fset is None: raise AttributeError('can\'t set attribute') return self.fset(obj, value) def __getattr__(self, name): return getattr(self.wrapped, name) def getter(self, fget): if self.wrapped is not None: return type(self)(interface=self._dbus_info.interface, signature=self._dbus_info.signature, fget=self.wrapped.getter(fget)) else: return type(self)(interface=self._dbus_info.interface, signature=self._dbus_info.signature, fget=fget, fset=self.fset) def setter(self, fset): if self.wrapped is not None: return type(self)(interface=self._dbus_info.interface, signature=self._dbus_info.signature, fget=self.wrapped.setter(fset)) else: return type(self)(interface=self._dbus_info.interface, signature=self._dbus_info.signature, fget=self.fget, fset=fset) class DBusServiceObject(GObject.Object): object_path = GObject.Property(type=str, flags=GObject.ParamFlags.READWRITE|GObject.ParamFlags.CONSTRUCT_ONLY) def __init__(self, **kwargs): super().__init__(**kwargs) self.__dbus_info = DBusNodeInfo(path=self.object_path) self.__dbus_regids = [] for id in dir(self): # don't use getattr(self, id) as default to avoid calling # __get__ of properties (which may not have been initialized) attr = getattr(type(self), id, None) if attr is None: attr = getattr(self, id) try: info = attr._dbus_info except AttributeError: continue interface = self.__dbus_info.interfaces.setdefault(info.interface, DBusInterfaceInfo(name=info.interface)) if isinstance(info, DBusMethodInfo): interface.methods.append(info) elif isinstance(info, DBusPropertyInfo): # the name of properties is determined by its attribute name info.name = info.name or id interface.properties.append(info) elif isinstance(info, DBusSignalInfo): interface.signals.append(info) if self.connection: self.__dbus_export() def __del__(self): if self.connection: self.__dbus_unexport() @GObject.Property(type=Gio.DBusConnection, flags=GObject.ParamFlags.READWRITE|GObject.ParamFlags.CONSTRUCT) def connection(self): return self.__connection @connection.setter def __set_connection(self, conn): prev = None if not hasattr(self, '__connection') else self.__connection if prev: self.__dbus_unexport() self.__connection = conn if prev and self.__connection: # Only export on changes otherwise it is done during init self.__dbus_export() def __dbus_export(self): xml = ElementTree.tostring(self.__dbus_info.generate_xml(), encoding='unicode') node_info = Gio.DBusNodeInfo.new_for_xml(xml) try: logging.debug('--- XML: ---\n{}\n-------'.format(node_info.generate_xml(0).str)) except TypeError: pass for interface in self.__dbus_info.interfaces: regid = self.connection.register_object( self.__dbus_info.path, node_info.lookup_interface(interface), self.__dbus_method_call, self.__dbus_get_property, self.__dbus_set_property ) self.__dbus_regids.append(regid) def __dbus_unexport(self): for reg_id in self.__dbus_regids: self.connection.unregister_object(reg_id) self.regids = [] def __dbus_method_call(self, conn, sender, object_path, iface_name, method_name, parameters, invocation): try: method = getattr(self, method_name) info = method._dbus_info except AttributeError: invocation.return_error_literal(Gio.dbus_error_quark(), Gio.DBusError.UNKNOWN_METHOD, 'No such interface or method: %s.%s' % (iface_name, method_name)) return try: ret = method(*parameters.unpack()) if ret is None and not info.out_args: invocation.return_value(None) else: invocation.return_value(GLib.Variant('(%s)' %info.out_args[0].signature, (ret,))) except Exception as e: invocation.return_error_literal(Gio.dbus_error_quark(), Gio.DBusError.IO_ERROR, 'Method %s.%s failed with: %s' % (iface_name, method_name, str(e))) def __dbus_get_property(self, conn, sender, object_path, iface_name, prop_name): try: info = getattr(type(self), prop_name)._dbus_info ret = getattr(self, prop_name) except AttributeError: return None return GLib.Variant(info.signature, ret) def __dbus_set_property(self, conn, sender, object_path, iface_name, prop_name, value): try: info = getattr(type(self), prop_name)._dbus_info ret = setattr(self, prop_name, value.unpack()) except AttributeError: return False return True pithos-1.6.1/pithos/plugins/inhibit_screensaver.py000066400000000000000000000043731443173105600224270ustar00rootroot00000000000000# # Copyright (C) 2017 Jason Gray # # 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, Gio ) from pithos.plugin import PithosPlugin class InhibitScreensaverPlugin(PithosPlugin): preference = 'enable_inhibitscreensaver' description = 'Prevent Session from going idle' _cookie = 0 _status_handler_id = None _playing = None _pithos_app = None def on_prepare(self): self._pithos_app = Gio.Application.get_default() self.prepare_complete() def on_enable(self): self._on_status_changed() if self._status_handler_id is None: self._status_handler_id = self.window.connect( 'play-state-changed', self._on_status_changed, ) def on_disable(self): if self._status_handler_id is not None: self.window.disconnect(self._status_handler_id) self._status_handler_id = None self._uninhibit() def _on_status_changed(self, *ignore): playing = self.window.playing if self._playing != playing: self._playing = playing if self._playing: self._inhibit() else: self._uninhibit() def _inhibit(self): suspend = Gtk.ApplicationInhibitFlags.SUSPEND idle = Gtk.ApplicationInhibitFlags.IDLE self._cookie = self._pithos_app.inhibit( self.window, suspend | idle, 'Inhibit Screensaver plugin enabled', ) def _uninhibit(self): if self._cookie != 0: self._pithos_app.uninhibit(self._cookie) self._cookie = 0 self._playing = None pithos-1.6.1/pithos/plugins/journald_logging.py000066400000000000000000000116471443173105600217270ustar00rootroot00000000000000# # Copyright (C) 2016 Jason Gray # # 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 gi.repository import GObject, Gtk from pithos.plugin import PithosPlugin LOG_LEVELS = { 'debug': logging.DEBUG, 'verbose': logging.INFO, 'warning': logging.WARN, } class JournalLoggingPlugin(PithosPlugin): preference = 'journald-logging' description = _('Store logs with the journald service') _logging_changed_handler = None def on_prepare(self): try: from systemd.journal import JournalHandler self._journal = JournalHandler(SYSLOG_IDENTIFIER='io.github.Pithos') self._journal.setFormatter(logging.Formatter()) self._logger = logging.getLogger() self.preferences_dialog = LoggingPluginPrefsDialog(self.window, self.settings) except ImportError: self.prepare_complete(error=_('Systemd Python module not found')) else: self.prepare_complete() def on_enable(self): self._on_logging_changed(None, self.settings['data'] or 'verbose') self._logger.addHandler(self._journal) self._logging_changed_handler = self.preferences_dialog.connect('logging-changed', self._on_logging_changed) def _on_logging_changed(self, prefs_dialog, level): self.settings['data'] = level self._journal.setLevel(LOG_LEVELS[level]) logging.info('setting journald logging level to: {}'.format(level)) def on_disable(self): if self._logging_changed_handler: self.preferences_dialog.disconnect(self._logging_changed_handler) self._logger.removeHandler(self._journal) class LoggingPluginPrefsDialog(Gtk.Dialog): __gtype_name__ = 'LoggingPluginPrefsDialog' __gsignals__ = { 'logging-changed': (GObject.SignalFlags.RUN_FIRST, None, (GObject.TYPE_STRING,)), } def __init__(self, parent, settings): super().__init__( _('Logging Level'), parent, 0, ('_Cancel', Gtk.ResponseType.CANCEL, '_Apply', Gtk.ResponseType.APPLY), use_header_bar=1, ) self.set_default_size(300, -1) self.pithos_window = parent self.settings = settings self.set_resizable(False) self.connect('delete-event', lambda *ignore: self.response(Gtk.ResponseType.CANCEL) or True) sub_title = Gtk.Label.new(_('Set the journald logging level for Pithos')) sub_title.set_halign(Gtk.Align.CENTER) self.log_level_combo = Gtk.ComboBoxText.new() logging_levels = [ ('debug', 'High - debug'), ('verbose', 'Default - verbose'), ('warning', 'Low - warning'), ] for level in logging_levels: self.log_level_combo.append(level[0], level[1]) self._reset_combo() content_area = self.get_content_area() content_area.add(sub_title) content_area.add(self.log_level_combo) content_area.show_all() def _reset_combo(self): self.log_level_combo.set_active_id(self.settings['data'] or 'verbose') def do_response(self, response): if response != Gtk.ResponseType.APPLY: self.hide() self._reset_combo() return setting = self.settings['data'] active_id = self.log_level_combo.get_active_id() if setting == active_id: self.hide() return if active_id != 'debug': self.hide() self.emit('logging-changed', active_id) return def on_dialog_response(dialog, response): if response == Gtk.ResponseType.YES: self.hide() self.emit('logging-changed', active_id) dialog.destroy() message = (_( 'The debug logging level is not ' 'recommended unless you are actually debugging an issue, ' 'as it generates very large logs.\n\nAre you sure you want to set logging to debug?', )) dialog = Gtk.MessageDialog( parent=self.pithos_window.prefs_dlg, flags=Gtk.DialogFlags.MODAL, type=Gtk.MessageType.WARNING, buttons=Gtk.ButtonsType.YES_NO, text=_('Debug Logging Level'), secondary_text=message, ) dialog.connect('response', on_dialog_response) dialog.show() pithos-1.6.1/pithos/plugins/lastfm.py000066400000000000000000000277011443173105600176670ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- # 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 . from enum import Enum import logging from gi.repository import Gtk, GObject 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' class LastfmPlugin(PithosPlugin): preference = 'enable_lastfm' description = _('Scrobble songs to Last.fm') is_really_enabled = False network = None def on_prepare(self): try: import pylast except ImportError: logging.warning('pylast not found.') self.prepare_complete(error=_('pylast not found')) else: self.pylast = pylast self.worker = GObjectWorker() self.preferences_dialog = LastFmAuth(self.pylast, self.settings) self.preferences_dialog.connect('lastfm-authorized', self.on_lastfm_authorized) self.window.prefs_dlg.connect('login-changed', self._show_dialog) self.prepare_complete() def on_enable(self): if self.settings['data']: self._enable_real() else: # Show the LastFmAuth dialog on enabling the plugin if we aren't already authorized. dialog = self.preferences_dialog dialog.set_transient_for(self.window.prefs_dlg) dialog.set_destroy_with_parent(True) dialog.set_modal(True) dialog.show_all() def on_lastfm_authorized(self, prefs_dialog, auth_state): if auth_state is prefs_dialog.AuthState.AUTHORIZED: self._enable_real() elif auth_state is prefs_dialog.AuthState.NOT_AUTHORIZED: self.on_disable() def _show_dialog(self, *ignore): if not self.network or not self.settings['data']: return def err(e): logging.error('Could not get Last.fm username. Error: {}'.format(e)) return None def get_username(): username = self.network.get_authenticated_user().get_name() logging.debug('Got Last.fm username: {}'.format(username)) return username self.worker.send(get_username, (), self._dialog, err) def _dialog(self, username): if not username: return def on_response(dialog, response): if self.enabled: disable_response = Gtk.ResponseType.NO else: disable_response = Gtk.ResponseType.YES if response == disable_response: self.preferences_dialog.auth_state = self.preferences_dialog.AuthState.NOT_AUTHORIZED self.settings.reset('enabled') self.settings.reset('data') self.preferences_dialog.button.set_sensitive(True) self.preferences_dialog.set_widget_text() if self.enabled: self.on_disable() dialog.destroy() if self.enabled: text = _('The Last.fm Plugin is Enabled') secondary_text = _('Would you like to continue Scrobbling to this Last.fm account?') trinary_text = _( 'You will need to re-enable the Last.fm Plugin if you wish to Scrobble to a different account.' ) else: text = _('The Last.fm Plugin is Disabled') secondary_text = _('But Pithos is still authorized with this Last.fm account:') trinary_text = _('Would you like to deauthorize it?') if self.window.prefs_dlg.get_visible(): parent = self.window.prefs_dlg else: parent = self.window dialog = Gtk.MessageDialog( parent=parent, flags=Gtk.DialogFlags.MODAL, type=Gtk.MessageType.INFO, buttons=Gtk.ButtonsType.YES_NO, text=text, secondary_text=secondary_text, ) dialog.connect('response', on_response) link_label = Gtk.Label.new(None) link_label.set_halign(Gtk.Align.CENTER) link = 'https://www.last.fm/user/{}'.format(username) link_label.set_markup('{}'.format(link, username)) trinary_label = Gtk.Label.new(trinary_text) trinary_label.set_halign(Gtk.Align.CENTER) message_area = dialog.get_message_area() message_area.add(link_label) message_area.add(trinary_label) message_area.show_all() dialog.show() def _enable_real(self): self._connect(self.settings['data']) self.is_really_enabled = True # Update Last.fm if plugin is enabled in the middle of a song. if self.window.current_song: self._on_song_changed(self.window, self.window.current_song) self._handlers = [ self.window.connect('song-ended', self._on_song_ended), self.window.connect('song-changed', self._on_song_changed), ] logging.debug('Last.fm plugin fully enabled') def on_disable(self): if self.is_really_enabled: if self._handlers: for handler in self._handlers: self.window.disconnect(handler) if self.preferences_dialog.auth_state is self.preferences_dialog.AuthState.AUTHORIZED: self._show_dialog() self.is_really_enabled = False self._handlers = [] def _connect(self, session_key): # get_lastfm_network is deprecated. Use LastFMNetwork preferably. if hasattr(self.pylast, 'LastFMNetwork'): get_network = self.pylast.LastFMNetwork else: get_network = self.pylast.get_lastfm_network self.network = get_network( api_key=API_KEY, api_secret=API_SECRET, session_key=session_key ) def _on_song_changed(self, window, song): def err(e): logging.error('Failed to update Last.fm now playing. Error: {}'.format(e)) def success(*ignore): logging.debug('Updated Last.fm now playing. {} by {}'.format(song.title, song.artist)) self.worker.send(self.network.update_now_playing, (song.artist, song.title, song.album), success, err) def _on_song_ended(self, window, song): def err(e): logging.error('Failed to Scrobble song at Last.fm. Error: {}'.format(e)) def success(*ignore): logging.info('Scrobbled {} by {} to Last.fm'.format(song.title, song.artist)) duration = song.get_duration_sec() position = song.get_position_sec() if not song.is_ad and duration > 30 and (position > 240 or position > duration / 2): args = ( song.artist, song.title, int(song.start_time), song.album, None, None, int(duration), ) self.worker.send(self.network.scrobble, args, success, err) class LastFmAuth(Gtk.Dialog): __gtype_name__ = 'LastFmAuth' __gsignals__ = { 'lastfm-authorized': (GObject.SignalFlags.RUN_FIRST, None, (GObject.TYPE_PYOBJECT,)), } class AuthState(Enum): NOT_AUTHORIZED = 0 BEGAN_AUTHORIZATION = 1 AUTHORIZED = 2 def __init__(self, pylast, settings): super().__init__(use_header_bar=1) self.set_title('Last.fm') self.set_default_size(300, -1) self.set_resizable(False) self.connect('delete-event', self.on_close) self.worker = GObjectWorker() self.settings = settings self.pylast = pylast self.auth_url = '' if self.settings['data']: self.auth_state = self.AuthState.AUTHORIZED else: self.auth_state = self.AuthState.NOT_AUTHORIZED self.label = Gtk.Label.new(None) self.label.set_halign(Gtk.Align.CENTER) self.button = Gtk.Button() self.button.set_halign(Gtk.Align.CENTER) self.set_widget_text() self.button.connect('clicked', self.on_clicked) content_area = self.get_content_area() content_area.add(self.label) content_area.add(self.button) content_area.show_all() def on_close(self, *ignore): self.hide() # Don't let things be left in a half authorized state if the dialog is closed and not fully authorized. # Also disable the plugin if it's not fully authorized so there's no confusion. if self.auth_state is not self.AuthState.AUTHORIZED: self.auth_state = self.AuthState.NOT_AUTHORIZED self.settings.reset('enabled') self.button.set_sensitive(True) self.set_widget_text() return True def set_widget_text(self): if self.auth_state is self.AuthState.AUTHORIZED: self.button.set_label(_('Deauthorize')) self.label.set_text(_('Pithos is Authorized with Last.fm')) elif self.auth_state is self.AuthState.NOT_AUTHORIZED: self.button.set_label(_('Authorize')) self.label.set_text(_('Pithos is not Authorized with Last.fm')) elif self.auth_state is self.AuthState.BEGAN_AUTHORIZATION: self.button.set_label(_('Finish')) self.label.set_text(_('Click Finish when Authorized with Last.fm')) def setkey(self, key): if not key: self.auth_state = self.AuthState.NOT_AUTHORIZED self.settings.reset('data') logging.debug('Last.fm Auth Key cleared') else: self.auth_state = self.AuthState.AUTHORIZED self.settings['data'] = key logging.debug('Got Last.fm Auth Key: {}'.format(key)) self.set_widget_text() self.button.set_sensitive(True) self.emit('lastfm-authorized', self.auth_state) def begin_authorization(self): def err(e): logging.error('Failed to begin Last.fm authorization. Error: {}'.format(e)) self.setkey('') def callback(url): self.auth_url = url logging.debug('Opening Last.fm Auth url: {}'.format(self.auth_url)) open_browser(self.auth_url) self.button.set_sensitive(True) self.auth_state = self.AuthState.BEGAN_AUTHORIZATION # get_lastfm_network is deprecated. Use LastFMNetwork preferably. if hasattr(self.pylast, 'LastFMNetwork'): get_network = self.pylast.LastFMNetwork else: get_network = self.pylast.get_lastfm_network self.sg = self.pylast.SessionKeyGenerator(get_network(api_key=API_KEY, api_secret=API_SECRET)) self.set_widget_text() self.button.set_sensitive(False) self.worker.send(self.sg.get_web_auth_url, (), callback, err) def finish_authorization(self): def err(e): logging.error('Failed to finish Last.fm authorization. Error: {}'.format(e)) self.setkey('') self.button.set_sensitive(False) self.worker.send(self.sg.get_web_auth_session_key, (self.auth_url,), self.setkey, err) def on_clicked(self, *ignore): if self.auth_state is self.AuthState.NOT_AUTHORIZED: self.begin_authorization() elif self.auth_state is self.AuthState.BEGAN_AUTHORIZATION: self.finish_authorization() elif self.auth_state is self.AuthState.AUTHORIZED: self.setkey('') pithos-1.6.1/pithos/plugins/mediakeys.py000066400000000000000000000152611443173105600203520ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- # 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 . import logging from gi.repository import GLib, Gdk, Gio from pithos.plugin import PithosPlugin APP_ID = 'io.github.Pithos' class MediaKeyPlugin(PithosPlugin): preference = 'enable_mediakeys' description = 'Control playback with media keys' mediakeys = None keybinder = None de_busnames = [ ('gnome', 'org.gnome.SettingsDaemon.MediaKeys'), ('gnome', 'org.gnome.SettingsDaemon'), ('mate', 'org.mate.SettingsDaemon'), ] def grab_media_keys(self): self.mediakeys.call( 'GrabMediaPlayerKeys', GLib.Variant('(su)', (APP_ID, 0)), Gio.DBusCallFlags.NONE, -1, None, None, ) def release_media_keys(self): self.mediakeys.call( 'ReleaseMediaPlayerKeys', GLib.Variant('(s)', (APP_ID,)), Gio.DBusCallFlags.NONE, -1, None, None, ) def update_focus_time(self, widget, event, userdata=None): if event.changed_mask & Gdk.WindowState.FOCUSED and \ event.new_window_state & Gdk.WindowState.FOCUSED: self.grab_media_keys() def update_active(self, *ignore): if self.window.is_active(): self.grab_media_keys() def mediakey_signal(self, proxy, sender, signal, param, userdata=None): if signal != 'MediaPlayerKeyPressed': return app, action = param.unpack() if app == APP_ID: if action == 'Play': self.window.playpause_notify() elif action == 'Next': self.window.next_song() elif action == 'Previous': self.window.bring_to_top() elif action in ('Stop', 'Pause'): self.window.user_pause() def on_prepare(self): def prepare_keybinder(): display = self.window.props.screen.get_display() if not type(display).__name__.endswith('X11Display'): self.prepare_complete(error='DBus binding failed and Keybinder requires X11.') else: try: import gi gi.require_version('Keybinder', '3.0') from gi.repository import Keybinder self.keybinder = Keybinder self.keybinder.init() except (ValueError, ImportError): self.keybinder = None self.prepare_complete(error='DBus binding failed and Keybinder not found.') else: self.prepare_complete() def on_new_finish(source, result, data): try: mediakeys = Gio.DBusProxy.new_finish(result) except GLib.Error as e: logging.warning(e) prepare_keybinder() else: if mediakeys.get_name_owner(): self.mediakeys = mediakeys self.prepare_complete() elif self.de_busnames: de, busname = self.de_busnames.pop(0) get_bus(de, busname) else: logging.debug('DBus binding failed') prepare_keybinder() def get_bus(de, bus_name): Gio.DBusProxy.new( self.bus, Gio.DBusProxyFlags.DO_NOT_LOAD_PROPERTIES, None, bus_name, '/org/{}/SettingsDaemon/MediaKeys'.format(de), 'org.{}.SettingsDaemon.MediaKeys'.format(de), None, on_new_finish, None ) if self.bus: de, busname = self.de_busnames.pop(0) get_bus(de, busname) else: prepare_keybinder() def on_enable(self): if self.mediakeys: iface_name = self.mediakeys.props.g_interface_name if 'mate' in iface_name: # Workaround for MATE not updating it's window state properly. self.focus_hook = self.window.connect('notify::is-active', self.update_active) self.grab_media_keys() else: self.focus_hook = self.window.connect('window-state-event', self.update_focus_time) self.mediakey_hook = self.mediakeys.connect('g-signal', self.mediakey_signal) logging.info('Bound media keys with DBUS {}'.format(iface_name)) elif self.keybinder: ret = self.keybinder.bind('XF86AudioPlay', self.window.playpause, None) if not ret: # Presumably all bindings will fail self.keybinder = None # We don't need to unbind any keys logging.error('Failed to bind media keys with Keybinder') self.on_error('Failed to bind media keys with Keybinder') return if all((self.keybinder.bind('XF86AudioStop', self.window.user_pause, None), self.keybinder.bind('XF86AudioPause', self.window.user_pause, None), self.keybinder.bind('XF86AudioNext', self.window.next_song, None), self.keybinder.bind('XF86AudioPrev', self.window.bring_to_top, None))): logging.info('Bound media keys with Keybinder') else: # Keybinder hardcodes a warning with the specific failures logging.warning('Some media keys failed to bind with Keybinder') def on_disable(self): if self.mediakeys: self.window.disconnect(self.focus_hook) self.mediakeys.disconnect(self.mediakey_hook) self.release_media_keys() logging.info('Disabled dbus mediakey bindings') elif self.keybinder: self.keybinder.unbind('XF86AudioPlay') self.keybinder.unbind('XF86AudioStop') self.keybinder.unbind('XF86AudioPause') self.keybinder.unbind('XF86AudioNext') self.keybinder.unbind('XF86AudioPrev') logging.info('Disabled keybinder mediakey bindings') pithos-1.6.1/pithos/plugins/mpris.py000066400000000000000000001004251443173105600175260ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- # Copyright (C) 2011 Rick Spencer # Copyright (C) 2011-2012 Kevin Mehall # Copyright (C) 2017 Jason Gray # 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 . # # See # for documentation. import codecs import logging import math from gi.repository import ( GLib, Gio, Gtk ) from .dbus_util.DBusServiceObject import ( DBusServiceObject, dbus_method, dbus_signal, dbus_property ) from pithos.plugin import PithosPlugin class MprisPlugin(PithosPlugin): preference = 'enable_mpris' description = 'Control with external programs' def on_prepare(self): if self.bus is None: logging.debug('Failed to connect to DBus') self.prepare_complete(error='Failed to connect to DBus') else: try: self.mpris = PithosMprisService(self.window, connection=self.bus) except Exception as e: logging.warning('Failed to create DBus mpris service: {}'.format(e)) self.prepare_complete(error='Failed to create DBus mpris service') else: self.preferences_dialog = MprisPluginPrefsDialog(self.window, self.settings) self.prepare_complete() def on_enable(self): '''Enables the mpris plugin.''' self.mpris.connect() def on_disable(self): '''Disables the mpris plugin.''' self.mpris.disconnect() class PithosMprisService(DBusServiceObject): MEDIA_PLAYER2_IFACE = 'org.mpris.MediaPlayer2' MEDIA_PLAYER2_PLAYER_IFACE = 'org.mpris.MediaPlayer2.Player' MEDIA_PLAYER2_PLAYLISTS_IFACE = 'org.mpris.MediaPlayer2.Playlists' MEDIA_PLAYER2_TRACKLIST_IFACE = 'org.mpris.MediaPlayer2.TrackList' # As per https://lists.freedesktop.org/archives/mpris/2012q4/000054.html # Secondary mpris interfaces to allow for options not allowed within the # confines of the mrpis spec are a completely valid use case. # This interface allows clients to love, ban, set tired and unrate songs. MEDIA_PLAYER2_RATINGS_IFACE = 'org.mpris.MediaPlayer2.ExtensionPithosRatings' TRACK_OBJ_PATH = '/io/github/Pithos/TrackId/' NO_TRACK_OBJ_PATH = '/org/mpris/MediaPlayer2/TrackList/NoTrack' PLAYLIST_OBJ_PATH = '/io/github/Pithos/PlaylistId/' NO_TRACK_METADATA = { 'mpris:trackid': GLib.Variant('o', NO_TRACK_OBJ_PATH), } def __init__(self, window, **kwargs): '''Creates a PithosMprisService object.''' super().__init__(object_path='/org/mpris/MediaPlayer2', **kwargs) self.window = window def _reset(self): '''Resets state to default.''' self._has_thumbprint_radio = False self._volume = math.pow(self.window.player.props.volume, 1.0 / 3.0) self._metadata = self.NO_TRACK_METADATA self._metadata_list = [self.NO_TRACK_METADATA] self._tracks = [self.NO_TRACK_OBJ_PATH] self._playback_status = 'Stopped' self._playlists = [('/', '', '')] self._current_playlist = False, ('/', '', '') self._orderings = ['CreationDate'] self._stations_dlg_handlers = [] self._window_handlers = [] self._stations_dlg_handlers = [] self._volumechange_handler_id = None self._sort_order_handler_id = None def connect(self): '''Takes ownership of the Pithos mpris Interfaces.''' self._reset() def on_name_acquired(connection, name): logging.info('Got bus name: {}'.format(name)) self._update_handlers() self._connect_handlers() self.bus_id = Gio.bus_own_name_on_connection( self.connection, 'org.mpris.MediaPlayer2.io.github.Pithos', Gio.BusNameOwnerFlags.NONE, on_name_acquired, None, ) def disconnect(self): '''Disowns the Pithos mpris Interfaces.''' self._disconnect_handlers() if self.bus_id: Gio.bus_unown_name(self.bus_id) self.bus_id = 0 def _update_handlers(self): '''Updates signal handlers.''' # Update some of our dynamic props if mpris # was enabled after a song has already started. window = self.window station = self.window.current_station song = self.window.current_song if station: self._current_playlist_handler( window, station, ) self._update_playlists_handler( window, window.pandora.stations, ) if song: self._songs_added_handler( window, 4, ) self._metadatachange_handler( window, song, ) self._playstate_handler( window, window.playing, ) self._sort_order_handler() def _connect_handlers(self): '''Connects signal handlers.''' window = self.window self._window_handlers = [ window.connect( 'metadata-changed', self._metadatachange_handler, ), window.connect( 'play-state-changed', self._playstate_handler, ), window.connect( 'buffering-finished', lambda window, position: self.Seeked(position // 1000), ), window.connect( 'station-changed', self._current_playlist_handler, ), window.connect( 'stations-processed', self._update_playlists_handler, ), window.connect( 'stations-dlg-ready', self._stations_dlg_ready_handler, ), window.connect( 'songs-added', self._songs_added_handler, ), window.connect( 'station-added', self._add_playlist_handler, ), ] if window.stations_dlg: # If stations_dlg exists already # we missed the ready signal and # we should connect our handlers. self._stations_dlg_ready_handler() self._volumechange_handler_id = window.player.connect( 'notify::volume', self._volumechange_handler, ) self._sort_order_handler_id = window.settings.connect( 'changed::sort-stations', self._sort_order_handler, ) def _disconnect_handlers(self): '''Disconnects signal handlers.''' window = self.window stations_dlg = self.window.stations_dlg if self._window_handlers: for handler in self._window_handlers: window.disconnect(handler) if stations_dlg and self._stations_dlg_handlers: for handler in self._stations_dlg_handlers: stations_dlg.disconnect(handler) if self._volumechange_handler_id: window.player.disconnect(self._volumechange_handler_id) if self._sort_order_handler_id: window.settings.disconnect(self._sort_order_handler_id) def _stations_dlg_ready_handler(self, *ignore): '''Connects stations dialog handlers.''' stations_dlg = self.window.stations_dlg self._stations_dlg_handlers = [ stations_dlg.connect( 'station-renamed', self._rename_playlist_handler, ), stations_dlg.connect( 'station-added', self._add_playlist_handler, ), stations_dlg.connect( 'station-removed', self._remove_playlist_handler, ), ] def _sort_order_handler(self, *ignore): '''Changes the Playlist Orderings Property based on the station popover sort order.''' if self.window.settings['sort-stations']: new_orderings = ['Alphabetical'] else: new_orderings = ['CreationDate'] if self._orderings != new_orderings: self._orderings = new_orderings self.PropertiesChanged( self.MEDIA_PLAYER2_PLAYLISTS_IFACE, {'Orderings': GLib.Variant('as', self._orderings)}, [], ) def _update_playlists_handler(self, window, stations): '''Updates the Playlist Interface when stations are loaded/refreshed.''' # The Thumbprint Radio Station may not exist if it does it will be the 2nd station. self._has_thumbprint_radio = stations[1].isThumbprint self._playlists = [(self.PLAYLIST_OBJ_PATH + station.id, station.name, '') for station in stations] self.PropertiesChanged( self.MEDIA_PLAYER2_PLAYLISTS_IFACE, {'PlaylistCount': GLib.Variant('u', len(self._playlists))}, [], ) def _remove_playlist_handler(self, window, station): '''Removes a deleted station from the Playlist Interface.''' for index, playlist in enumerate(self._playlists[:]): if playlist[0].strip(self.PLAYLIST_OBJ_PATH) == station.id: del self._playlists[index] self.PropertiesChanged( self.MEDIA_PLAYER2_PLAYLISTS_IFACE, {'PlaylistCount': GLib.Variant('u', len(self._playlists))}, [], ) break def _rename_playlist_handler(self, stations_dlg, data): '''Renames the corresponding Playlist when a station is renamed.''' station_id, new_name = data for index, playlist in enumerate(self._playlists): if playlist[0].strip(self.PLAYLIST_OBJ_PATH) == station_id: self._playlists[index] = (self.PLAYLIST_OBJ_PATH + station_id, new_name, '') self.PlaylistChanged(self._playlists[index]) break def _add_playlist_handler(self, window, station): '''Adds a new station to the Playlist Interface when it is created.''' new_playlist = (self.PLAYLIST_OBJ_PATH + station.id, station.name, '') if new_playlist not in self._playlists: if self._has_thumbprint_radio: self._playlists.insert(2, new_playlist) else: self._playlists.insert(1, new_playlist) self.PropertiesChanged( self.MEDIA_PLAYER2_PLAYLISTS_IFACE, {'PlaylistCount': GLib.Variant('u', len(self._playlists))}, [], ) def _current_playlist_handler(self, window, station): '''Sets the ActivePlaylist Property to the current station.''' new_current_playlist = (self.PLAYLIST_OBJ_PATH + station.id, station.name, '') if self._current_playlist != (True, new_current_playlist): self._current_playlist = (True, new_current_playlist) self.PropertiesChanged( self.MEDIA_PLAYER2_PLAYLISTS_IFACE, {'ActivePlaylist': GLib.Variant('(b(oss))', self._current_playlist)}, [], ) def _playstate_handler(self, window, state): '''Updates the mpris PlaybackStatus Property.''' play_state = 'Playing' if state else 'Paused' if self._playback_status != play_state: # stops unneeded updates self._playback_status = play_state self.PropertiesChanged( self.MEDIA_PLAYER2_PLAYER_IFACE, {'PlaybackStatus': GLib.Variant('s', self._playback_status)}, [], ) def _volumechange_handler(self, player, spec): '''Updates the mpris Volume Property.''' volume = math.pow(player.props.volume, 1.0 / 3.0) if self._volume != volume: # stops unneeded updates self._volume = volume self.PropertiesChanged( self.MEDIA_PLAYER2_PLAYER_IFACE, {'Volume': GLib.Variant('d', self._volume)}, [], ) def _songs_added_handler(self, window, song_count): '''Adds songs to the TrackList Interface.''' songs_model = window.songs_model stop = len(songs_model) start = max(0, stop - (song_count + 1)) songs = [songs_model[i][0] for i in range(start, stop)] self._tracks = [self._track_id_from_song(song) for song in songs] self._metadata_list = [self._get_metadata(window, song) for song in songs] self.TrackListReplaced(self._tracks, self._tracks[0]) def _metadatachange_handler(self, window, song): '''Updates the metadata for the Player and TrackList Interfaces.''' # Ignore songs that have no chance of being in our Tracks list. if song.index < max(0, len(window.songs_model) - 5): return metadata = self._get_metadata(window, song) trackId = self._track_id_from_song(song) if trackId in self._tracks: for index, track_id in enumerate(self._tracks): if track_id == trackId and not self._metadata_equal(self._metadata_list[index], metadata): self._metadata_list[index] = metadata self.TrackMetadataChanged(trackId, metadata) break # No need to update the current metadata if the current song has been banned # or set tired as it will be skipped anyway very shortly. if (song is window.current_song and not (song.tired or song.rating == 'ban') and not self._metadata_equal(self._metadata, metadata)): self._metadata = metadata self.PropertiesChanged( self.MEDIA_PLAYER2_PLAYER_IFACE, {'Metadata': GLib.Variant('a{sv}', self._metadata)}, [], ) def _get_metadata(self, window, song): '''Generates metadata for a song.''' # Map pithos ratings to something MPRIS understands userRating = 1.0 if song.rating == 'love' else 0.0 duration = song.get_duration_sec() * 1000000 pithos_rating = window.song_icon(song) or '' trackid = self._track_id_from_song(song) metadata = { 'mpris:trackid': GLib.Variant('o', trackid), 'xesam:title': GLib.Variant('s', song.title or 'Title Unknown'), 'xesam:artist': GLib.Variant('as', [song.artist] or ['Artist Unknown']), 'xesam:album': GLib.Variant('s', song.album or 'Album Unknown'), 'xesam:userRating': GLib.Variant('d', userRating), 'xesam:url': GLib.Variant('s', song.audioUrl), 'mpris:length': GLib.Variant('x', duration), 'pithos:rating': GLib.Variant('s', pithos_rating), } # If we don't have an artUrl the best thing we can # do is not even have 'mpris:artUrl' in the metadata, # and let the applet decide what to do. if song.artUrl is not None: metadata['mpris:artUrl'] = GLib.Variant('s', song.artUrl) return metadata def _metadata_equal(self, m1, m2): # Test to see if 2 sets of metadata are the same # to avoid unneeded updates. if len(m1) != len(m2): return False for key in m1.keys(): if not m1[key].equal(m2[key]): return False return True def _song_from_track_id(self, TrackId): '''Convenience method that takes a TrackId and returns the corresponding song object.''' if TrackId not in self._tracks: return if self.window.current_song_index is None: return songs_model = self.window.songs_model stop = len(songs_model) start = max(0, stop - 5) for i in range(start, stop): song = songs_model[i][0] if TrackId == self._track_id_from_song(song): return song def _track_id_from_song(self, song): '''Convenience method that generates a TrackId based on a song.''' return self.TRACK_OBJ_PATH + codecs.encode(bytes(song.trackToken, 'ascii'), 'hex').decode('ascii') @dbus_property(MEDIA_PLAYER2_IFACE, signature='b') def CanQuit(self): '''b Read only Interface MediaPlayer2''' return True @dbus_property(MEDIA_PLAYER2_IFACE, signature='b') def Fullscreen(self): '''b Read/Write (optional) Interface MediaPlayer2''' return False @Fullscreen.setter def Fullscreen(self, Fullscreen): '''Not Implemented''' # Spec says the Fullscreen property should be read/write so we # include this dummy setter for applets that might wrongly ignore # the CanSetFullscreen property and try to set the Fullscreen # property anyway. pass @dbus_property(MEDIA_PLAYER2_IFACE, signature='b') def CanSetFullscreen(self): '''b Read only (optional) Interface MediaPlayer2''' return False @dbus_property(MEDIA_PLAYER2_IFACE, signature='b') def CanRaise(self): '''b Read only Interface MediaPlayer2''' return True @dbus_property(MEDIA_PLAYER2_IFACE, signature='b') def HasTrackList(self): '''b Read only Interface MediaPlayer2''' return True @dbus_property(MEDIA_PLAYER2_IFACE, signature='s') def Identity(self): '''s Read only Interface MediaPlayer2''' return 'Pithos' @dbus_property(MEDIA_PLAYER2_IFACE, signature='s') def DesktopEntry(self): '''s Read only (optional) Interface MediaPlayer2''' return 'io.github.Pithos' @dbus_property(MEDIA_PLAYER2_IFACE, signature='as') def SupportedUriSchemes(self): '''as Read only Interface MediaPlayer2''' return [] @dbus_property(MEDIA_PLAYER2_IFACE, signature='as') def SupportedMimeTypes(self): '''as Read only Interface MediaPlayer2''' return [] @dbus_property(MEDIA_PLAYER2_PLAYER_IFACE, signature='s') def PlaybackStatus(self): '''s Read only Interface MediaPlayer2.Player''' return self._playback_status @dbus_property(MEDIA_PLAYER2_PLAYER_IFACE, signature='s') def LoopStatus(self): '''s Read/Write only (optional) Interface MediaPlayer2.Player''' return 'None' @LoopStatus.setter def LoopStatus(self, LoopStatus): '''Not Implemented''' # There is no way to tell clients this property can't be set. pass @dbus_property(MEDIA_PLAYER2_PLAYER_IFACE, signature='b') def Shuffle(self): '''b Read/Write (optional) Interface MediaPlayer2.Player''' return False @Shuffle.setter def Shuffle(self, Shuffle): '''Not Implemented''' # There is no way to tell clients this property can't be set. pass @dbus_property(MEDIA_PLAYER2_PLAYER_IFACE, signature='d') def Rate(self): '''d Read/Write Interface MediaPlayer2.Player''' return 1.0 @Rate.setter def Rate(self, Rate): '''Not Implemented''' # There is no way to tell clients this property can't be set. pass @dbus_property(MEDIA_PLAYER2_PLAYER_IFACE, signature='a{sv}') def Metadata(self): '''a{sv} Read only Interface MediaPlayer2.Player''' return self._metadata @dbus_property(MEDIA_PLAYER2_PLAYER_IFACE, signature='d') def Volume(self): '''d Read/Write Interface MediaPlayer2.Player''' volume = self.window.player.get_property('volume') scaled_volume = math.pow(volume, 1.0 / 3.0) return scaled_volume @Volume.setter def Volume(self, new_volume): scaled_vol = math.pow(new_volume, 3.0 / 1.0) self.window.player.set_property('volume', scaled_vol) @dbus_property(MEDIA_PLAYER2_PLAYER_IFACE, signature='x') def Position(self): '''x Read only Interface MediaPlayer2.Player''' position = self.window.query_position() if position is not None: return position // 1000 else: return 0 @dbus_property(MEDIA_PLAYER2_PLAYER_IFACE, signature='d') def MinimumRate(self): '''d Read only Interface MediaPlayer2.Player''' return 1.0 @dbus_property(MEDIA_PLAYER2_PLAYER_IFACE, signature='d') def MaximumRate(self): '''d Read only Interface MediaPlayer2.Player''' return 1.0 @dbus_property(MEDIA_PLAYER2_PLAYER_IFACE, signature='b') def CanGoNext(self): '''b Read only Interface MediaPlayer2.Player''' return True @dbus_property(MEDIA_PLAYER2_PLAYER_IFACE, signature='b') def CanGoPrevious(self): '''b Read only Interface MediaPlayer2.Player''' return False @dbus_property(MEDIA_PLAYER2_PLAYER_IFACE, signature='b') def CanPlay(self): '''b Read only Interface MediaPlayer2.Player''' return True @dbus_property(MEDIA_PLAYER2_PLAYER_IFACE, signature='b') def CanPause(self): '''b Read only Interface MediaPlayer2.Player''' return True @dbus_property(MEDIA_PLAYER2_PLAYER_IFACE, signature='b') def CanSeek(self): '''b Read only Interface MediaPlayer2.Player''' return False @dbus_property(MEDIA_PLAYER2_PLAYER_IFACE, signature='b') def CanControl(self): '''b Read only Interface MediaPlayer2.Player''' return True @dbus_property(MEDIA_PLAYER2_PLAYLISTS_IFACE, signature='(b(oss))') def ActivePlaylist(self): '''(b(oss)) Read only Interface MediaPlayer2.Playlists''' return self._current_playlist @dbus_property(MEDIA_PLAYER2_PLAYLISTS_IFACE, signature='u') def PlaylistCount(self): '''u Read only Interface MediaPlayer2.Playlists''' return len(self._playlists) @dbus_property(MEDIA_PLAYER2_PLAYLISTS_IFACE, signature='as') def Orderings(self): '''as Read only Interface MediaPlayer2.Playlists''' return self._orderings @dbus_property(MEDIA_PLAYER2_TRACKLIST_IFACE, signature='ao') def Tracks(self): '''ao Read only Interface MediaPlayer2.TrackList''' return self._tracks @dbus_property(MEDIA_PLAYER2_TRACKLIST_IFACE, signature='b') def CanEditTracks(self): '''b Read only Interface MediaPlayer2.TrackList''' return False @dbus_property(MEDIA_PLAYER2_RATINGS_IFACE, signature='b') def HasPithosExtension(self): '''b Read only Interface MediaPlayer2.ExtensionPithosRatings''' # This property exists so that applets can check it to make sure # the MediaPlayer2.ExtensionPithosRatings interface actually exists. # It's much more convenient for them then wrapping all their # ratings code in the equivalent of a try except block. # Not all versions of Pithos will have this interface. # It serves a similar function as HasTrackList. return True @dbus_method(MEDIA_PLAYER2_IFACE) def Raise(self): '''() -> nothing Interface MediaPlayer2''' self.window.bring_to_top() @dbus_method(MEDIA_PLAYER2_IFACE) def Quit(self): '''() -> nothing Interface MediaPlayer2''' self.window.quit() @dbus_method(MEDIA_PLAYER2_PLAYER_IFACE) def Previous(self): '''Not Implemented''' pass @dbus_method(MEDIA_PLAYER2_PLAYER_IFACE) def Next(self): '''() -> nothing Interface MediaPlayer2.Player''' if not self.window.waiting_for_playlist: self.window.next_song() @dbus_method(MEDIA_PLAYER2_PLAYER_IFACE) def PlayPause(self): '''() -> nothing Interface MediaPlayer2.Player''' if self.window.current_song: self.window.playpause() @dbus_method(MEDIA_PLAYER2_PLAYER_IFACE) def Play(self): '''() -> nothing Interface MediaPlayer2.Player''' if self.window.current_song: self.window.play() @dbus_method(MEDIA_PLAYER2_PLAYER_IFACE) def Pause(self): '''() -> nothing Interface MediaPlayer2.Player''' if self.window.current_song: self.window.pause() @dbus_method(MEDIA_PLAYER2_PLAYER_IFACE) def Stop(self): '''Stop is only used internally, mapping to pause instead.''' if self.window.current_song: self.window.pause() @dbus_method(MEDIA_PLAYER2_PLAYER_IFACE, in_signature='x') def Seek(self, Offset): '''Not Implemented''' pass @dbus_method(MEDIA_PLAYER2_PLAYER_IFACE, in_signature='s') def OpenUri(self, Uri): '''Not Implemented''' pass @dbus_method(MEDIA_PLAYER2_PLAYER_IFACE, in_signature='ox') def SetPosition(self, TrackId, Position): '''Not Implemented''' pass @dbus_method(MEDIA_PLAYER2_PLAYLISTS_IFACE, in_signature='uusb', out_signature='a(oss)') def GetPlaylists(self, Index, MaxCount, Order, ReverseOrder): '''(uusb) -> a(oss) Interface MediaPlayer2.Playlists''' playlists = self._playlists[:] always_first = [playlists.pop(0)] # the QuickMix if self._has_thumbprint_radio: always_first.append(playlists.pop(0)) # Thumbprint Radio if it exists if Order not in ('CreationDate', 'Alphabetical') or Order == 'Alphabetical': playlists = sorted(playlists, key=lambda playlists: playlists[1]) if ReverseOrder: playlists.reverse() playlists = always_first + playlists[Index:MaxCount - len(always_first)] return playlists @dbus_method(MEDIA_PLAYER2_PLAYLISTS_IFACE, in_signature='o') def ActivatePlaylist(self, PlaylistId): '''(o) -> nothing Interface MediaPlayer2.Playlists''' stations = self.window.pandora.stations station_id = PlaylistId.strip(self.PLAYLIST_OBJ_PATH) for station in stations: if station.id == station_id: self.window.station_changed(station) break @dbus_method(MEDIA_PLAYER2_TRACKLIST_IFACE, in_signature='ao', out_signature='aa{sv}') def GetTracksMetadata(self, TrackIds): '''(ao) -> aa{sv} Interface MediaPlayer2.TrackList''' return [self._metadata_list[self._tracks.index(TrackId)] for TrackId in TrackIds if TrackId in self._tracks] @dbus_method(MEDIA_PLAYER2_TRACKLIST_IFACE, in_signature='sob') def AddTrack(self, Uri, AfterTrack, SetAsCurrent): '''Not Implemented''' pass @dbus_method(MEDIA_PLAYER2_TRACKLIST_IFACE, in_signature='o') def RemoveTrack(self, TrackId): '''Not Implemented''' pass @dbus_method(MEDIA_PLAYER2_TRACKLIST_IFACE, in_signature='o') def GoTo(self, TrackId): '''(o) -> nothing Interface MediaPlayer2.TrackList''' song = self._song_from_track_id(TrackId) if song and song.index > self.window.current_song_index and not (song.tired or song.rating == 'ban'): self.window.start_song(song.index) @dbus_method(MEDIA_PLAYER2_RATINGS_IFACE, in_signature='o') def LoveSong(self, TrackId): '''(o) -> nothing Interface MediaPlayer2.ExtensionPithosRatings''' song = self._song_from_track_id(TrackId) if song: self.window.love_song(song=song) @dbus_method(MEDIA_PLAYER2_RATINGS_IFACE, in_signature='o') def BanSong(self, TrackId): '''(o) -> nothing Interface MediaPlayer2.ExtensionPithosRatings''' song = self._song_from_track_id(TrackId) if song: self.window.ban_song(song=song) @dbus_method(MEDIA_PLAYER2_RATINGS_IFACE, in_signature='o') def TiredSong(self, TrackId): '''(o) -> nothing Interface MediaPlayer2.ExtensionPithosRatings''' song = self._song_from_track_id(TrackId) if song: self.window.tired_song(song=song) @dbus_method(MEDIA_PLAYER2_RATINGS_IFACE, in_signature='o') def UnRateSong(self, TrackId): '''(o) -> nothing Interface MediaPlayer2.ExtensionPithosRatings''' song = self._song_from_track_id(TrackId) if song: self.window.unrate_song(song=song) @dbus_signal(MEDIA_PLAYER2_PLAYER_IFACE, signature='x') def Seeked(self, Position): '''x Interface MediaPlayer2.Player''' # Unsupported, but some applets depend on this. pass @dbus_signal(MEDIA_PLAYER2_PLAYLISTS_IFACE, signature='(oss)') def PlaylistChanged(self, Playlist): '''(oss) Interface MediaPlayer2.Playlists''' pass @dbus_signal(MEDIA_PLAYER2_TRACKLIST_IFACE, signature='aoo') def TrackListReplaced(self, Tracks, CurrentTrack): '''aoo Interface MediaPlayer2.TrackList''' pass @dbus_signal(MEDIA_PLAYER2_TRACKLIST_IFACE, signature='a{sv}o') def TrackAdded(self, Metadata, AfterTrack): '''a{sv}o Interface MediaPlayer2.TrackList''' pass @dbus_signal(MEDIA_PLAYER2_TRACKLIST_IFACE, signature='o') def TrackRemoved(self, TrackId): '''o Interface MediaPlayer2.TrackList''' pass @dbus_signal(MEDIA_PLAYER2_TRACKLIST_IFACE, signature='oa{sv}') def TrackMetadataChanged(self, TrackId, Metadata): '''oa{sv} Interface MediaPlayer2.TrackList''' pass def PropertiesChanged(self, interface, changed, invalidated): '''Emits mpris Property changes.''' try: self.connection.emit_signal(None, '/org/mpris/MediaPlayer2', 'org.freedesktop.DBus.Properties', 'PropertiesChanged', GLib.Variant.new_tuple( GLib.Variant('s', interface), GLib.Variant('a{sv}', changed), GLib.Variant('as', invalidated) )) except GLib.Error as e: logging.warning(e) class MprisPluginPrefsDialog(Gtk.Dialog): __gtype_name__ = 'MprisPluginPrefsDialog' def __init__(self, window, settings): super().__init__(use_header_bar=1) self.set_title(_('Hide on Close')) self.set_default_size(300, -1) self.set_resizable(False) self.connect('delete-event', self.on_close) self.pithos = window self.settings = settings self.delete_handler = None box = Gtk.Box() label = Gtk.Label() label.set_markup('{}\n{}'.format(_('Hide Pithos on Close'), _('Instead of Quitting'))) label.set_halign(Gtk.Align.START) box.pack_start(label, True, True, 4) self.switch = Gtk.Switch() self.switch.connect('notify::active', self.on_activated) self.switch.set_active(self.settings['data'] == 'True') self.settings.connect('changed::enabled', self._on_plugin_enabled) self.switch.set_halign(Gtk.Align.END) self.switch.set_valign(Gtk.Align.CENTER) box.pack_end(self.switch, False, False, 2) content_area = self.get_content_area() content_area.add(box) content_area.show_all() def on_close(self, window, event): window.hide() return True def on_activated(self, *ignore): if self.switch.get_active(): self.settings['data'] = 'True' self._enable_hide_on_delete() else: self.settings['data'] = 'False' self._disable_hide_on_delete() def _on_plugin_enabled(self, *ignore): if self.settings['enabled']: self.switch.set_active(self.settings['data'] == 'True') if self.switch.get_active(): self._enable_hide_on_delete() else: self._disable_hide_on_delete() else: self._disable_hide_on_delete() def _disable_hide_on_delete(self): if self.delete_handler: self.pithos.disconnect(self.delete_handler) self.delete_handler = self.pithos.connect('delete-event', self.pithos.on_destroy) def _enable_hide_on_delete(self): if self.delete_handler: self.pithos.disconnect(self.delete_handler) self.delete_handler = self.pithos.connect('delete-event', self.on_close) pithos-1.6.1/pithos/plugins/notification_icon.py000066400000000000000000000255231443173105600220770ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- # 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 . import logging import gi from gi.repository import ( GLib, Gio, Gtk ) try: gi.require_versions({ 'DbusmenuGtk3': '0.4', 'Dbusmenu': '0.4', }) from gi.repository import Dbusmenu, DbusmenuGtk3 have_dbusmenu = True logging.info('Imported Dbusmenu') except (ValueError, ImportError) as e: logging.info('Failed to import Dbusmenu: {}'.format(e)) have_dbusmenu = False from .dbus_util.DBusServiceObject import ( DBusServiceObject, dbus_method, dbus_property ) from pithos.plugin import PithosPlugin STATUS_NOTIFIER_WATCH_NAME = 'org.kde.StatusNotifierWatcher' STATUS_NOTIFIER_WATCH_PATH = '/StatusNotifierWatcher' STATUS_NOTIFIER_WATCH_IFACE = 'org.kde.StatusNotifierWatcher' DBUS_MENU_PATH = '/io/github/Pithos/notification_icon/menu' class PithosStatusNotifierItem(DBusServiceObject): STATUS_NOTIFIER_ITEM_IFACE = 'org.kde.StatusNotifierItem' STATUS_NOTIFIER_ITEM_PATH = '/StatusNotifierItem' def __init__(self, window, **kwargs): self.conn = kwargs.get('connection') self.icon = kwargs.pop('icon') super().__init__(object_path=self.STATUS_NOTIFIER_ITEM_PATH, **kwargs) self.window = window self.status = 'Passive' logging.info('PithosStatusNotifierItem created') def notify_property_change(self, prop): self.conn.emit_signal( STATUS_NOTIFIER_WATCH_NAME, self.STATUS_NOTIFIER_ITEM_PATH, self.STATUS_NOTIFIER_ITEM_IFACE, 'New' + prop, GLib.Variant('(s)', (self.status, )) if prop == 'Status' else None ) def set_active(self, active): self.status = 'Active' if active else 'Passive' self.notify_property_change('Status') def set_icon(self, icon): self.icon = icon self.notify_property_change('Icon') def toggle_visible(self, *args): if self.window.get_visible(): self.window.hide() else: self.window.bring_to_top() @dbus_property(STATUS_NOTIFIER_ITEM_IFACE, 's') def Id(self): return 'pithos' @dbus_property(STATUS_NOTIFIER_ITEM_IFACE, 's') def Title(self): return 'Pithos' @dbus_property(STATUS_NOTIFIER_ITEM_IFACE, 's') def Category(self): return 'ApplicationStatus' @dbus_property(STATUS_NOTIFIER_ITEM_IFACE, 's') def Status(self): return self.status @dbus_property(STATUS_NOTIFIER_ITEM_IFACE, 'u') def Window(self): return 0 # Not available on Wayland? @dbus_property(STATUS_NOTIFIER_ITEM_IFACE, 's') def IconName(self): return self.icon @dbus_property(STATUS_NOTIFIER_ITEM_IFACE, 's') def OverlayIconName(self): return '' @dbus_property(STATUS_NOTIFIER_ITEM_IFACE, 's') def AttentionIconName(self): return '' @dbus_property(STATUS_NOTIFIER_ITEM_IFACE, 'b') def ItemIsMenu(self): return False @dbus_property(STATUS_NOTIFIER_ITEM_IFACE, 'o') def Menu(self): return DBUS_MENU_PATH if have_dbusmenu else '/NO_DBUSMENU' @dbus_method(STATUS_NOTIFIER_ITEM_IFACE, 'ii') def Activate(self, x, y): self.toggle_visible() @dbus_method(STATUS_NOTIFIER_ITEM_IFACE, 'ii') def SecondaryActivate(self, x, y): self.toggle_visible() @dbus_method(STATUS_NOTIFIER_ITEM_IFACE, 'is') def Scroll(self, delta, orientation): if orientation == 'vertical': self.window.adjust_volume(-delta) class PithosNotificationIcon(PithosPlugin): preference = 'show_icon' description = 'Adds Pithos StatusNotifier to tray' def on_prepare(self): self.playpausebtn = None # Preferences for icon type if not self.settings['data']: self.settings['data'] = 'io.github.Pithos-tray-symbolic' self.preferences_dialog = NotificationIconPluginPrefsDialog(self.window, self.settings) def on_icon_theme_changed(settings, key): if self.statusnotifieritem: self.statusnotifieritem.set_icon(settings[key]) self.settings.connect('changed::data', on_icon_theme_changed) self.registered = False def on_registered_signal(conn, sender, path, iface, signal, params, user_data): bus_id = params.get_child_value(0).get_string() if bus_id.startswith(self.bus_id): logging.info('StatusNotifierItemRegistered') self.registered = True def on_unregistered_signal(conn, sender, path, iface, signal, params, user_data): bus_id = params.get_child_value(0).get_string() if bus_id.startswith(self.bus_id): logging.info('StatusNotifierItemUnregistered') self.registered = False self._show_window() def on_watcher_appeared(conn, name, name_owner, user_data=None): self.registered_signal_handler = conn.signal_subscribe( STATUS_NOTIFIER_WATCH_NAME, STATUS_NOTIFIER_WATCH_IFACE, 'StatusNotifierItemRegistered', STATUS_NOTIFIER_WATCH_PATH, None, Gio.DBusSignalFlags.NONE, on_registered_signal, None ) self.unregistered_signal_handler = conn.signal_subscribe( STATUS_NOTIFIER_WATCH_NAME, STATUS_NOTIFIER_WATCH_IFACE, 'StatusNotifierItemUnregistered', STATUS_NOTIFIER_WATCH_PATH, None, Gio.DBusSignalFlags.NONE, on_unregistered_signal, None ) self.bus_id = conn.get_unique_name() logging.info('Calling RegisterStatusNotifierItem("{}")'.format(self.bus_id)) conn.call( STATUS_NOTIFIER_WATCH_NAME, STATUS_NOTIFIER_WATCH_PATH, STATUS_NOTIFIER_WATCH_IFACE, 'RegisterStatusNotifierItem', GLib.Variant('(s)', (self.bus_id, )), None, Gio.DBusCallFlags.NONE, -1, None, None ) def on_watcher_disappear(conn, name, user_data=None): logging.info('StatusNotifierWatcher disappeared') if hasattr(self, 'registered_signal_handler'): conn.signal_unsubscribe(self.registered_signal_handler) del self.registered_signal_handler if hasattr(self, 'unregistered_signal_handler'): conn.signal_unsubscribe(self.unregistered_signal_handler) del self.unregistered_signal_handler self.registered = False self._show_window() Gio.bus_watch_name_on_connection( self.bus, STATUS_NOTIFIER_WATCH_NAME, Gio.BusNameWatcherFlags.AUTO_START, on_watcher_appeared, on_watcher_disappear ) self._setup_dbusmenu() self.statusnotifieritem = PithosStatusNotifierItem(self.window, connection=self.bus, icon=self.settings['data']) self.prepare_complete() def _play_state_changed(self, window, playing): if self.playpausebtn: self.playpausebtn.set_label("Pause" if playing else "Play") def _build_context_menu(self): menu = Gtk.Menu() def button(text, action): item = Gtk.MenuItem(text) item.connect('activate', action) item.show() menu.append(item) return item 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) self.menu = menu def _setup_dbusmenu(self): if not have_dbusmenu: return self._build_context_menu() self.dbusmenuservice = Dbusmenu.Server.new(DBUS_MENU_PATH) self.dbusmenuservice.set_root(DbusmenuGtk3.gtk_parse_menu_structure(self.menu)) def _show_window(self): if not self.window.get_visible(): self.window.show() def _toggle_visible(self, *args): if self.registered: self.statusnotifieritem.toggle_visible() return True 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.statusnotifieritem.set_active(True) def on_disable(self): self.window.disconnect(self.delete_callback_handle) self.window.disconnect(self.state_callback_handle) self.statusnotifieritem.set_active(False) class NotificationIconPluginPrefsDialog(Gtk.Dialog): def __init__(self, parent, settings): super().__init__( title=_('Icon Type'), transient_for=parent, use_header_bar=1, resizable=False, default_width=300 ) self.settings = settings self.add_buttons('_Cancel', Gtk.ResponseType.CANCEL, '_Apply', Gtk.ResponseType.APPLY) self.connect('delete-event', lambda *ignore: self.response(Gtk.ResponseType.CANCEL) or True) sub_title = Gtk.Label.new(_('Set the Notification Icon Type')) sub_title.set_halign(Gtk.Align.CENTER) self.icons_combo = Gtk.ComboBoxText.new() icons = ( ('io.github.Pithos-tray', _('Full Color')), ('io.github.Pithos-symbolic', _('Symbolic')), ) for icon in icons: self.icons_combo.append(icon[0], icon[1]) self._reset_combo() content_area = self.get_content_area() content_area.add(sub_title) content_area.add(self.icons_combo) content_area.show_all() def _reset_combo(self): self.icons_combo.set_active_id(self.settings['data']) def do_response(self, response): if response == Gtk.ResponseType.APPLY: self.settings['data'] = self.icons_combo.get_active_id() else: self._reset_combo() self.hide() pithos-1.6.1/pithos/plugins/notify.py000066400000000000000000000062531443173105600177100ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- # 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 . import os from gi.repository import Gio from pithos.plugin import PithosPlugin from pithos.util import is_flatpak class NotifyPlugin(PithosPlugin): preference = 'notify' description = 'Shows notifications on song change' _app = None _app_id = None _fallback_icon = None def on_prepare(self): # We prefer the behavior of the fdo backend to the gtk backend # as it doesn't force persistence which doesn't make sense for # this application. if not is_flatpak(): os.environ['GNOTIFICATION_BACKEND'] = 'freedesktop' self._app = Gio.Application.get_default() self._app_id = self._app.get_application_id() self._fallback_icon = Gio.ThemedIcon.new('audio-x-generic') self.prepare_complete() def on_enable(self): self._song_change_handler = self.window.connect('song-changed', self.send_notification) self._shutdown_handler = self._app.connect('shutdown', lambda app: app.withdraw_notification(self._app_id)) def send_notification(self, window, *ignore): if window.is_active(): # GNOME-Shell will auto dismiss notifications # when the window becomes "active" but other DE's may not (KDE for example). # If we're not going to replace a previous notification # we should withdraw said stale previous notification. self._app.withdraw_notification(self._app_id) else: song = window.current_song # This matches GNOME-Shell's format notification = Gio.Notification.new(song.artist) # GNOME focuses the application by default, we want to match that behavior elsewhere such as on KDE. notification.set_default_action('app.activate') notification.set_body(song.title) if song.artUrl: icon = Gio.FileIcon.new(Gio.File.new_for_uri(song.artUrl)) else: icon = self._fallback_icon notification.set_icon(icon) notification.add_button(_('Skip'), 'app.next-song') self._app.send_notification(self._app_id, notification) def on_disable(self): self._app.withdraw_notification(self._app_id) if self._song_change_handler: self.window.disconnect(self._song_change_handler) self._song_change_handler = 0 if self._shutdown_handler: self._app.disconnect(self._shutdown_handler) self._shutdown_handler = 0 pithos-1.6.1/pithos/plugins/screensaver_pause.py000066400000000000000000000034511443173105600221120ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- # 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 . from gi.repository import Gio from pithos.plugin import PithosPlugin class ScreenSaverPausePlugin(PithosPlugin): preference = 'enable_screensaverpause' description = 'Pause playback on screensaver' _signal_handle = 0 _app = None _wasplaying = False def on_prepare(self): self._app = Gio.Application.get_default() if not hasattr(self._app.props, 'screensaver_active'): self.prepare_complete(error='Gtk 3.24+ required') else: self.prepare_complete() def _on_screensaver_active(self, pspec, user_data=None): if self._app.props.screensaver_active: self._wasplaying = self.window.playing self.window.pause() elif self._wasplaying: self.window.user_play() def on_enable(self): self._signal_handle = self._app.connect('notify::screensaver-active', self._on_screensaver_active) def on_disable(self): if self._signal_handle: self._app.disconnect(self._signal_handle) self._signal_handle = 0 pithos-1.6.1/pithos/util.py000066400000000000000000000211731443173105600156720ustar00rootroot00000000000000# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- # 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 . import logging import os from urllib.parse import splittype, splituser, splitpasswd import gi gi.require_version('Secret', '1') from gi.repository import ( GLib, Secret, Gtk ) class _SecretService: _account_schema = Secret.Schema.new( 'io.github.Pithos.Account', Secret.SchemaFlags.NONE, {'email': Secret.SchemaAttributeType.STRING}, ) def __init__(self): self._current_collection = Secret.COLLECTION_DEFAULT def unlock_keyring(self, callback): # Inside of flatpak we only have access to the simple API. if is_flatpak(): callback(None) return def on_unlock_finish(source, result, data): service, default_collection = data try: num_items, unlocked = service.unlock_finish(result) except GLib.Error as e: logging.error('Error on service.unlock, Error: {}'.format(e)) callback(e) else: if not num_items or default_collection not in unlocked: self._current_collection = Secret.COLLECTION_SESSION logging.debug('The default keyring is still locked. Using session collection.') else: logging.debug('The default keyring was unlocked.') callback(None) def on_for_alias_finish(source, result, service): try: default_collection = Secret.Collection.for_alias_finish(result) except GLib.Error as e: logging.error('Error getting Secret.COLLECTION_DEFAULT, Error: {}'.format(e)) callback(e) else: if default_collection is None: logging.warning( 'Could not get the default Secret Collection.\n' 'Attempting to use the session Collection.' ) self._current_collection = Secret.COLLECTION_SESSION callback(None) elif default_collection.get_locked(): logging.debug('The default keyring is locked.') service.unlock( [default_collection], None, on_unlock_finish, (service, default_collection), ) else: logging.debug('The default keyring is unlocked.') callback(None) def on_get_finish(source, result, data): try: service = Secret.Service.get_finish(result) except GLib.Error as e: logging.error('Failed to get Secret.Service, Error: {}'.format(e)) callback(e) else: Secret.Collection.for_alias( service, Secret.COLLECTION_DEFAULT, Secret.CollectionFlags.NONE, None, on_for_alias_finish, service, ) Secret.Service.get( Secret.ServiceFlags.NONE, None, on_get_finish, None, ) def get_account_password(self, email, callback): def on_password_lookup_finish(_, result): try: password = Secret.password_lookup_finish(result) or '' callback(password) except GLib.Error as e: logging.error('Failed to lookup password async, Error: {}'.format(e)) callback('') # The async version of this hangs forever in flatpak and its been broken for years # so for now lets just use the sync version as it works. if is_flatpak(): try: password = Secret.password_lookup_sync( self._account_schema, {'email': email}, None, ) or '' callback(password) except GLib.Error as e: logging.error('Failed to lookup password sync, Error: {}'.format(e)) callback('') return Secret.password_lookup( self._account_schema, {'email': email}, None, on_password_lookup_finish, ) def set_account_password(self, old_email, new_email, password, callback): def on_password_store_finish(source, result, data): try: success = Secret.password_store_finish(result) except GLib.Error as e: logging.error('Failed to store password, Error: {}'.format(e)) success = False if callback: callback(success) def on_password_clear_finish(source, result, data): try: password_removed = Secret.password_clear_finish(result) if password_removed: logging.debug('Cleared password for: {}'.format(old_email)) else: logging.debug('No password found to clear for: {}'.format(old_email)) except GLib.Error as e: logging.error('Failed to clear password for: {}, Error: {}'.format(old_email, e)) if callback: callback(False) else: Secret.password_store( self._account_schema, {'email': new_email}, self._current_collection, 'Pandora Account', password, None, on_password_store_finish, None, ) if old_email and old_email != new_email: Secret.password_clear( self._account_schema, {'email': old_email}, None, on_password_clear_finish, None, ) else: Secret.password_store( self._account_schema, {'email': new_email}, self._current_collection, 'Pandora Account', password, None, on_password_store_finish, None, ) SecretService = _SecretService() 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, parent=None, timestamp=0): logging.info("Opening URL {}".format(url)) if not timestamp: timestamp = Gtk.get_current_event_time() try: if hasattr(Gtk, 'show_uri_on_window'): Gtk.show_uri_on_window(parent, url, timestamp) else: # Gtk <= 3.20 screen = None if parent: screen = parent.get_screen() Gtk.show_uri(screen, url, timestamp) except GLib.Error as e: logging.warning('Failed to open URL: {}'.format(e.message)) if hasattr(Gtk.Menu, 'popup_at_pointer'): popup_at_pointer = Gtk.Menu.popup_at_pointer else: popup_at_pointer = lambda menu, event: menu.popup(None, None, None, None, event.button, event.time) _is_flatpak = None def is_flatpak() -> bool: global _is_flatpak if _is_flatpak is None: _is_flatpak = os.path.exists('/.flatpak-info') return _is_flatpak pithos-1.6.1/po/000077500000000000000000000000001443173105600134475ustar00rootroot00000000000000pithos-1.6.1/po/LINGUAS000066400000000000000000000000001443173105600144620ustar00rootroot00000000000000pithos-1.6.1/po/POTFILES000066400000000000000000000010141443173105600146130ustar00rootroot00000000000000data/io.github.Pithos.appdata.xml.in data/io.github.Pithos.desktop.in data/io.github.Pithos.gschema.xml data/ui/AboutPithosDialog.ui data/ui/PithosWindow.ui data/ui/PreferencesPithosDialog.ui data/ui/SearchDialog.ui data/ui/StationsDialog.ui data/gtk/menus.ui data/gtk/help-overlay.ui pithos/application.py pithos/pithos.py pithos/StationsPopover.py pithos/PreferencesPithosDialog.py pithos/plugins/journald_logging.py pithos/plugins/lastfm.py pithos/plugins/notification_icon.py pithos/plugins/auto_volume_normalization.py pithos-1.6.1/po/meson.build000066400000000000000000000000631443173105600156100ustar00rootroot00000000000000i18n.gettext(meson.project_name(), preset: 'glib') pithos-1.6.1/setup.cfg000066400000000000000000000005401443173105600146510ustar00rootroot00000000000000[flake8] # Conflicts with gi.require_version() usage # E402 module level import not at top of file # These just go against personal style: # E227 missing whitespace around bitwise or shift operator # E261 at least two spaces before inline comment ignore = E261,E227,E402 exclude = docs,pithos/gi_composites.py max-line-length = 120 builtins = _ pithos-1.6.1/zanata.xml000066400000000000000000000006521443173105600150340ustar00rootroot00000000000000 https://translate.zanata.org/zanata pithos master gettext po po {locale}.po es