diff -Nru pithos-1.1.2/.editorconfig pithos-1.6.2/.editorconfig --- pithos-1.1.2/.editorconfig 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/.editorconfig 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,18 @@ +root = 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 diff -Nru pithos-1.1.2/.github/FUNDING.yml pithos-1.6.2/.github/FUNDING.yml --- pithos-1.1.2/.github/FUNDING.yml 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/.github/FUNDING.yml 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1 @@ +github: [TingPing, JasonLG1979] diff -Nru pithos-1.1.2/.github/workflows/CI.yml pithos-1.6.2/.github/workflows/CI.yml --- pithos-1.1.2/.github/workflows/CI.yml 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/.github/workflows/CI.yml 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,21 @@ +on: + 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" diff -Nru pithos-1.1.2/.github/workflows/codeql.yml pithos-1.6.2/.github/workflows/codeql.yml --- pithos-1.1.2/.github/workflows/codeql.yml 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/.github/workflows/codeql.yml 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,41 @@ +name: "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 }}" diff -Nru pithos-1.1.2/.gitignore pithos-1.6.2/.gitignore --- pithos-1.1.2/.gitignore 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/.gitignore 2024-03-03 23:53:20.000000000 +0000 @@ -1,22 +1,4 @@ +/build/ +/po/*.pot +*.tar.xz __pycache__/ -*.py[cod] -bin/ -build/ -develop-eggs/ -dist/ -eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -*.egg-info/ -.installed.cfg -*.egg -config/ -*.patch -debian/ -build-debian.sh -.project -.pydevproject -.settings/ diff -Nru pithos-1.1.2/MANIFEST.in pithos-1.6.2/MANIFEST.in --- pithos-1.1.2/MANIFEST.in 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/MANIFEST.in 1970-01-01 00:00:00.000000000 +0000 @@ -1,4 +0,0 @@ -include README.md -recursive-include data *.svg pithos.desktop *.xml -recursive-include pithos/data/ui *.ui *.xml -recursive-include pithos/data/media *.png *.svg diff -Nru pithos-1.1.2/bin/meson.build pithos-1.6.2/bin/meson.build --- pithos-1.1.2/bin/meson.build 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/bin/meson.build 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,23 @@ +prefix = 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 + ] +) diff -Nru pithos-1.1.2/bin/pithos.in pithos-1.6.2/bin/pithos.in --- pithos-1.1.2/bin/pithos.in 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/bin/pithos.in 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,48 @@ +#!/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) diff -Nru pithos-1.1.2/data/gtk/help-overlay.ui pithos-1.6.2/data/gtk/help-overlay.ui --- pithos-1.1.2/data/gtk/help-overlay.ui 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/data/gtk/help-overlay.ui 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,92 @@ + + + + + 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 + + + + + + + + + Binary files /tmp/tmpbqegcfwp/Xym0jYgLpO/pithos-1.1.2/data/icons/hicolor/48x48/apps/io.github.Pithos-tray.png and /tmp/tmpbqegcfwp/1xdaNWyxyt/pithos-1.6.2/data/icons/hicolor/48x48/apps/io.github.Pithos-tray.png differ Binary files /tmp/tmpbqegcfwp/Xym0jYgLpO/pithos-1.1.2/data/icons/hicolor/pithos-tray-icon.png and /tmp/tmpbqegcfwp/1xdaNWyxyt/pithos-1.6.2/data/icons/hicolor/pithos-tray-icon.png differ diff -Nru pithos-1.1.2/data/icons/hicolor/pithos-tray-icon.svg pithos-1.6.2/data/icons/hicolor/pithos-tray-icon.svg --- pithos-1.1.2/data/icons/hicolor/pithos-tray-icon.svg 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/data/icons/hicolor/pithos-tray-icon.svg 1970-01-01 00:00:00.000000000 +0000 @@ -1,531 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff -Nru pithos-1.1.2/data/icons/hicolor/pithos.svg pithos-1.6.2/data/icons/hicolor/pithos.svg --- pithos-1.1.2/data/icons/hicolor/pithos.svg 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/data/icons/hicolor/pithos.svg 1970-01-01 00:00:00.000000000 +0000 @@ -1,475 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff -Nru pithos-1.1.2/data/icons/hicolor/scalable/apps/io.github.Pithos-tray.svg pithos-1.6.2/data/icons/hicolor/scalable/apps/io.github.Pithos-tray.svg --- pithos-1.1.2/data/icons/hicolor/scalable/apps/io.github.Pithos-tray.svg 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/data/icons/hicolor/scalable/apps/io.github.Pithos-tray.svg 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,531 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff -Nru pithos-1.1.2/data/icons/hicolor/scalable/apps/io.github.Pithos.svg pithos-1.6.2/data/icons/hicolor/scalable/apps/io.github.Pithos.svg --- pithos-1.1.2/data/icons/hicolor/scalable/apps/io.github.Pithos.svg 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/data/icons/hicolor/scalable/apps/io.github.Pithos.svg 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,475 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff -Nru pithos-1.1.2/data/icons/hicolor/symbolic/apps/io.github.Pithos-symbolic.svg pithos-1.6.2/data/icons/hicolor/symbolic/apps/io.github.Pithos-symbolic.svg --- pithos-1.1.2/data/icons/hicolor/symbolic/apps/io.github.Pithos-symbolic.svg 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/data/icons/hicolor/symbolic/apps/io.github.Pithos-symbolic.svg 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,39 @@ + + + + + + + image/svg+xml + + + + + + + + + + diff -Nru pithos-1.1.2/data/icons/meson.build pithos-1.6.2/data/icons/meson.build --- pithos-1.1.2/data/icons/meson.build 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/data/icons/meson.build 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,38 @@ +themes = [ + ['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 diff -Nru pithos-1.1.2/data/icons/ubuntu-mono-dark/16x16/apps/io.github.Pithos-tray.svg pithos-1.6.2/data/icons/ubuntu-mono-dark/16x16/apps/io.github.Pithos-tray.svg --- pithos-1.1.2/data/icons/ubuntu-mono-dark/16x16/apps/io.github.Pithos-tray.svg 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/data/icons/ubuntu-mono-dark/16x16/apps/io.github.Pithos-tray.svg 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,16 @@ + + + + + + image/svg+xml + + + + + + + + + + diff -Nru pithos-1.1.2/data/icons/ubuntu-mono-dark/pithos-tray-icon.svg pithos-1.6.2/data/icons/ubuntu-mono-dark/pithos-tray-icon.svg --- pithos-1.1.2/data/icons/ubuntu-mono-dark/pithos-tray-icon.svg 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/data/icons/ubuntu-mono-dark/pithos-tray-icon.svg 1970-01-01 00:00:00.000000000 +0000 @@ -1,16 +0,0 @@ - - - - - - image/svg+xml - - - - - - - - - - diff -Nru pithos-1.1.2/data/icons/ubuntu-mono-light/16x16/apps/io.github.Pithos-tray.svg pithos-1.6.2/data/icons/ubuntu-mono-light/16x16/apps/io.github.Pithos-tray.svg --- pithos-1.1.2/data/icons/ubuntu-mono-light/16x16/apps/io.github.Pithos-tray.svg 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/data/icons/ubuntu-mono-light/16x16/apps/io.github.Pithos-tray.svg 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,16 @@ + + + + + + image/svg+xml + + + + + + + + + + diff -Nru pithos-1.1.2/data/icons/ubuntu-mono-light/pithos-tray-icon.svg pithos-1.6.2/data/icons/ubuntu-mono-light/pithos-tray-icon.svg --- pithos-1.1.2/data/icons/ubuntu-mono-light/pithos-tray-icon.svg 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/data/icons/ubuntu-mono-light/pithos-tray-icon.svg 1970-01-01 00:00:00.000000000 +0000 @@ -1,16 +0,0 @@ - - - - - - image/svg+xml - - - - - - - - - - diff -Nru pithos-1.1.2/data/io.github.Pithos.appdata.xml.in pithos-1.6.2/data/io.github.Pithos.appdata.xml.in --- pithos-1.1.2/data/io.github.Pithos.appdata.xml.in 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/data/io.github.Pithos.appdata.xml.in 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,187 @@ + + + io.github.Pithos + io.github.Pithos.desktop + pithos + Pithos + Pithos + Pandora radio client + CC0-1.0 + GPL-3.0+ + +

An 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 many features such as last.fm scrobbling

+
+ 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 + + #e6d4ff + #644b93 + + + + https://i.imgur.com/RzMCls4.png + Main Window showing a playlist + + + https://i.imgur.com/5tcEhkp.png + Dialog showing available plugins + + + https://i.imgur.com/NyQ0uZB.png + Dark variant of the main window + + + + + +

This is a small release with a few fixes

+
    +
  • Fix issue where playback would stop after a few songs
  • +
  • Fix album art caches never being deleted
  • +
+
+
+ + +

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 +
diff -Nru pithos-1.1.2/data/io.github.Pithos.desktop.in pithos-1.6.2/data/io.github.Pithos.desktop.in --- pithos-1.1.2/data/io.github.Pithos.desktop.in 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/data/io.github.Pithos.desktop.in 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,10 @@ +[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 diff -Nru pithos-1.1.2/data/io.github.Pithos.gresource.xml pithos-1.6.2/data/io.github.Pithos.gresource.xml --- pithos-1.1.2/data/io.github.Pithos.gresource.xml 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/data/io.github.Pithos.gresource.xml 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,13 @@ + + + + gtk/help-overlay.ui + + ui/PithosWindow.ui + ui/AboutPithosDialog.ui + ui/PreferencesPithosDialog.ui + ui/SearchDialog.ui + ui/StationsDialog.ui + ui/EqDialog.ui + + diff -Nru pithos-1.1.2/data/io.github.Pithos.gschema.xml pithos-1.6.2/data/io.github.Pithos.gschema.xml --- pithos-1.1.2/data/io.github.Pithos.gschema.xml 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/data/io.github.Pithos.gschema.xml 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,104 @@ + + + + + + "" + 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 + + + + diff -Nru pithos-1.1.2/data/io.github.Pithos.service.in pithos-1.6.2/data/io.github.Pithos.service.in --- pithos-1.1.2/data/io.github.Pithos.service.in 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/data/io.github.Pithos.service.in 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,3 @@ +[D-BUS Service] +Name=io.github.Pithos +Exec=@bindir@/pithos --gapplication-service diff -Nru pithos-1.1.2/data/meson.build pithos-1.6.2/data/meson.build --- pithos-1.1.2/data/meson.build 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/data/meson.build 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,83 @@ +gnome = 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') diff -Nru pithos-1.1.2/data/pithos.appdata.xml pithos-1.6.2/data/pithos.appdata.xml --- pithos-1.1.2/data/pithos.appdata.xml 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/data/pithos.appdata.xml 1970-01-01 00:00:00.000000000 +0000 @@ -1,15 +0,0 @@ - - - pithos.desktop - CC0 - GPL-3.0+ - -

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

-

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

-
- https://pithos.github.io - - https://i.imgur.com/1vl3Dsk.png - - tingping_at_fedoraproject.org -
diff -Nru pithos-1.1.2/data/pithos.desktop pithos-1.6.2/data/pithos.desktop --- pithos-1.1.2/data/pithos.desktop 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/data/pithos.desktop 1970-01-01 00:00:00.000000000 +0000 @@ -1,8 +0,0 @@ -[Desktop Entry] -Name=Pithos -Comment=Play music from Pandora Radio -Categories=GNOME;AudioVideo;Player; -Exec=pithos -Icon=pithos -Terminal=false -Type=Application diff -Nru pithos-1.1.2/data/ui/AboutPithosDialog.ui pithos-1.6.2/data/ui/AboutPithosDialog.ui --- pithos-1.1.2/data/ui/AboutPithosDialog.ui 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/data/ui/AboutPithosDialog.ui 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,22 @@ + + + + + + diff -Nru pithos-1.1.2/data/ui/EqDialog.ui pithos-1.6.2/data/ui/EqDialog.ui --- pithos-1.1.2/data/ui/EqDialog.ui 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/data/ui/EqDialog.ui 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,466 @@ + + + + + + -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 + + + diff -Nru pithos-1.1.2/data/ui/PithosWindow.ui pithos-1.6.2/data/ui/PithosWindow.ui --- pithos-1.1.2/data/ui/PithosWindow.ui 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/data/ui/PithosWindow.ui 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,435 @@ + + + + + +
+ + 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 + + + + + + + + +
diff -Nru pithos-1.1.2/data/ui/PreferencesPithosDialog.ui pithos-1.6.2/data/ui/PreferencesPithosDialog.ui --- pithos-1.1.2/data/ui/PreferencesPithosDialog.ui 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/data/ui/PreferencesPithosDialog.ui 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,368 @@ + + + + + + diff -Nru pithos-1.1.2/data/ui/SearchDialog.ui pithos-1.6.2/data/ui/SearchDialog.ui --- pithos-1.1.2/data/ui/SearchDialog.ui 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/data/ui/SearchDialog.ui 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,86 @@ + + + + + + diff -Nru pithos-1.1.2/data/ui/StationsDialog.ui pithos-1.6.2/data/ui/StationsDialog.ui --- pithos-1.1.2/data/ui/StationsDialog.ui 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/data/ui/StationsDialog.ui 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,121 @@ + + + + + + + StationsDialog + warning + + + Yes + 1 + 1 + + + + + No + 1 + + + + button_no + button_yes + + + + + + 1 + Listen Now + + + + + + 1 + Info + + + + + + 1 + Rename + + + + + + 1 + Delete + + + + + diff -Nru pithos-1.1.2/debian/changelog pithos-1.6.2/debian/changelog --- pithos-1.1.2/debian/changelog 2021-01-03 13:24:58.000000000 +0000 +++ pithos-1.6.2/debian/changelog 2022-09-29 21:49:19.000000000 +0000 @@ -1,143 +1,13 @@ -pithos (1.1.2-1.1) unstable; urgency=medium +pithos (1.6.2-0ubuntu23.10) mantic; urgency=medium - * Non maintainer upload by the Reproducible Builds team. - * No source change upload to rebuild on buildd with .buildinfo files. + * Fix issue where playback would stop after a few songs + * Fix album art caches never being deleted - -- Holger Levsen Sun, 03 Jan 2021 14:24:58 +0100 + -- pandajim (key for lives deb) Tue, 29 Sep 2022 21:49:19 +0000 -pithos (1.1.2-1) unstable; urgency=medium +pithos (1.6.1-0ubuntu22.04) jammy; urgency=medium - * New upstream version - * Correct filenamemangle rule in debian/watch + * Fix Python 3.11 (ubuntu 23.04, Fedora 38) support. + * Fix very short songs being labeled as ads. - -- Luke Faraone Sun, 06 Mar 2016 03:56:58 +0000 - -pithos (1.1.1-2) unstable; urgency=medium - - * Correct GStreamer dependency. (Thanks Unit 193!) - - -- Luke Faraone Sat, 11 Jul 2015 23:47:38 +0000 - -pithos (1.1.1-1) unstable; urgency=medium - - * New upstream version. (closes: #696496, #785914, #746613) - * Update dependencies (upstream migrated to Python3 and GI) - * Update copyright, reword description, correct homepage/watchfile - * Switch to pybuild, drop CDBS - * Debhelper compat to 9 - - -- Luke Faraone Sat, 11 Jul 2015 17:42:45 +0000 - -pithos (0.3.17-2) unstable; urgency=low - - * Add dependency on pandoc-data to fix FTBFS (closes: #724198) - * Increase standards version, no changes needed. - - -- Luke Faraone Sun, 22 Sep 2013 16:45:59 -0400 - -pithos (0.3.17-1) unstable; urgency=low - - * New upstream bugfix and UX improvement release - - Switch to JSON API. (closes: #670676, LP: #988395) - - -- Luke Faraone Thu, 03 May 2012 23:48:44 -0400 - -pithos (0.3.14-1) unstable; urgency=high - - * New upstream bugfix release: - - Avoid "You have no chance to survive make your time" error (LP: #743198) - - -- Luke Faraone Thu, 05 Jan 2012 00:11:10 -0500 - -pithos (0.3.13-1) unstable; urgency=high - - * New upstream bugfix release, fixing among other bugs: - - Support protocol 33. (closes: #648210, LP: #887886) - - -- Luke Faraone Wed, 09 Nov 2011 14:39:02 -0500 - -pithos (0.3.11-1) unstable; urgency=low - - * New upstream bugfix release - - Support protocol 32. (closes: #642377, LP: #856035) - - -- Luke Faraone Fri, 30 Sep 2011 12:39:05 -0400 - -pithos (0.3.10-1) unstable; urgency=high - - * New upstream bugfix release. - - Support protocol 31. (LP: #672258) - - -- Luke Faraone Sat, 09 Jul 2011 16:31:02 -0400 - -pithos (0.3.9-1) unstable; urgency=medium - - * New upstream bugfix release. - - Support protocol 30. (LP: #771804, closes: #624324) - - Enable gstreamer progressive download to improve stream quality. - (LP: #705271) - - -- Luke Faraone Wed, 27 Apr 2011 23:02:20 -0400 - -pithos (0.3.8-1) unstable; urgency=high - - * New upstream bugfix release. - * SECURITY UPDATE: Pandora password leak to local users. (LP: #733307) - - pithos/PreferencesPithosDialog.py: correct mode on pithos.ini on next - run of pithos - - bin/pithos: run permissions fixer, resave pithos.ini if fix applied - - CVE-2011-1500 - * Drop 0001_cell_background_fix.patch and - 0002_long_song_format_fix_lp734962.patch, integrated upstream. - - -- Luke Faraone Tue, 12 Apr 2011 20:17:54 -0400 - -pithos (0.3.7-3) unstable; urgency=low - - * Correctly handle hour-long songs. (LP: #734962) - * Switch to dh_python2. (closes: #616939) - * Bump standards version, no changes needed. - - -- Luke Faraone Thu, 07 Apr 2011 14:49:08 -0400 - -pithos (0.3.7-2) unstable; urgency=low - - * Re-include lost entries in changelog. - * Fix TypeError when skipping songs under certain unlikely conditions. - Thanks to Rick Spencer for the patch. (LP: #706681) - - -- Luke Faraone Sat, 05 Mar 2011 23:15:21 -0500 - -pithos (0.3.7-1) unstable; urgency=low - - * New upstream version. - - -- Luke Faraone Tue, 08 Feb 2011 12:48:01 -0500 - -pithos (0.3.6-1) unstable; urgency=medium - - * New upstream version. - - Support protocol 29. - - -- Luke Faraone Sat, 06 Nov 2010 17:46:43 -0400 - -pithos (0.3.5-1) unstable; urgency=high - - * New upstream version. - - SECURITY UPDATE: fixes overwriting of arbitrary file via symlinks - (LP: #667896) - - -- Luke Faraone Sun, 31 Oct 2010 11:38:06 -0400 - -pithos (0.3.3-1) unstable; urgency=low - - * New upstream version. - - Support new Pandora API. (Closes: 599338) - - -- Luke Faraone Mon, 11 Oct 2010 15:54:28 -0400 - -pithos (0.3.2-1) unstable; urgency=low - - * Initial release (Closes: #597985) - - -- Luke Faraone Sat, 25 Sep 2010 23:35:44 -0400 + -- pandajim (key for lives deb) Tue, 29 Sep 2022 21:49:19 +0000 diff -Nru pithos-1.1.2/debian/control pithos-1.6.2/debian/control --- pithos-1.1.2/debian/control 2016-03-06 03:57:10.000000000 +0000 +++ pithos-1.6.2/debian/control 2019-11-05 21:49:19.000000000 +0000 @@ -1,41 +1,41 @@ Source: pithos Section: gnome Priority: optional -Maintainer: Luke Faraone -Build-Depends: debhelper (>= 9), dh-python, pandoc, pandoc-data, python3, - python3-setuptools, python3-sphinx -Standards-Version: 3.9.6 -Homepage: https://pithos.github.io/ -Vcs-Bzr: https://alioth.debian.org/scm/loggerhead/collab-maint/pithos/ -X-Python3-Version: >=3.2 +Maintainer: Patrick Griffis +Homepage: https://pithos.github.io +Standards-Version: 3.9.7 +X-Python3-Version: >= 3.4 +Build-Depends: + debhelper (>= 9), + dh-autoreconf, + meson (>= 0.5.0), + python3 (>= 3.4), + pkg-config, + intltool, + libglib2.0-dev, + libgdk-pixbuf2.0-dev Package: pithos Architecture: all -Depends: ${python3:Depends}, ${misc:Depends}, - gstreamer1.0-plugins-good, - gstreamer1.0-plugins-bad, - python3-pkg-resources, +Depends: + ${misc:Depends}, + ${autoreconf:Depends}, python3-gi, python3-gi-cairo, gir1.2-gtk-3.0, + gir1.2-secret-1, gir1.2-gstreamer-1.0, gir1.2-gst-plugins-base-1.0, -Recommends: python3-dbus, + gstreamer1.0-plugins-good, + gstreamer1.0-plugins-bad +Recommends: python3-pylast, gir1.2-appindicator3-0.1, gir1.2-keybinder-3.0, - gir1.2-notify-0.7, gnome-icon-theme-symbolic, -Description: Pandora Radio client for the GNOME desktop - Pithos is a cross-platform desktop client for the personalized web - radio Pandora, supporting all important features the official Flashâ„¢ - client has. - . - Pithos was based on pianobar, a console client for Pandora. In addition - to sporting a GTK+ GUI, Pithos has feature-parity with pianobar. - . - Out of concern for the longevity of Pandora Media Inc., the - software authors would recommend subscribing to Pandora One. - . - Use of this application requires a Pandora account; one can be created - for free at https://pandora.com. + gnome-keyring +Description: Pandora.com client for the GNOME desktop + 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. + diff -Nru pithos-1.1.2/debian/copyright pithos-1.6.2/debian/copyright --- pithos-1.1.2/debian/copyright 2016-03-06 03:57:10.000000000 +0000 +++ pithos-1.6.2/debian/copyright 2018-10-31 12:49:33.000000000 +0000 @@ -1,719 +1,10 @@ -Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ -Source: https://github.com/pithos/pithos/releases +Format-Specification: http://wiki.debian.org/Proposals/CopyrightFormat +Upstream-Name: pithos +Upstream-Maintainer: Pithos Team +Upstream-Source: https://github.com/pithos/pithos Files: * -Copyright: © 2010-2012 Kevin Mehall -License: GPL-3 - -Files: ./pithos/plugins/_mpris.py ./pithos/plugins/mpris.py -Copyright: 2011-2012 Kevin Mehall , - 2011 Rick Spencer -License: GPL-3 - -Files: ./pithos/pandora/pandora.py -Copyright: 2010 Kevin Mehall , - 2012 Christopher Eby -License: GPL-3 - -Files: ./pithos/pandora/blowfish.py -Copyright: 2011 Versile AS -License: AGPL-3+ - -Files: ./debian/* -Copyright: 2010-2011, 2015 Luke Faraone -License: GPL-3 - -License: GPL-3 - 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 package; if not, see - . - . - On Debian systems, the full text of the GNU General Public - License version 3 can be found in the file - `/usr/share/common-licenses/GPL-3'. - -License: AGPL-3+ - This program 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 - . - . - GNU AFFERO GENERAL PUBLIC LICENSE - Version 3, 19 November 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 Affero General Public License is a free, copyleft license for - software and other kinds of works, specifically designed to ensure - cooperation with the community in the case of network server software. - . - The licenses for most software and other practical works are designed - to take away your freedom to share and change the works. By contrast, - our General Public Licenses are 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. - . - 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. - . - Developers that use our General Public Licenses protect your rights - with two steps: (1) assert copyright on the software, and (2) offer - you this License which gives you legal permission to copy, distribute - and/or modify the software. - . - A secondary benefit of defending all users' freedom is that - improvements made in alternate versions of the program, if they - receive widespread use, become available for other developers to - incorporate. Many developers of free software are heartened and - encouraged by the resulting cooperation. However, in the case of - software used on network servers, this result may fail to come about. - The GNU General Public License permits making a modified version and - letting the public access it on a server without ever releasing its - source code to the public. - . - The GNU Affero General Public License is designed specifically to - ensure that, in such cases, the modified source code becomes available - to the community. It requires the operator of a network server to - provide the source code of the modified version running there to the - users of that server. Therefore, public use of a modified version, on - a publicly accessible server, gives the public access to the source - code of the modified version. - . - An older license, called the Affero General Public License and - published by Affero, was designed to accomplish similar goals. This is - a different license, not a version of the Affero GPL, but Affero has - released a new version of the Affero GPL which permits relicensing under - this license. - . - 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 Affero 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. Remote Network Interaction; Use with the GNU General Public License. - . - Notwithstanding any other provision of this License, if you modify the - Program, your modified version must prominently offer all users - interacting with it remotely through a computer network (if your version - supports such interaction) an opportunity to receive the Corresponding - Source of your version by providing access to the Corresponding Source - from a network server at no charge, through some standard or customary - means of facilitating copying of software. This Corresponding Source - shall include the Corresponding Source for any work covered by version 3 - of the GNU General Public License that is incorporated pursuant to the - following paragraph. - . - 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 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 work with which it is combined will remain governed by version - 3 of the GNU General Public License. - . - 14. Revised Versions of this License. - . - The Free Software Foundation may publish revised and/or new versions of - the GNU Affero 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 Affero 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 Affero 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 Affero 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. - . - - Copyright (C) - . - This program 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 . - . - Also add information on how to contact you by electronic and paper mail. - . - If your software can interact with users remotely through a computer - network, you should also make sure that it provides a way for users to - get its source. For example, if your program is a web application, its - interface could display a "Source" link that leads users to an archive - of the code. There are many ways you could offer source, and different - solutions will be better for different programs; see section 13 for the - specific requirements. - . - 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 AGPL, see - . +Copyright: (C) 2008-2013 Kevin Mehall +License: GPL v3 + The full text of the GPL is distributed in + /usr/share/common-licenses/GPL-3 on Debian systems. diff -Nru pithos-1.1.2/debian/links pithos-1.6.2/debian/links --- pithos-1.1.2/debian/links 2016-03-06 03:57:10.000000000 +0000 +++ pithos-1.6.2/debian/links 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -usr/share/pithos/run_pithos usr/bin/pithos diff -Nru pithos-1.1.2/debian/manpages pithos-1.6.2/debian/manpages --- pithos-1.1.2/debian/manpages 2016-03-06 03:57:10.000000000 +0000 +++ pithos-1.6.2/debian/manpages 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -pithos.1 diff -Nru pithos-1.1.2/debian/pithos.1.md pithos-1.6.2/debian/pithos.1.md --- pithos-1.1.2/debian/pithos.1.md 2016-03-06 03:57:10.000000000 +0000 +++ pithos-1.6.2/debian/pithos.1.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,30 +0,0 @@ -% PITHOS(1) -% -% September 29, 2010 - -# NAME - -pithos - Pandora Radio client for the GNOME desktop - -# SYNOPSIS - -**pithos** [_arguments_] - -# DESCRIPTION - -Pithos is a cross-platform desktop client for the personalized web radio Pandora. When run, it starts a X11/GTK+ user interface, which allows the user to control the radio via the mouse and media keys. - -# OPTIONS - -This program does not accept any options or parameters other than as described above. - -# AUTHORS - -**Pithos** was written by Kevin Mehall. - -This manual page was written by Luke Faraone for the **Debian GNU/Linux** system, but its use elsewhere is encouraged. - -# SEE ALSO - -Before using Pithos, you need to create an account with Pandora at . Out of concern for the the longevity of Pandora Media Inc., the software authors would recommend subscribing to Pandora One. - diff -Nru pithos-1.1.2/debian/rules pithos-1.6.2/debian/rules --- pithos-1.1.2/debian/rules 2016-03-06 03:57:10.000000000 +0000 +++ pithos-1.6.2/debian/rules 2018-10-31 12:49:33.000000000 +0000 @@ -1,19 +1,7 @@ #!/usr/bin/make -f -# -*- mode: makefile; coding: utf-8 -*- -export DH_VERBOSE = 1 - -export PYBUILD_INSTALL_ARGS_python3=--install-lib=/usr/share/pithos/ +#export DH_VERBOSE=1 %: - dh $@ --buildsystem pybuild --with python3 - -override_dh_auto_install: - dh_auto_install - pandoc -s -w man ./debian/pithos.1.md -o pithos.1 - mv debian/pithos/usr/bin/pithos debian/pithos/usr/share/pithos/run_pithos + dh $@ --with=autoreconf -override_dh_auto_clean: - python3 setup.py clean -a - py3clean . - rm -f pithos.1 diff -Nru pithos-1.1.2/debian/watch pithos-1.6.2/debian/watch --- pithos-1.1.2/debian/watch 2016-03-06 03:57:10.000000000 +0000 +++ pithos-1.6.2/debian/watch 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -version=3 -opts=filenamemangle=s/.+\/v?(\d\S*)\.tar\.gz/pithos-$1\.tar\.gz/ \ - https://github.com/pithos/pithos/tags .*/v?(\d\S*)\.tar\.gz diff -Nru pithos-1.1.2/debug.py pithos-1.6.2/debug.py --- pithos-1.1.2/debug.py 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/debug.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,27 +0,0 @@ -#!/usr/bin/env python3 - -import os -import sys - -# None of this works on Windows atm -if sys.platform != 'win32': - - # Store config locally - config_dir = os.path.abspath('./config') - os.environ['XDG_CONFIG_HOME'] = config_dir - - # Migrate old debug_config - old_config_dir = os.path.abspath('./debug_config') - if os.path.exists(old_config_dir): - os.rename(old_config_dir, config_dir) - - if not os.path.exists(config_dir): - os.makedirs(config_dir) - - # Enable verbose logging and test mode - if len(sys.argv) == 1: - sys.argv.append('-tvv') - -from pithos import pithos - -pithos.main() diff -Nru pithos-1.1.2/docs/conf.py pithos-1.6.2/docs/conf.py --- pithos-1.1.2/docs/conf.py 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/docs/conf.py 2024-03-03 23:53:20.000000000 +0000 @@ -17,7 +17,7 @@ # 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('.')) +sys.path.insert(0, os.path.abspath('..')) # -- General configuration ----------------------------------------------------- @@ -83,7 +83,7 @@ # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. -html_theme = 'default' +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 @@ -112,7 +112,7 @@ # 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'] +#html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. diff -Nru pithos-1.1.2/docs/meson.build pithos-1.6.2/docs/meson.build --- pithos-1.1.2/docs/meson.build 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/docs/meson.build 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,27 @@ +sphinx_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') diff -Nru pithos-1.1.2/docs/pithos.1 pithos-1.6.2/docs/pithos.1 --- pithos-1.1.2/docs/pithos.1 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/docs/pithos.1 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,40 @@ +.\" 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 diff -Nru pithos-1.1.2/flatpak/io.github.Pithos.json pithos-1.6.2/flatpak/io.github.Pithos.json --- pithos-1.1.2/flatpak/io.github.Pithos.json 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/flatpak/io.github.Pithos.json 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,43 @@ +{ + "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": "../" + } + ] + } + ] +} diff -Nru pithos-1.1.2/flatpak/python3-pylast.json pithos-1.6.2/flatpak/python3-pylast.json --- pithos-1.1.2/flatpak/python3-pylast.json 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/flatpak/python3-pylast.json 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,19 @@ +{ + "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" + } + ] +} \ No newline at end of file diff -Nru pithos-1.1.2/meson.build pithos-1.6.2/meson.build --- pithos-1.1.2/meson.build 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/meson.build 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,15 @@ +project('pithos', + version: '1.6.2', + 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') diff -Nru pithos-1.1.2/meson_post_install.py pithos-1.6.2/meson_post_install.py --- pithos-1.1.2/meson_post_install.py 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/meson_post_install.py 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,21 @@ +#!/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) diff -Nru pithos-1.1.2/pithos/AboutPithosDialog.py pithos-1.6.2/pithos/AboutPithosDialog.py --- pithos-1.1.2/pithos/AboutPithosDialog.py 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/AboutPithosDialog.py 2024-03-03 23:53:20.000000000 +0000 @@ -1,72 +1,28 @@ # -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- -### BEGIN LICENSE # Copyright (C) 2010-2012 Kevin Mehall -#This program is free software: you can redistribute it and/or modify it -#under the terms of the GNU General Public License version 3, as published -#by the Free Software Foundation. +# This program is 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. +# 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 +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . -from gi.repository import Gtk, GdkPixbuf -from .pithosconfig import get_ui_file, get_media_file -from .util import open_browser +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): - """__init__ - This function is typically not called directly. - Creation of a AboutPithosDialog requires redeading the associated ui - file and parsing the ui definition extrenally, - and then calling AboutPithosDialog.finish_initializing(). - - Use the convenience function NewAboutPithosDialog to create - NewAboutPithosDialog objects. - - """ - pass - - def finish_initializing(self, builder): - """finish_initalizing should be called after parsing the ui definition - and creating a AboutPithosDialog object with it in order to finish - initializing the start of the new AboutPithosDialog instance. - - """ - #get a reference to the builder and set up the signals - self.builder = builder - self.builder.connect_signals(self) - - self.set_logo(GdkPixbuf.Pixbuf.new_from_file_at_scale(get_media_file('icon'), -1, 96, True)) - - #code for other initialization actions should be added here - - def activate_link_cb(self, wid, uri): - open_browser(uri) - return True - -def NewAboutPithosDialog(): - """NewAboutPithosDialog - returns a fully instantiated - AboutPithosDialog object. Use this function rather than - creating a AboutPithosDialog instance directly. - - """ - - builder = Gtk.Builder() - builder.add_from_file(get_ui_file('about')) - dialog = builder.get_object("about_pithos_dialog") - dialog.finish_initializing(builder) - return dialog - -if __name__ == "__main__": - dialog = NewAboutPithosDialog() - dialog.show() - Gtk.main() + 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)) diff -Nru pithos-1.1.2/pithos/PreferencesPithosDialog.py pithos-1.6.2/pithos/PreferencesPithosDialog.py --- pithos-1.1.2/pithos/PreferencesPithosDialog.py 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/PreferencesPithosDialog.py 2024-03-03 23:53:20.000000000 +0000 @@ -1,49 +1,42 @@ # -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- -### BEGIN LICENSE # Copyright (C) 2010 Kevin Mehall -#This program is free software: you can redistribute it and/or modify it -#under the terms of the GNU General Public License version 3, as published -#by the Free Software Foundation. +# This program is 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. +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranties of +# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR +# PURPOSE. See the GNU General Public License for more details. # -#You should have received a copy of the GNU General Public License along -#with this program. If not, see . -### END LICENSE - -import sys -import os -import stat +# 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 Gtk, GObject, GLib, Pango +from gi.repository import Gio, Gtk, GObject, Pango -from .pithosconfig import get_ui_file -from .pandora.data import * +from .util import SecretService -pacparser_imported = False try: import pacparser - pacparser_imported = True except ImportError: + pacparser = None logging.info("Could not import python-pacparser.") -config_home = GLib.get_user_config_dir() -configfilename = os.path.join(config_home, 'pithos.ini') class PithosPluginRow(Gtk.ListBoxRow): - def __init__(self, plugin, enabled): - Gtk.ListBoxRow.__init__(self) + 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(plugin.name.title().replace('_', ' '), plugin.description)) + 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) @@ -52,10 +45,12 @@ box.pack_start(label, True, True, 4) self.switch = Gtk.Switch() - self.switch.set_active(enabled) + 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) @@ -63,6 +58,23 @@ 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) @@ -77,251 +89,128 @@ self.set_sensitive(False) self.set_tooltip_text(self.plugin.error) elif self.plugin.prepared: - self.get_toplevel().preference_btn.set_sensitive(self.plugin.preferences_dialog != None) + self.set_prefs_btn() + +@Gtk.Template(resource_path='/io/github/Pithos/ui/PreferencesPithosDialog.ui') class PreferencesPithosDialog(Gtk.Dialog): __gtype_name__ = "PreferencesPithosDialog" - prefernces = {} - def __init__(self): - """__init__ - This function is typically not called directly. - Creation of a PreferencesPithosDialog requires reading the associated ui - file and parsing the ui definition extrenally, - and then calling PreferencesPithosDialog.finish_initializing(). - - Use the convenience function NewPreferencesPithosDialog to create - NewAboutPithosDialog objects. - """ - - pass - - def finish_initializing(self, builder): - """finish_initalizing should be called after parsing the ui definition - and creating a AboutPithosDialog object with it in order to finish - initializing the start of the new AboutPithosDialog instance. - """ - - # get a reference to the builder and set up the signals - self.builder = builder - self.builder.connect_signals(self) - self.preference_btn = self.builder.get_object('prefs_btn') - self.listbox = self.builder.get_object('plugins_listbox') - - # initialize the "Audio Quality" combobox backing list - audio_quality_combo = self.builder.get_object('prefs_audio_quality') - fmt_store = Gtk.ListStore(GObject.TYPE_STRING, GObject.TYPE_STRING) - for audio_quality in valid_audio_formats: - fmt_store.append(audio_quality) - audio_quality_combo.set_model(fmt_store) - render_text = Gtk.CellRendererText() - audio_quality_combo.pack_start(render_text, True) - audio_quality_combo.add_attribute(render_text, "text", 1) + __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'), + } - self.__load_preferences() + 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): - if len(self.listbox.set_header_func.get_arguments()) == 3: - # pygobject3 3.10 - self.listbox.set_header_func(self.on_listbox_update_header, None) - else: - # pygobject3 3.12+ - self.listbox.set_header_func(self.on_listbox_update_header) + self.plugins_listbox.set_header_func(self.on_listbox_update_header) for plugin in plugins.values(): - row = PithosPluginRow(plugin, self.__preferences[plugin.preference]) - self.listbox.add(row) - self.listbox.show_all() - - def get_preferences(self): - """get_preferences - returns a dictionary object that contains - preferences for pithos. - """ - return self.__preferences + 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 != None) + self.preference_btn.set_sensitive(row.plugin.preferences_dialog is not None) + @Gtk.Template.Callback() def on_prefs_btn_clicked(self, btn): - dialog = self.listbox.get_selected_rows()[0].plugin.preferences_dialog + 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() - def on_listbox_update_header(self, row, before, junk = None): + @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)) - def __load_preferences(self): - #default preferences that will be overwritten if some are saved - self.__preferences = { - "username":'', - "password":'', - "x_pos": None, - "y_pos": None, - "notify":True, - "last_station_id":None, - "proxy":'', - "control_proxy":'', - "control_proxy_pac":'', - "show_icon": False, - "lastfm_key": False, - "enable_mediakeys":True, - "enable_screensaverpause":False, - "enable_lastfm":False, - "enable_mpris":True, - "volume": 1.0, - # If set, allow insecure permissions. Implements CVE-2011-1500 - "unsafe_permissions": False, - "audio_quality": default_audio_quality, - "pandora_one": False, - "force_client": None, - } - - try: - f = open(configfilename) - except IOError: - f = [] - - for line in f: - sep = line.find('=') - key = line[:sep] - val = line[sep+1:].strip() - if val == 'None': val=None - elif val == 'False': val=False - elif val == 'True': val=True - self.__preferences[key]=val - - if 'audio_format' in self.__preferences: - # Pithos <= 0.3.17, replaced by audio_quality - del self.__preferences['audio_format'] - - if not pacparser_imported and self.__preferences['control_proxy_pac'] != '': - self.__preferences['control_proxy_pac'] = '' - - self.setup_fields() - - def fix_perms(self): - """Apply new file permission rules, fixing CVE-2011-1500. - If the file is 0644 and if "unsafe_permissions" is not True, - chmod 0600 - If the file is world-readable (but not exactly 0644) and if - "unsafe_permissions" is not True: - chmod o-rw - """ - def complain_unsafe(): - # Display this message iff permissions are unsafe, which is why - # we don't just check once and be done with it. - logging.warning("Ignoring potentially unsafe permissions due to user override.") - - changed = False - - if os.path.exists(configfilename): - # We've already written the file, get current permissions - config_perms = stat.S_IMODE(os.stat(configfilename).st_mode) - if config_perms == (stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH): - if self.__preferences["unsafe_permissions"]: - return complain_unsafe() - # File is 0644, set to 0600 - logging.warning("Removing world- and group-readable permissions, to fix CVE-2011-1500 in older software versions. To force, set unsafe_permissions to True in pithos.ini.") - os.chmod(configfilename, stat.S_IRUSR | stat.S_IWUSR) - changed = True - - elif config_perms & stat.S_IROTH: - if self.__preferences["unsafe_permissions"]: - return complain_unsafe() - # File is o+r, - logging.warning("Removing world-readable permissions, configuration should not be globally readable. To force, set unsafe_permissions to True in pithos.ini.") - config_perms ^= stat.S_IROTH - os.chmod(configfilename, config_perms) - changed = True - - if config_perms & stat.S_IWOTH: - if self.__preferences["unsafe_permissions"]: - return complain_unsafe() - logging.warning("Removing world-writable permissions, configuration should not be globally writable. To force, set unsafe_permissions to True in pithos.ini.") - config_perms ^= stat.S_IWOTH - os.chmod(configfilename, config_perms) - changed = True - - return changed - - def save(self): - existed = os.path.exists(configfilename) - f = open(configfilename, 'w') - - if not existed: - # make the file owner-readable and writable only - os.fchmod(f.fileno(), (stat.S_IRUSR | stat.S_IWUSR)) - - for key in self.__preferences: - f.write('%s=%s\n'%(key, self.__preferences[key])) - f.close() - - def setup_fields(self): - self.builder.get_object('prefs_username').set_text(self.__preferences["username"]) - self.builder.get_object('prefs_password').set_text(self.__preferences["password"]) - self.builder.get_object('checkbutton_pandora_one').set_active(self.__preferences["pandora_one"]) - self.builder.get_object('prefs_proxy').set_text(self.__preferences["proxy"]) - self.builder.get_object('prefs_control_proxy').set_text(self.__preferences["control_proxy"]) - self.builder.get_object('prefs_control_proxy_pac').set_text(self.__preferences["control_proxy_pac"]) - if not pacparser_imported: - self.builder.get_object('prefs_control_proxy_pac').set_sensitive(False) - self.builder.get_object('prefs_control_proxy_pac').set_tooltip_text("Please install python-pacparser") - - audio_quality_combo = self.builder.get_object('prefs_audio_quality') - for row in audio_quality_combo.get_model(): - if row[0] == self.__preferences["audio_quality"]: - audio_quality_combo.set_active_iter(row.iter) - break - - for row in self.listbox.get_children(): - row.switch.set_active(self.__preferences[row.plugin.preference]) - - def ok(self, widget, data=None): - """ok - The user has elected to save the changes. - Called before the dialog returns Gtk.RESONSE_OK from run(). - """ - - self.__preferences["username"] = self.builder.get_object('prefs_username').get_text() - self.__preferences["password"] = self.builder.get_object('prefs_password').get_text() - self.__preferences["pandora_one"] = self.builder.get_object('checkbutton_pandora_one').get_active() - self.__preferences["proxy"] = self.builder.get_object('prefs_proxy').get_text() - self.__preferences["control_proxy"] = self.builder.get_object('prefs_control_proxy').get_text() - self.__preferences["control_proxy_pac"] = self.builder.get_object('prefs_control_proxy_pac').get_text() - - audio_quality = self.builder.get_object('prefs_audio_quality') - active_idx = audio_quality.get_active() - if active_idx != -1: # ignore unknown format - self.__preferences["audio_quality"] = audio_quality.get_model()[active_idx][0] - - for row in self.listbox.get_children(): - self.__preferences[row.plugin.preference] = row.switch.get_active() - - self.save() - - def cancel(self, widget, data=None): - """cancel - The user has elected cancel changes. - Called before the dialog returns Gtk.ResponseType.CANCEL for run() - """ - - self.setup_fields() # restore fields to previous values - pass - - -def NewPreferencesPithosDialog(): - """NewPreferencesPithosDialog - returns a fully instantiated - PreferencesPithosDialog object. Use this function rather than - creating a PreferencesPithosDialog instance directly. - """ - - builder = Gtk.Builder() - builder.add_from_file(get_ui_file('preferences')) - dialog = builder.get_object("preferences_pithos_dialog") - dialog.finish_initializing(builder) - return dialog - -if __name__ == "__main__": - dialog = NewPreferencesPithosDialog() - dialog.show() - Gtk.main() + @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() diff -Nru pithos-1.1.2/pithos/SearchDialog.py pithos-1.6.2/pithos/SearchDialog.py --- pithos-1.1.2/pithos/SearchDialog.py 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/SearchDialog.py 2024-03-03 23:53:20.000000000 +0000 @@ -1,118 +1,73 @@ # -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- -### BEGIN LICENSE # Copyright (C) 2010-2012 Kevin Mehall -#This program is free software: you can redistribute it and/or modify it -#under the terms of the GNU General Public License version 3, as published -#by the Free Software Foundation. +# This program is 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. +# 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 +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . -import sys -import os import html -from gi.repository import Gtk -from gi.repository import GObject +from gi.repository import GObject, Gtk -from .pithosconfig import get_ui_file +@Gtk.Template(resource_path='/io/github/Pithos/ui/SearchDialog.ui') class SearchDialog(Gtk.Dialog): __gtype_name__ = "SearchDialog" - def __init__(self): - """__init__ - This function is typically not called directly. - Creation of a SearchDialog requires redeading the associated ui - file and parsing the ui definition extrenally, - and then calling SearchDialog.finish_initializing(). - - Use the convenience function NewSearchDialog to create - a SearchDialog object. - - """ - pass - - def finish_initializing(self, builder, worker_run): - """finish_initalizing should be called after parsing the ui definition - and creating a SearchDialog object with it in order to finish - initializing the start of the new SearchDialog instance. - - """ - #get a reference to the builder and set up the signals - self.builder = builder - self.builder.connect_signals(self) - - self.entry = self.builder.get_object('entry') - self.treeview = self.builder.get_object('treeview') - self.okbtn = self.builder.get_object('okbtn') + 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.worker_run = worker_run - + self.query = '' self.result = None - - def ok(self, widget, data=None): - """ok - The user has elected to save the changes. - Called before the dialog returns Gtk.RESONSE_OK from run(). - - """ - - - def cancel(self, widget, data=None): - """cancel - The user has elected cancel changes. - Called before the dialog returns Gtk.ResponseType.CANCEL for run() - - """ - pass - + @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): - if not query: return + 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 is 'song': - mk = "%s by %s"%(html.escape(i.title), html.escape(i.artist)) - elif i.resultType is 'artist': - mk = "%s (artist)"%(html.escape(i.name)) + 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', (query,), callback, "Searching...") - - def get_selected(self): - sel = self.treeview.get_selection().get_selected() - if sel[1]: - return self.treeview.get_model().get_value(sel[1], 0) - + self.worker_run('search', (self.query,), callback, "Searching...") + def cursor_changed(self, *ignore): self.result = self.get_selected() - self.okbtn.set_sensitive(not not self.result) - - -def NewSearchDialog(worker_run): - """NewSearchDialog - returns a fully instantiated - dialog-camel_case_nameDialog object. Use this function rather than - creating SearchDialog instance directly. - - """ - - builder = Gtk.Builder() - builder.add_from_file(get_ui_file('search')) - dialog = builder.get_object("search_dialog") - dialog.finish_initializing(builder, worker_run) - return dialog - -if __name__ == "__main__": - dialog = NewSearchDialog() - dialog.show() - Gtk.main() - + self.set_response_sensitive(Gtk.ResponseType.OK, not not self.result) diff -Nru pithos-1.1.2/pithos/StationsDialog.py pithos-1.6.2/pithos/StationsDialog.py --- pithos-1.1.2/pithos/StationsDialog.py 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/StationsDialog.py 2024-03-03 23:53:20.000000000 +0000 @@ -1,74 +1,67 @@ # -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- -### BEGIN LICENSE # Copyright (C) 2010-2012 Kevin Mehall -#This program is free software: you can redistribute it and/or modify it -#under the terms of the GNU General Public License version 3, as published -#by the Free Software Foundation. +# This program is 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. +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranties of +# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR +# PURPOSE. See the GNU General Public License for more details. # -#You should have received a copy of the GNU General Public License along -#with this program. If not, see . -### END LICENSE - -import sys -import os -from gi.repository import Gtk +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . + +import html import logging -from .pithosconfig import get_ui_file -from .util import open_browser +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() - def __init__(self): - """__init__ - This function is typically not called directly. - Creation of a StationsDialog requires redeading the associated ui - file and parsing the ui definition extrenally, - and then calling StationsDialog.finish_initializing(). - - Use the convenience function NewStationsDialog to create - a StationsDialog object. - - """ - pass - - def finish_initializing(self, builder, pithos): - """finish_initalizing should be called after parsing the ui definition - and creating a StationsDialog object with it in order to finish - initializing the start of the new StationsDialog instance. - - """ - #get a reference to the builder and set up the signals - self.builder = builder - self.builder.connect_signals(self) - self.pithos = pithos self.model = pithos.stations_model self.worker_run = pithos.worker_run self.quickmix_changed = False self.searchDialog = None - + self.modelfilter = self.model.filter_new() - self.modelfilter.set_visible_func(lambda m, i, d: m.get_value(i, 0) and not m.get_value(i, 0).isQuickMix) - self.modelsortable = Gtk.TreeModelSort.sort_new_with_model(self.modelfilter) + 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. + @todo Leaving it as sorting by date added by default. Probably should make a radio select in the window or an option in program options for user preference """ # self.modelsortable.set_sort_column_id(1, Gtk.SortType.ASCENDING) - - self.treeview = self.builder.get_object("treeview") + self.treeview.set_model(self.modelsortable) self.treeview.connect('button_press_event', self.on_treeview_button_press_event) - - name_col = Gtk.TreeViewColumn() + + name_col = Gtk.TreeViewColumn() name_col.set_title("Name") render_text = Gtk.CellRendererText() render_text.set_property('editable', True) @@ -78,138 +71,181 @@ name_col.set_expand(True) name_col.set_sort_column_id(1) self.treeview.append_column(name_col) - - qm_col = Gtk.TreeViewColumn() + + 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: + + def qm_datafunc(column, cell, model, _iter, data=None): + if model.get_value(_iter, 0).useQuickMix: cell.set_active(True) else: cell.set_active(False) + qm_col.set_cell_data_func(render_toggle, qm_datafunc) render_toggle.connect("toggled", self.qm_toggled) self.treeview.append_column(qm_col) - - self.station_menu = builder.get_object("station_menu") - + def qm_toggled(self, renderer, path): station = self.modelfilter[path][0] station.useQuickMix = not station.useQuickMix self.quickmix_changed = True - + def station_renamed(self, cellrenderertext, path, new_text): station = self.modelfilter[path][0] - self.worker_run(station.rename, (new_text,), context='net', message="Renaming Station...") + 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) - time = event.time pthinfo = treeview.get_path_at_pos(x, y) if pthinfo is not None: path, col, cellx, celly = pthinfo treeview.grab_focus() - treeview.set_cursor( path, col, 0) - self.station_menu.popup(None, None, None, None, event.button, time) + 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) - + 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) - + 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.builder.get_object("delete_confirm_dialog") - dialog.set_property("text", "Are you sure you want to delete the station \"%s\"?"%(station.name)) + + 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: + + if response == Gtk.ResponseType.YES: self.worker_run(station.delete, context='net', message="Deleting Station...") - del self.pithos.stations_model[self.pithos.station_index(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.NewSearchDialog(self.worker_run) - self.searchDialog.set_transient_for(self) + 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): - logging.info("in add_station_cb {} {}".format(dialog.result, response)) - if response == 1: - self.worker_run("add_station_by_music_id", (dialog.result.musicId,), self.station_added, "Creating station...") + 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): - logging.debug("1 "+ repr(station)) - it = self.model.insert_after(self.model.get_iter(1), (station, station.name)) - logging.debug("2 "+ repr(it)) + + 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 ") - - def add_genre_station(self, widget): - """ - This is just a stub for the non-completed buttn - """ - + + @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.worker_run("save_quick_mix", message="Saving QuickMix...") self.quickmix_changed = False - + logging.info("closed dialog") return True - -def NewStationsDialog(pithos): - """NewStationsDialog - returns a fully instantiated - Dialog object. Use this function rather than - creating StationsDialog instance directly. - - """ - - builder = Gtk.Builder() - builder.add_from_file(get_ui_file('stations')) - dialog = builder.get_object("stations_dialog") - dialog.finish_initializing(builder, pithos) - return dialog - -if __name__ == "__main__": - dialog = NewStationsDialog() - dialog.show() - Gtk.main() - diff -Nru pithos-1.1.2/pithos/StationsPopover.py pithos-1.6.2/pithos/StationsPopover.py --- pithos-1.1.2/pithos/StationsPopover.py 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/pithos/StationsPopover.py 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,190 @@ +# -*- 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) diff -Nru pithos-1.1.2/pithos/__main__.py pithos-1.6.2/pithos/__main__.py --- pithos-1.1.2/pithos/__main__.py 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/__main__.py 2024-03-03 23:53:20.000000000 +0000 @@ -1,3 +1,3 @@ -from pithos.pithos import main +from pithos.application import main main() diff -Nru pithos-1.1.2/pithos/application.py pithos-1.6.2/pithos/application.py --- pithos-1.1.2/pithos/application.py 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/pithos/application.py 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,215 @@ +# -*- 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() Binary files /tmp/tmpbqegcfwp/Xym0jYgLpO/pithos-1.1.2/pithos/data/media/album_default.png and /tmp/tmpbqegcfwp/1xdaNWyxyt/pithos-1.6.2/pithos/data/media/album_default.png differ diff -Nru pithos-1.1.2/pithos/data/media/album_default.svg pithos-1.6.2/pithos/data/media/album_default.svg --- pithos-1.1.2/pithos/data/media/album_default.svg 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/data/media/album_default.svg 1970-01-01 00:00:00.000000000 +0000 @@ -1,117 +0,0 @@ - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - diff -Nru pithos-1.1.2/pithos/data/media/icon.svg pithos-1.6.2/pithos/data/media/icon.svg --- pithos-1.1.2/pithos/data/media/icon.svg 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/data/media/icon.svg 1970-01-01 00:00:00.000000000 +0000 @@ -1,475 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Binary files /tmp/tmpbqegcfwp/Xym0jYgLpO/pithos-1.1.2/pithos/data/media/pithos-tray-icon.png and /tmp/tmpbqegcfwp/1xdaNWyxyt/pithos-1.6.2/pithos/data/media/pithos-tray-icon.png differ Binary files /tmp/tmpbqegcfwp/Xym0jYgLpO/pithos-1.1.2/pithos/data/media/rate_bg.png and /tmp/tmpbqegcfwp/1xdaNWyxyt/pithos-1.6.2/pithos/data/media/rate_bg.png differ diff -Nru pithos-1.1.2/pithos/data/media/rate_bg.svg pithos-1.6.2/pithos/data/media/rate_bg.svg --- pithos-1.1.2/pithos/data/media/rate_bg.svg 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/data/media/rate_bg.svg 1970-01-01 00:00:00.000000000 +0000 @@ -1,108 +0,0 @@ - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - diff -Nru pithos-1.1.2/pithos/data/ui/AboutPithosDialog.ui pithos-1.6.2/pithos/data/ui/AboutPithosDialog.ui --- pithos-1.1.2/pithos/data/ui/AboutPithosDialog.ui 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/data/ui/AboutPithosDialog.ui 1970-01-01 00:00:00.000000000 +0000 @@ -1,53 +0,0 @@ - - - - - - - False - 5 - True - ../media/icon.svg - dialog - Pithos - 0.3 - Copyright © 2012 Kevin Mehall - A Pandora Radio client for the GNOME Desktop - http://pithos.github.io - Kevin Mehall -Patrick Griffis -Brad Pitcher -Christopher Eby -Steven Allen -Greg Sheremeta -Glenn Moss - - - Jason Gray - gpl-3-0 - - - - True - False - 2 - - - True - False - end - - - False - True - end - 0 - - - - - - - - - diff -Nru pithos-1.1.2/pithos/data/ui/PithosWindow.ui pithos-1.6.2/pithos/data/ui/PithosWindow.ui --- pithos-1.1.2/pithos/data/ui/PithosWindow.ui 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/data/ui/PithosWindow.ui 1970-01-01 00:00:00.000000000 +0000 @@ -1,550 +0,0 @@ - - - - - - - 100 - 1 - 10 - 10 - - - False - Pithos - 500 - 360 - pithos - - - - - - True - False - vertical - - - True - False - False - 2 - - - True - False - - - True - False - True - - - True - False - True - - - - True - False - media-playback-start-symbolic - 2 - - - - - False - True - 0 - - - - - True - False - True - - - - True - False - media-skip-forward-symbolic - 2 - - - - - False - True - 1 - - - - - True - False - True - none - False - vertical - audio-volume-muted-symbolic -audio-volume-high-symbolic -audio-volume-low-symbolic -audio-volume-medium-symbolic - - - - True - True - center - center - none - - - - - True - True - center - center - none - - - - - False - True - 2 - - - - - - - - False - False - - - - - True - False - False - - - True - False - - - - - True - False - - - True - False - - - True - False - True - right - True - - - - True - False - dialog-information-symbolic - - - - - False - True - 0 - - - - - 120 - True - False - False - - - - False - True - 1 - - - - - - - - False - False - - - - - False - True - 0 - - - - - True - False - adjustment1 - never - - - True - True - adjustment1 - False - - - - - - - - True - True - 1 - - - - - True - False - 2 - - - False - True - 2 - - - - - - - False - 5 - True - dialog - pithos_window - error - Pithos Upgrade Required - Pithos needs to be updated for compatibility with Pandora's latest changes. - True - - - True - False - vertical - 2 - - - True - False - end - - - Get Help Online - True - False - True - - - False - False - 0 - - - - - Quit - True - False - True - True - - - False - False - 1 - - - - - False - True - end - 0 - - - - - - button4 - button5 - - - - False - 5 - True - dialog - True - pithos_window - error - Error - - - True - False - 2 - - - True - False - end - - - Quit - True - False - True - True - - - False - False - 0 - - - - - False - True - end - 1 - - - - - - button-error-quit - - - - False - 5 - True - dialog - pithos_window - - - True - False - vertical - 2 - - - True - False - end - - - - - - - - - False - True - end - 0 - - - - - - - False - 5 - True - dialog - pithos_window - error - Error - - - True - False - 2 - - - True - False - end - - - Cancel - True - False - True - - - False - False - 0 - - - - - Retry - True - False - True - - - False - False - 1 - - - - - Preferences - True - False - True - True - - - False - False - 2 - - - - - False - True - end - 1 - - - - - - button1 - button2 - button3 - - - - True - False - - - True - False - Song _Info... - True - - - - - - True - False - _Love Song - True - - - - - - True - False - _Unlove Song - True - - - - - - True - False - _Ban Song - True - - - - - - True - False - _Unban Song - True - - - - - - True - False - Don't play song for a month - _Tired of this song - True - - - - - - True - False - Bookmark - - - True - False - - - True - False - Song - - - - - - True - False - Artist - - - - - - - - - diff -Nru pithos-1.1.2/pithos/data/ui/PreferencesPithosDialog.ui pithos-1.6.2/pithos/data/ui/PreferencesPithosDialog.ui --- pithos-1.1.2/pithos/data/ui/PreferencesPithosDialog.ui 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/data/ui/PreferencesPithosDialog.ui 1970-01-01 00:00:00.000000000 +0000 @@ -1,426 +0,0 @@ - - - - - - - 333 - False - 5 - Preferences - False - pithos - dialog - - - True - False - 2 - - - True - False - end - - - Cancel - True - False - False - - - - False - False - 0 - - - - - OK - True - False - False - - - - False - False - 1 - - - - - False - True - end - 0 - - - - - True - True - - - True - False - 12 - 18 - - - True - False - - - True - False - start - Account - - - - - - 0 - 0 - - - - - True - False - 20 - 8 - 20 - - - True - False - start - center - Email - - - 0 - 0 - - - - - True - True - True - email - - - 1 - 0 - - - - - True - False - Password - - - 0 - 1 - - - - - True - True - False - password - - - 1 - 1 - - - - - Pandora One Subscriber - True - True - False - start - True - - - 0 - 2 - 2 - - - - - True - True - <small><a href='http://pandora.com'>Create an account at pandora.com</a></small> - True - - - 0 - 3 - 2 - - - - - 0 - 1 - - - - - 0 - 0 - - - - - True - False - - - True - False - start - Advanced Settings - - - - - - 0 - 0 - - - - - True - False - 20 - 8 - 20 - True - - - True - False - start - Audio Quality - - - 0 - 0 - - - - - True - False - - - 1 - 0 - - - - - True - False - This proxy is used for all HTTP/HTTPS traffic. If empty, http_proxy and https_proxy environment variables will be used. - start - Proxy URL - - - 0 - 1 - - - - - True - True - url - - - 1 - 1 - - - - - True - False - Proxy for Pandora API requests only (for those outside the US). If unset, the normal proxy is used. - start - Control Proxy URL - - - 0 - 2 - - - - - True - True - url - - - 1 - 2 - - - - - True - False - Proxy auto-configuration URL. Used only if Control Proxy URL above is unset. - start - Control Proxy PAC - - - 0 - 3 - - - - - True - True - url - - - 1 - 3 - - - - - 0 - 1 - - - - - 0 - 1 - - - - - - - True - False - Pandora - - - False - - - - - True - False - vertical - - - True - True - never - in - - - True - False - - - True - False - - - - - - - - True - True - 0 - - - - - True - False - - - True - False - False - This plugin either must be enabled or does not support preferences. - end - Preferences - True - - - - True - True - - - - - - False - True - 1 - - - - - 1 - - - - - True - False - Plugins - - - 1 - False - - - - - - - - - - - False - True - 1 - - - - - - button_cancel - button_ok - - - diff -Nru pithos-1.1.2/pithos/data/ui/SearchDialog.ui pithos-1.6.2/pithos/data/ui/SearchDialog.ui --- pithos-1.1.2/pithos/data/ui/SearchDialog.ui 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/data/ui/SearchDialog.ui 1970-01-01 00:00:00.000000000 +0000 @@ -1,126 +0,0 @@ - - - - - - - 380 - 350 - False - 5 - Search - True - pithos - dialog - - - True - False - 2 - - - True - False - end - - - Cancel - True - False - True - - - False - False - 0 - - - - - OK - True - False - False - True - - - - False - False - 1 - - - - - False - True - end - 0 - - - - - True - False - 4 - - - True - True - • - - - - False - True - 0 - - - - - True - False - - - True - False - False - - - - - - - column - - - - 1 - - - - - - - - - True - True - 1 - - - - - True - True - 1 - - - - - - button2 - okbtn - - - diff -Nru pithos-1.1.2/pithos/data/ui/StationsDialog.ui pithos-1.6.2/pithos/data/ui/StationsDialog.ui --- pithos-1.1.2/pithos/data/ui/StationsDialog.ui 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/data/ui/StationsDialog.ui 1970-01-01 00:00:00.000000000 +0000 @@ -1,222 +0,0 @@ - - - - - - - True - False - - - True - False - Listen Now - True - - - - - - True - False - Info - True - - - - - - True - False - Rename - - - - - - True - False - Delete - True - - - - - - 480 - 420 - False - 1 - Manage Stations - True - pithos - dialog - - - - True - False - vertical - 2 - - - True - False - end - - - Add Station - True - False - True - - - - False - False - 0 - True - - - - - Genre Stations - False - False - True - True - - - - False - False - 1 - True - - - - - Refresh Stations - True - False - True - - - - False - False - 2 - True - - - - - Close - True - False - True - - - - False - False - 3 - - - - - False - True - end - 0 - - - - - True - False - - - True - False - - - - - - - - True - True - 1 - - - - - - add_station - add_genre_station - refresh_stations - close - - - - False - 5 - True - dialog - stations_dialog - warning - - - True - False - vertical - 2 - - - True - False - end - - - Cancel - True - False - True - - - False - False - 0 - - - - - Delete - True - False - True - - - False - False - 1 - - - - - False - True - end - 0 - - - - - - button2 - button1 - - - diff -Nru pithos-1.1.2/pithos/data/ui/about_pithos_dialog.xml pithos-1.6.2/pithos/data/ui/about_pithos_dialog.xml --- pithos-1.1.2/pithos/data/ui/about_pithos_dialog.xml 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/data/ui/about_pithos_dialog.xml 1970-01-01 00:00:00.000000000 +0000 @@ -1,9 +0,0 @@ - - - - - - diff -Nru pithos-1.1.2/pithos/data/ui/app_menu.ui pithos-1.6.2/pithos/data/ui/app_menu.ui --- pithos-1.1.2/pithos/data/ui/app_menu.ui 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/data/ui/app_menu.ui 1970-01-01 00:00:00.000000000 +0000 @@ -1,29 +0,0 @@ - - - -
- - app.stations - _Stations - <Primary>s - - - app.preferences - _Preferences - <Primary>p - -
-
- - app.about - _About - - - app.quit - _Quit - <Primary>q - -
-
-
- diff -Nru pithos-1.1.2/pithos/data/ui/pithos_window.xml pithos-1.6.2/pithos/data/ui/pithos_window.xml --- pithos-1.1.2/pithos/data/ui/pithos_window.xml 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/data/ui/pithos_window.xml 1970-01-01 00:00:00.000000000 +0000 @@ -1,8 +0,0 @@ - - - - - diff -Nru pithos-1.1.2/pithos/data/ui/preferences_pithos_dialog.xml pithos-1.6.2/pithos/data/ui/preferences_pithos_dialog.xml --- pithos-1.1.2/pithos/data/ui/preferences_pithos_dialog.xml 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/data/ui/preferences_pithos_dialog.xml 1970-01-01 00:00:00.000000000 +0000 @@ -1,9 +0,0 @@ - - - - - - diff -Nru pithos-1.1.2/pithos/data/ui/search_dialog.xml pithos-1.6.2/pithos/data/ui/search_dialog.xml --- pithos-1.1.2/pithos/data/ui/search_dialog.xml 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/data/ui/search_dialog.xml 1970-01-01 00:00:00.000000000 +0000 @@ -1,9 +0,0 @@ - - - - - - diff -Nru pithos-1.1.2/pithos/data/ui/stations_dialog.xml pithos-1.6.2/pithos/data/ui/stations_dialog.xml --- pithos-1.1.2/pithos/data/ui/stations_dialog.xml 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/data/ui/stations_dialog.xml 1970-01-01 00:00:00.000000000 +0000 @@ -1,9 +0,0 @@ - - - - - - diff -Nru pithos-1.1.2/pithos/gobject_worker.py pithos-1.6.2/pithos/gobject_worker.py --- pithos-1.1.2/pithos/gobject_worker.py 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/gobject_worker.py 2024-03-03 23:53:20.000000000 +0000 @@ -1,35 +1,28 @@ # -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- -### BEGIN LICENSE # Copyright (C) 2010-2012 Kevin Mehall -#This program is free software: you can redistribute it and/or modify it -#under the terms of the GNU General Public License version 3, as published -#by the Free Software Foundation. +# This program is 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. +# 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 +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . import logging import threading -import queue -from gi.repository import GObject, GLib +from gi.repository import GLib import traceback -class GObjectWorker(): - def __init__(self): - self.thread = threading.Thread(target=self._run) - self.thread.daemon = True - self.queue = queue.Queue() - self.thread.start() - - def _run(self): - while True: - command, args, callback, errorback = self.queue.get() + +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: @@ -38,32 +31,33 @@ e.traceback = traceback.format_exc() if errorback: GLib.idle_add(errorback, e) - - def send(self, command, args=(), callback=None, errorback=None): - if errorback is None: errorback = self._default_errorback - self.queue.put((command, args, callback, errorback)) - + 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 - + 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 - + worker.send(test_cmd, (3, 4), test_cb) + worker.send(test_cmd, ((), ()), test_cb) # trigger exception in worker to test error handling + Gtk.main() - - diff -Nru pithos-1.1.2/pithos/migrate_settings.py pithos-1.6.2/pithos/migrate_settings.py --- pithos-1.1.2/pithos/migrate_settings.py 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/pithos/migrate_settings.py 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,95 @@ +# -*- 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') diff -Nru pithos-1.1.2/pithos/pandora/__init__.py pithos-1.6.2/pithos/pandora/__init__.py --- pithos-1.1.2/pithos/pandora/__init__.py 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/pandora/__init__.py 2024-03-03 23:53:20.000000000 +0000 @@ -1,18 +1,16 @@ # -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- -### BEGIN LICENSE # Copyright (C) 2010 Kevin Mehall -#This program is free software: you can redistribute it and/or modify it -#under the terms of the GNU General Public License version 3, as published -#by the Free Software Foundation. +# This program is 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. +# 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 +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . from .pandora import * diff -Nru pithos-1.1.2/pithos/pandora/blowfish.py pithos-1.6.2/pithos/pandora/blowfish.py --- pithos-1.1.2/pithos/pandora/blowfish.py 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/pandora/blowfish.py 2024-03-03 23:53:20.000000000 +0000 @@ -48,7 +48,7 @@ def __init__(self, *args): super(VCryptoException, self).__init__(*args) -class Blowfish(object): +class Blowfish: """Blowfish cipher. When initialized the object can encrypt and decrypt blocks of @@ -216,7 +216,7 @@ return bytes([b & 0xff for b in bval]) -# These are the standard initialization valies of P and S blocks for the +# 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. diff -Nru pithos-1.1.2/pithos/pandora/data.py pithos-1.6.2/pithos/pandora/data.py --- pithos-1.1.2/pithos/pandora/data.py 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/pandora/data.py 2024-03-03 23:53:20.000000000 +0000 @@ -21,14 +21,6 @@ default_client_id = "android-generic" default_one_client_id = "pandora-one" -# See http://pan-do-ra-api.wikia.com/wiki/Json/5/station.getPlaylist -valid_audio_formats = [ - ('highQuality', 'High'), - ('mediumQuality', 'Medium'), - ('lowQuality', 'Low'), -] -default_audio_quality = 'mediumQuality' - # The CA used by internal-tuner.pandora.com is untrusted by most machines so we will just directly # trust it. diff -Nru pithos-1.1.2/pithos/pandora/fake.py pithos-1.6.2/pithos/pandora/fake.py --- pithos-1.1.2/pithos/pandora/fake.py 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/pandora/fake.py 2024-03-03 23:53:20.000000000 +0000 @@ -1,18 +1,17 @@ # -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- -### BEGIN LICENSE # Copyright (C) 2010 Kevin Mehall -#This program is free software: you can redistribute it and/or modify it -#under the terms of the GNU General Public License version 3, as published -#by the Free Software Foundation. +# This program is 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. +# 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 +# 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 @@ -55,7 +54,7 @@ def set_authenticated(self): self.auth_check.set_active(True) - def json_call(self, method, args={}, https=False, blowfish=True): + def json_call(self, method, args=None, https=False, blowfish=True): time.sleep(1) self.maybe_fail() @@ -113,15 +112,22 @@ '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, diff -Nru pithos-1.1.2/pithos/pandora/pandora.py pithos-1.6.2/pithos/pandora/pandora.py --- pithos-1.1.2/pithos/pandora/pandora.py 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/pandora/pandora.py 2024-03-03 23:53:20.000000000 +0000 @@ -1,19 +1,17 @@ # -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- -### BEGIN LICENSE # Copyright (C) 2010 Kevin Mehall # Copyright (C) 2012 Christopher Eby -#This program is free software: you can redistribute it and/or modify it -#under the terms of the GNU General Public License version 3, as published -#by the Free Software Foundation. +# This program is 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. +# 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 +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . """Pandora JSON v5 API @@ -30,6 +28,9 @@ 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 @@ -40,17 +41,91 @@ RATE_LOVE = 'love' RATE_NONE = None -API_ERROR_API_VERSION_NOT_SUPPORTED = 11 -API_ERROR_COUNTRY_NOT_SUPPORTED = 12 -API_ERROR_INSUFFICIENT_CONNECTIVITY = 13 -API_ERROR_READ_ONLY_MODE = 1000 -API_ERROR_INVALID_AUTH_TOKEN = 1001 -API_ERROR_INVALID_LOGIN = 1002 -API_ERROR_LISTENER_NOT_AUTHORIZED = 1003 -API_ERROR_PARTNER_NOT_AUTHORIZED = 1010 -API_ERROR_PLAYLIST_EXCEEDED = 1039 +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 -PLAYLIST_VALIDITY_TIME = 60*60*3 + @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]') @@ -68,7 +143,7 @@ def pad(s, l): return s + b'\0' * (l - len(s)) -class Pandora(object): +class Pandora: """Access the Pandora API To use the Pandora class, make sure to call :py:meth:`set_audio_quality` @@ -82,6 +157,8 @@ """ 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)]) @@ -89,7 +166,9 @@ def pandora_decrypt(self, s): return b''.join([self.blowfish_decode.decrypt(pad(codecs.decode(s[i:i+16], 'hex_codec'), 8)) for i in range(0, len(s), 16)]).rstrip(b'\x08') - def json_call(self, method, args={}, https=False, blowfish=True): + 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) @@ -120,8 +199,8 @@ try: req = urllib.request.Request(url, data, {'User-agent': USER_AGENT, 'Content-type': 'text/plain'}) - response = self.opener.open(req, timeout=HTTP_TIMEOUT) - text = response.read().decode('utf-8') + 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)) @@ -131,42 +210,38 @@ 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'] - logging.error('fault code: ' + str(code) + ' message: ' + msg) - if code == API_ERROR_INVALID_AUTH_TOKEN: + 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 code == API_ERROR_COUNTRY_NOT_SUPPORTED: - raise PandoraError("Pandora not available", code, - submsg="Pandora is not available in your country.") - elif code == API_ERROR_API_VERSION_NOT_SUPPORTED: + elif error_enum is ApiError.API_VERSION_NOT_SUPPORTED: raise PandoraAPIVersionError(msg) - elif code == API_ERROR_INSUFFICIENT_CONNECTIVITY: - raise PandoraError("Out of sync", code, - submsg="Correct your system's clock. If the problem persists, a Pithos update may be required") - elif code == API_ERROR_READ_ONLY_MODE: - raise PandoraError("Pandora maintenance", code, - submsg="Pandora is in read-only mode as it is performing maintenance. Try again later.") - elif code == API_ERROR_INVALID_LOGIN: - raise PandoraError("Login Error", code, submsg="Invalid username or password") - elif code == API_ERROR_LISTENER_NOT_AUTHORIZED: - raise PandoraError("Pandora Error", code, - submsg="A Pandora One account is required to access this feature. Uncheck 'Pandora One' in Settings.") - elif code == API_ERROR_PARTNER_NOT_AUTHORIZED: - raise PandoraError("Login Error", code, - submsg="Invalid Pandora partner keys. A Pithos update may be required.") - elif code == API_ERROR_PLAYLIST_EXCEEDED: - raise PandoraError("Playlist Error", code, - submsg="You have requested too many playlists. Try again later.") + elif error_enum is ApiError.UNKNOWN_ERROR: + submsg = 'Undocumented Error Code: {}\n{}'.format(code, msg) + raise PandoraError(error_enum.title, code, submsg) else: - raise PandoraError("Pandora returned an error", code, "%s (code %d)"%(msg, code)) + 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'] @@ -202,6 +277,7 @@ :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 @@ -222,15 +298,39 @@ pandora_time = int(self.pandora_decrypt(partner['syncTime'].encode('utf-8'))[4:14]) self.time_offset = pandora_time - time.time() logging.info("Time offset is %s", self.time_offset) - - user = self.json_call('auth.userLogin', {'username': user, 'password': password, 'loginType': 'user'}, https=True) + 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.get_stations(self) + 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')['stations'] + stations = self.json_call( + 'user.getStationList', + {'returnAllStations': True} + )['stations'] self.quickMixStationIds = None self.stations = [Station(self, i) for i in stations] @@ -249,10 +349,14 @@ self.json_call('user.setQuickMix', {'quickMixStationIds': stationIds}) def search(self, query): - results = self.json_call('music.search', {'searchText': query}) + results = self.json_call( + 'music.search', + {'includeGenreStations': True, 'includeNearMatches': True, 'searchText': query}, + ) - l = [SearchResult('artist', i) for i in results['artists']] - l += [SearchResult('song', i) for i in results['songs']] + 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 @@ -260,9 +364,23 @@ def add_station_by_music_id(self, musicid): d = self.json_call('station.createStation', {'musicToken': musicid}) station = Station(self, d) - self.stations.append(station) + 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: @@ -277,7 +395,7 @@ def delete_feedback(self, stationToken, feedbackId): self.json_call('station.deleteFeedback', {'feedbackId': feedbackId, 'stationToken': stationToken}) -class Station(object): +class Station: def __init__(self, pandora, d): self.pandora = pandora @@ -285,6 +403,7 @@ 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 @@ -299,12 +418,17 @@ def get_playlist(self): logging.info("pandora: Get Playlist") - playlist = self.pandora.json_call('station.getPlaylist', {'stationToken': self.idToken}, https=True) - songs = [] - for i in playlist['items']: - if 'songName' in i: # check for ads - songs.append(Song(self.pandora, i)) - return songs + # 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): @@ -318,8 +442,7 @@ self.name = new_name def delete(self): - logging.info("pandora: Deleting Station") - self.pandora.json_call('station.deleteStation', {'stationToken': self.idToken}) + self.pandora.delete_station(self) def __repr__(self): return '<{}.{} {} "{}">'.format( @@ -329,13 +452,23 @@ self.name, ) -class Song(object): - def __init__(self, pandora, d): +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.audioUrlMap = d['audioUrlMap'] self.trackToken = d['trackToken'] self.rating = RATE_LOVE if d['songRating'] == 1 else RATE_NONE # banned songs won't play, so we don't care about them self.stationId = d['stationId'] @@ -343,64 +476,75 @@ 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'] - self.bitrate = None - self.is_ad = None # None = we haven't checked, otherwise True/False - self.tired=False - self.message='' - self.duration = None - self.position = None - self.start_time = None - self.finished = False - self.playlist_time = time.time() - self.feedbackId = None - - @property - def title(self): - if not hasattr(self, '_title'): - # the actual name of the track, minus any special characters (except dashes) is stored - # as the last part of the songExplorerUrl, before the args. - explorer_name = self.songExplorerUrl.split('?')[0].split('/')[-1] - clean_expl_name = NAME_COMPARE_REGEX.sub('', explorer_name).lower() - clean_name = NAME_COMPARE_REGEX.sub('', self.songName).lower() - - if clean_name == clean_expl_name: - self._title = self.songName + # 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: - try: - xml_data = urllib.request.urlopen(self.songExplorerUrl) - dom = minidom.parseString(xml_data.read()) + # 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 - return self._title + # 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.warn("Unable to use audio format %s. Using %s", + 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 - - def get_position_sec (self): - if self.position is not None: - return self.position / 1000000000 + 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: @@ -434,20 +578,22 @@ return self.rating def is_still_valid(self): - return (time.time() - self.playlist_time) < PLAYLIST_VALIDITY_TIME + # 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.songName, + self.title, self.artist, self.album, ) -class SearchResult(object): +class SearchResult: def __init__(self, resultType, d): self.resultType = resultType self.score = d['score'] @@ -458,4 +604,6 @@ self.artist = d['artistName'] elif resultType == 'artist': self.name = d['artistName'] + elif resultType == 'genre': + self.stationName = d['stationName'] diff -Nru pithos-1.1.2/pithos/pithos.py pithos-1.6.2/pithos/pithos.py --- pithos-1.1.2/pithos/pithos.py 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/pithos.py 2024-03-03 23:53:20.000000000 +0000 @@ -1,210 +1,356 @@ -#!/usr/bin/env python # -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- -### BEGIN LICENSE # Copyright (C) 2010-2012 Kevin Mehall -#This program is free software: you can redistribute it and/or modify it -#under the terms of the GNU General Public License version 3, as published -#by the Free Software Foundation. +# This program is 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. +# 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 +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . + -import argparse -import cgi import contextlib +import hashlib import html import json import logging import math -import os import re -import signal +import os import sys import time import urllib.error import urllib.parse import urllib.request +from enum import Enum import gi gi.require_version('Gst', '1.0') -gi.require_version('Gtk', '3.0') +gi.require_version('GstAudio', '1.0') gi.require_version('GstPbutils', '1.0') -from gi.repository import Gst, GstPbutils, GObject, Gtk, Gdk, Pango, GdkPixbuf, Gio, GLib +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 .pithosconfig import get_ui_file, get_media_file, VERSION from .plugin import load_plugins -from .util import parse_proxy, open_browser +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 -ALBUM_ART_X_PAD = 6 +TEXT_X_PADDING = 12 +# 15 days in seconds to retain album art files. +ART_CACHE_TIME = 1.296e+6 + +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): - GObject.GObject.__init__(self) + super().__init__(height=ALBUM_ART_SIZE, width=ALBUM_ART_SIZE) self.icon = None self.pixbuf = None - self.rate_bg = GdkPixbuf.Pixbuf.new_from_file(get_media_file('rate')) + 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.PARAM_READWRITE), - 'pixbuf': (GdkPixbuf.Pixbuf, 'pixmap', 'pixmap', GObject.PARAM_READWRITE) + '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_get_size(self, widget, cell_area): - return (0, 0, ALBUM_ART_SIZE + ALBUM_ART_X_PAD, ALBUM_ART_SIZE) def do_render(self, ctx, widget, background_area, cell_area, flags): - if self.pixbuf: + if self.pixbuf is not None: Gdk.cairo_set_source_pixbuf(ctx, self.pixbuf, cell_area.x, cell_area.y) ctx.paint() - if self.icon: - x = cell_area.x+(cell_area.width-self.rate_bg.get_width()) - ALBUM_ART_X_PAD # right - y = cell_area.y+(cell_area.height-self.rate_bg.get_height()) # bottom - Gdk.cairo_set_source_pixbuf(ctx, self.rate_bg, x, y) + 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() - pixbuf = Gtk.IconTheme.get_default().load_icon(self.icon, Gtk.IconSize.MENU, 0) - x = cell_area.x+(cell_area.width-pixbuf.get_width())-5 - ALBUM_ART_X_PAD # right - y = cell_area.y+(cell_area.height-pixbuf.get_height())-5 # bottom - Gdk.cairo_set_source_pixbuf(ctx, pixbuf, x, y) + 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() -def get_album_art(url, *extra): - try: - with urllib.request.urlopen(url) as f: - image = f.read() - except urllib.error.HTTPError: - logging.warn('Invalid image url received') - return (None,) + extra - - with contextlib.closing(GdkPixbuf.PixbufLoader()) as loader: - loader.set_size(ALBUM_ART_SIZE, ALBUM_ART_SIZE) - loader.write(image) - return (loader.get_pixbuf(),) + extra - -class PlayerStatus (object): - def __init__(self): - self.reset() - - def reset(self): - self.async_done = False - self.began_buffering = None - self.buffer_percent = 0 - self.pending_duration_query = False + 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,)), - "song-rating-changed": (GObject.SignalFlags.RUN_FIRST, None, (GObject.TYPE_PYOBJECT,)), "play-state-changed": (GObject.SignalFlags.RUN_FIRST, None, (GObject.TYPE_BOOLEAN,)), "user-changed-play-state": (GObject.SignalFlags.RUN_FIRST, None, (GObject.TYPE_BOOLEAN,)), + "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,)), } - def __init__(self): - """__init__ - This function is typically not called directly. - Creation a PithosWindow requires redeading the associated ui - file and parsing the ui definition extrenally, - and then calling PithosWindow.finish_initializing(). - - Use the convenience function NewPithosWindow to create - PithosWindow object. - - """ - pass - - def finish_initializing(self, builder, cmdopts): - """finish_initalizing should be called after parsing the ui definition - and creating a PithosWindow object with it in order to finish - initializing the start of the new PithosWindow instance. - - """ - signal.signal(signal.SIGINT, signal.SIG_DFL) - - self.cmdopts = cmdopts - - #get a reference to the builder and set up the signals - self.builder = builder - self.builder.connect_signals(self) - - self.prefs_dlg = PreferencesPithosDialog.NewPreferencesPithosDialog() - self.prefs_dlg.set_transient_for(self) - self.preferences = self.prefs_dlg.get_preferences() - - if self.prefs_dlg.fix_perms(): - # Changes were made, save new config variable - self.prefs_dlg.save() + 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.prefs_dlg.set_plugins(self.plugins) - - if not self.preferences['username']: - self.show_preferences(is_startup=True) - self.pandora = make_pandora(self.cmdopts.test) - self.set_proxy() + self.pandora = make_pandora(test_mode) + self.set_proxy(reconnect=False) self.set_audio_quality() - self.pandora_connect() + 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 - self.stations_model = Gtk.ListStore(GObject.TYPE_PYOBJECT, str) + # 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.player = Gst.ElementFactory.make("playbin", "player"); + self._query_buffer = Gst.Query.new_buffering(Gst.Format.PERCENT) + + self.player = Gst.ElementFactory.make("playbin3", "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::async-done", self.on_gst_async_done) - bus.connect("message::duration-changed", self.on_gst_duration_changed) + 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) - bus.connect("message::tag", self.on_gst_tag) self.player.connect("notify::volume", self.on_gst_volume) self.player.connect("notify::source", self.on_gst_source) - self.player_status = PlayerStatus() - self.stations_dlg = None - self.playing = None # None is a special "Waiting to play" state + self._current_state = PseudoGst.STOPPED + self._buffer_recovery_state = PseudoGst.STOPPED + self.current_song_index = None self.current_station = None - self.current_station_id = self.preferences.get('last_station_id') + 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 @@ -213,71 +359,129 @@ 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() - self.art_worker = GObjectWorker() - aa = GdkPixbuf.Pixbuf.new_from_file(get_media_file('album')) + 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 = os.path.join(tempdir_base, 'pithos_cache') + os.makedirs(self.tempdir, exist_ok=True) + logging.info("Created temporary directory {}".format(self.tempdir)) + except IOError as e: + self.tempdir = None + logging.warning('Failed to create a temporary directory: {}'.format(e)) - self.default_album_art = aa.scale_simple(ALBUM_ART_SIZE, ALBUM_ART_SIZE, GdkPixbuf.InterpType.BILINEAR) + @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') - os.environ['PULSE_PROP_media.role'] = 'music' - - self.playpause_image = self.builder.get_object('playpause_image') - self.volume = self.builder.get_object('volume') self.volume.set_relief(Gtk.ReliefStyle.NORMAL) # It ignores glade... - self.volume.set_property("value", math.pow(float(self.preferences['volume']), 1.0/3.0)) - - self.statusbar = self.builder.get_object('statusbar1') + self.settings.bind('volume', self.volume, 'value', Gio.SettingsBindFlags.DEFAULT) - self.song_menu = self.builder.get_object('song_menu') - self.song_menu_love = self.builder.get_object('menuitem_love') - self.song_menu_unlove = self.builder.get_object('menuitem_unlove') - self.song_menu_ban = self.builder.get_object('menuitem_ban') - self.song_menu_unban = self.builder.get_object('menuitem_unban') - - self.songs_treeview = self.builder.get_object('songs_treeview') self.songs_treeview.set_model(self.songs_model) title_col = Gtk.TreeViewColumn() - def bgcolor_data_func(column, cell, model, iter, data=None): - if model.get_value(iter, 0) is self.current_song: - bgcolor = column.get_tree_view().get_style_context().get_background_color(Gtk.StateFlags.ACTIVE) - else: - bgcolor = column.get_tree_view().get_style_context().get_background_color(Gtk.StateFlags.NORMAL) - cell.set_property("cell-background-rgba", bgcolor) - - render_icon = CellRendererAlbumArt() - title_col.pack_start(render_icon, False) - title_col.add_attribute(render_icon, "icon", 2) - title_col.add_attribute(render_icon, "pixbuf", 3) - title_col.set_cell_data_func(render_icon, bgcolor_data_func) + render_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() + 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) - title_col.set_cell_data_func(render_text, bgcolor_data_func) 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_combo = self.builder.get_object('stations') - self.stations_combo.set_model(self.stations_model) - render_text = Gtk.CellRendererText() - self.stations_combo.pack_start(render_text, True) - self.stations_combo.add_attribute(render_text, "text", 1) - self.stations_combo.set_row_separator_func(lambda model, iter, data=None: model.get_value(iter, 0) is None, None) + self.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) - self.set_initial_pos() + 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'): + 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) @@ -286,7 +490,11 @@ def cb(v): if context: self.statusbar.pop(self.statusbar.get_context_id(context)) - if callback: callback(v) + if callback: + if user_data: + callback(v, user_data) + else: + callback(v) def eb(e): if context and message: @@ -300,21 +508,24 @@ if isinstance(e, PandoraAuthTokenInvalid) and not self.auto_retrying_auth: self.auto_retrying_auth = True logging.info("Automatic reconnect after invalid auth token") - self.pandora_connect("Reconnecting...", retry_cb) + 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.warn(e.traceback) + logging.warning(e.traceback) - self.worker.send(fn, args, cb, eb) + err = errorback or eb + + self.worker.send(fn, args, cb, err) def get_proxy(self): """ Get HTTP proxy, first trying preferences then system proxy """ - if self.preferences['proxy']: - return self.preferences['proxy'] + proxy = self.settings['proxy'] + if proxy: + return proxy system_proxies = urllib.request.getproxies() if 'http' in system_proxies: @@ -322,7 +533,26 @@ return None - def set_proxy(self): + 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 @@ -331,15 +561,15 @@ # by default handlers = [] - global_proxy = self.preferences['proxy'] + 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.preferences['control_proxy'] - control_proxy_pac = self.preferences['control_proxy_pac'] + 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() @@ -365,60 +595,128 @@ if control_proxy: control_opener = pandora.Pandora.build_opener(urllib.request.ProxyHandler({'http': control_proxy, 'https': control_proxy})) - self.worker_run('set_url_opener', (control_opener,)) + self.pandora.set_url_opener(control_opener) - def set_audio_quality(self): - self.worker_run('set_audio_quality', (self.preferences['audio_quality'],)) + 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) - def pandora_connect(self, message="Logging in...", callback=None): - if self.preferences['pandora_one']: + 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.preferences['force_client'] + 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: + except json.JSONDecodeError: logging.error("Could not parse force_client json") args = ( client, - self.preferences['username'], - self.preferences['password'], + email, + password, ) - def pandora_ready(*ignore): - logging.info("Pandora connected") + 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 - - for i in self.pandora.stations: - if i.isQuickMix and i.isCreator: - self.stations_model.append((i, "QuickMix")) - self.stations_model.append((None, 'sep')) - for i in self.pandora.stations: - if not (i.isQuickMix and i.isCreator): - self.stations_model.append((i, i.name)) - if i.id == self.current_station_id: - logging.info("Restoring saved station: id = %s"%(i.id)) - selected = i - if not selected: + # 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] - self.station_changed(selected, reconnecting = self.have_stations) - self.have_stations = True + 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): @@ -427,7 +725,6 @@ 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) @@ -444,7 +741,7 @@ self.update_song_row(prev) if not self.current_song.is_still_valid(): - self.current_song.message = "Playlist expired" + self.current_song.message = 'Song expired' self.update_song_row() return self.next_song() @@ -452,47 +749,78 @@ return self.next_song() logging.info("Starting song: index = %i"%(song_index)) - self.player_status.reset() - - self.player.set_property("uri", self.current_song.audioUrl) - self.player.set_state(Gst.State.PAUSED) - self.playing = None + 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("Pithos - %s by %s" % (self.current_song.title, self.current_song.artist)) + self.set_title("%s by %s - Pithos" % (song.title, song.artist)) - self.emit('song-changed', self.current_song) + self.update_song_row() + + self.emit('song-changed', song) + self.emit('metadata-changed', song) def next_song(self, *ignore): - self.start_song(self.current_song_index + 1) + 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): - self.play() - self.emit('user-changed-play-state', True) + if self.play(): + self.emit('user-changed-play-state', True) - def play(self): - if not self.playing: - self.playing = True - self.create_ui_loop() - self.player.set_state(Gst.State.PLAYING) - self.playpause_image.set_from_icon_name('media-playback-pause-symbolic', Gtk.IconSize.SMALL_TOOLBAR) - self.update_song_row() - self.emit('play-state-changed', True) + def 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): - self.playing = False - self.destroy_ui_loop() - self.player.set_state(Gst.State.PAUSED) - self.playpause_image.set_from_icon_name('media-playback-start-symbolic', Gtk.IconSize.SMALL_TOOLBAR) - self.update_song_row() - self.emit('play-state-changed', False) + 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): @@ -502,10 +830,10 @@ prev.position = self.query_position() self.emit("song-ended", prev) - self.playing = False - self.destroy_ui_loop() - self.player.set_state(Gst.State.NULL) - self.emit('play-state-changed', False) + 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() @@ -523,34 +851,101 @@ else: self.user_play() + def clear_art_cache(self): + logging.info('Checking for expired art in cache') + timestamp = time.time() + with os.scandir(self.tempdir) as art_list: + for art in art_list: + age = timestamp - art.stat().st_mtime + if age > ART_CACHE_TIME: + os.remove(os.path.join(self.tempdir, art.path)) + 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.warn("Too many gstreamer errors. Not retrying") + 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 + song, index = extra + if tmpdir: + try: + self.clear_art_cache() + filename_hash = hashlib.sha256((song.artist+song.album).encode('utf-8')).hexdigest()+'.jpeg' + cache_file_path = os.path.join(self.tempdir, filename_hash) + file_url = urllib.parse.urljoin('file://', urllib.parse.quote(cache_file_path)) + if not os.path.exists(cache_file_path): + with open(cache_file_path, 'xb') as f: + f.write(image) + 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): - pixbuf, song, index = t + nonlocal songs_left_to_process + pixbuf, file_url, song, index = t + songs_left_to_process -= 1 if index%s" % (description, msg) - def song_icon(self, song): + @staticmethod + def song_icon(song): if song.tired: - return 'go-jump' + return 'tired' if song.rating == RATE_LOVE: - return 'emblem-favorite' + return 'love' if song.rating == RATE_BAN: - return 'dialog-error' + 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) or "" - return self.playing + self.songs_model[song.index][2] = self.song_icon(song) + return True def create_ui_loop(self): if not self.ui_loop_timer_id: @@ -833,16 +1255,22 @@ GLib.source_remove(self.ui_loop_timer_id) self.ui_loop_timer_id = 0 - def stations_combo_changed(self, widget): - index = widget.get_active() - if index>=0: - self.station_changed(self.stations_model[index][0]) + def 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) - def format_time(self, time_int): + @staticmethod + def format_time(time_int): if time_int is None: return None - time_int = time_int // 1000000000 + time_int //= 1000000000 s = time_int % 60 time_int //= 60 m = time_int % 60 @@ -859,73 +1287,110 @@ if sel: return self.songs_treeview.get_model().get_value(sel[1], 0) - def love_song(self, song=None): + 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('song-rating-changed', song) + self.emit('metadata-changed', song) self.worker_run(song.rate, (RATE_LOVE,), callback, "Loving song...") - def ban_song(self, song=None): + def ban_song(self, *ignore, song=None): song = song or self.current_song def callback(l): self.update_song_row(song) - self.emit('song-rating-changed', 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, song=None): + def unrate_song(self, *ignore, song=None): song = song or self.current_song def callback(l): self.update_song_row(song) - self.emit('song-rating-changed', song) + self.emit('metadata-changed', song) self.worker_run(song.rate, (RATE_NONE,), callback, "Removing song rating...") - def tired_song(self, song=None): + def tired_song(self, *ignore, song=None): song = song or self.current_song def callback(l): self.update_song_row(song) - self.emit('song-rating-changed', 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, song=None): + 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, song=None): + 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(self.selected_song()) + self.love_song(song=self.selected_song()) + @Gtk.Template.Callback() def on_menuitem_ban(self, widget): - self.ban_song(self.selected_song()) + self.ban_song(song=self.selected_song()) + @Gtk.Template.Callback() def on_menuitem_unrate(self, widget): - self.unrate_song(self.selected_song()) + self.unrate_song(song=self.selected_song()) + @Gtk.Template.Callback() def on_menuitem_tired(self, widget): - self.tired_song(self.selected_song()) + self.tired_song(song=self.selected_song()) + @Gtk.Template.Callback() def on_menuitem_info(self, widget): - song = self.selected_song() - open_browser(song.songDetailURL) + self.info_song(song=self.selected_song()) + @Gtk.Template.Callback() def on_menuitem_bookmark_song(self, widget): - self.bookmark_song(self.selected_song()) + 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) - time = event.time pthinfo = treeview.get_path_at_pos(x, y) if pthinfo is not None: path, col, cellx, celly = pthinfo @@ -934,25 +1399,22 @@ if event.button == 3: rating = self.selected_song().rating - self.song_menu_love.set_property("visible", rating != RATE_LOVE); - self.song_menu_unlove.set_property("visible", rating == RATE_LOVE); - self.song_menu_ban.set_property("visible", rating != RATE_BAN); - self.song_menu_unban.set_property("visible", rating == RATE_BAN); + self.song_menu_love.set_property("visible", rating != RATE_LOVE) + self.song_menu_unlove.set_property("visible", rating == RATE_LOVE) + self.song_menu_ban.set_property("visible", rating != RATE_BAN) + self.song_menu_unban.set_property("visible", rating == RATE_BAN) - self.song_menu.popup( None, None, None, None, event.button, time) + popup_at_pointer(self.song_menu, event) return True - if event.button == 1 and event.type == Gdk.EventType._2BUTTON_PRESS: + if event.button == 1 and event.type == Gdk.EventType.DOUBLE_BUTTON_PRESS: logging.info("Double clicked on song %s", self.selected_song().index) - if self.selected_song().index <= self.current_song_index: - return False - self.start_song(self.selected_song().index) + 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) - self.preferences['volume'] = volume def adjust_volume(self, amount): old_volume = self.volume.get_property("value") @@ -961,185 +1423,90 @@ 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 station_properties(self, *ignore): - open_browser(self.current_station.info_url) - - def show_about(self): + def show_about(self, version): """about - display the about box for pithos """ - about = AboutPithosDialog.NewAboutPithosDialog() - about.set_transient_for(self) - about.set_version(VERSION) + about = AboutPithosDialog.AboutPithosDialog(transient_for=self) + about.set_version(version) about.run() about.destroy() - def show_preferences(self, is_startup=False): - """preferences - display the preferences window for pithos """ - if is_startup: - self.prefs_dlg.set_type_hint(Gdk.WindowTypeHint.NORMAL) - - old_prefs = dict(self.preferences) - response = self.prefs_dlg.run() + def on_prefs_response(self, widget, response): self.prefs_dlg.hide() - if response == Gtk.ResponseType.OK: - self.preferences = self.prefs_dlg.get_preferences() - if not is_startup: - if ( self.preferences['proxy'] != old_prefs['proxy'] - or self.preferences['control_proxy'] != old_prefs['control_proxy']): - self.set_proxy() - if self.preferences['audio_quality'] != old_prefs['audio_quality']: - self.set_audio_quality() - if ( self.preferences['username'] != old_prefs['username'] - or self.preferences['password'] != old_prefs['password'] - or self.preferences['pandora_one'] != old_prefs['pandora_one']): - self.pandora_connect() - else: - self.prefs_dlg.set_type_hint(Gdk.WindowTypeHint.DIALOG) + 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.NewStationsDialog(self) - self.stations_dlg.set_transient_for(self) + 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 set_initial_pos(self): + 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 """ - x, y = self.preferences['x_pos'], self.preferences['y_pos'] - if not x is None and not y is None: - self.move(int(x), int(y)) + # 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): - self.set_initial_pos() - self.show() - self.present() - - def on_configure_event(self, widget, event): - self.preferences['x_pos'], self.preferences['y_pos'] = event.x, event.y - - def on_kb_playpause(self, widget=None, data=None): - if not isinstance(widget.get_focus(), Gtk.Button) and data.keyval == 32: - self.playpause() - return True + 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""" - self.destroy() + 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.preferences['last_station_id'] = self.current_station_id - self.prefs_dlg.save() self.quit() - -def NewPithosWindow(app, options): - """NewPithosWindow - returns a fully instantiated - PithosWindow object. Use this function rather than - creating a PithosWindow directly. - """ - - builder = Gtk.Builder() - builder.add_from_file(get_ui_file('main')) - window = builder.get_object("pithos_window") - window.set_application(app) - window.finish_initializing(builder, options) - return window - -class PithosApplication(Gtk.Application): - def __init__(self): - # Use org.gnome to avoid conflict with existing dbus interface net.kevinmehall - Gtk.Application.__init__(self, application_id='org.gnome.pithos', - flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE) - self.window = None - self.options = None - - def do_startup(self): - Gtk.Application.do_startup(self) - - # Setup appmenu - builder = Gtk.Builder() - builder.add_from_file(get_ui_file('menu')) - menu = builder.get_object("app-menu") - self.set_app_menu(menu) - - action = Gio.SimpleAction.new("stations", None) - action.connect("activate", self.stations_cb) - self.add_action(action) - - action = Gio.SimpleAction.new("preferences", None) - action.connect("activate", self.prefs_cb) - self.add_action(action) - - action = Gio.SimpleAction.new("about", None) - action.connect("activate", self.about_cb) - self.add_action(action) - - action = Gio.SimpleAction.new("quit", None) - action.connect("activate", self.quit_cb) - self.add_action(action) - - # FIXME: do_local_command_line() segfaults? - def do_command_line(self, args): - Gtk.Application.do_command_line(self, args) - - parser = argparse.ArgumentParser() - parser.add_argument("-v", "--verbose", action="count", default=0, dest="verbose", help="Show debug messages") - parser.add_argument("-t", "--test", action="store_true", dest="test", help="Use a mock web interface instead of connecting to the real Pandora server") - self.options = parser.parse_args(args.get_arguments()[1:]) - - # First, get rid of existing logging handlers due to call in header as per - # http://stackoverflow.com/questions/1943747/python-logging-before-you-run-logging-basicconfig - logging.root.handlers = [] - - #set the logging level to show debug messages - if self.options.verbose > 1: - log_level = logging.DEBUG - elif self.options.verbose == 1: - log_level = logging.INFO - else: - log_level = logging.WARN - - logging.basicConfig(level=log_level, format='%(levelname)s - %(module)s:%(funcName)s:%(lineno)d - %(message)s') - - self.do_activate() - - return 0 - - def do_activate(self): - if not self.window: - logging.info("Pithos %s" %VERSION) - self.window = NewPithosWindow(self, self.options) - - self.window.present() - - def do_shutdown(self): - Gtk.Application.do_shutdown(self) - self.window.destroy() - - def stations_cb(self, action, param): - self.window.show_stations() - - def prefs_cb(self, action, param): - self.window.show_preferences() - - def about_cb(self, action, param): - self.window.show_about() - - def quit_cb(self, action, param): - self.window.destroy() - -def main(): - app = PithosApplication() - exit_status = app.run(sys.argv) - sys.exit(exit_status) - -if __name__ == '__main__': - main() diff -Nru pithos-1.1.2/pithos/pithosconfig.py pithos-1.6.2/pithos/pithosconfig.py --- pithos-1.1.2/pithos/pithosconfig.py 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/pithosconfig.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,88 +0,0 @@ -# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- -### BEGIN LICENSE -# Copyright (C) 2010-2012 Kevin Mehall -#This program is free software: you can redistribute it and/or modify it -#under the terms of the GNU General Public License version 3, as published -#by the Free Software Foundation. -# -#This program is distributed in the hope that it will be useful, but -#WITHOUT ANY WARRANTY; without even the implied warranties of -#MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR -#PURPOSE. See the GNU General Public License for more details. -# -#You should have received a copy of the GNU General Public License along -#with this program. If not, see . -### END LICENSE - -# where your project will head for your data (for instance, images and ui files) -# by default, this is data, relative your trunk layout -__pithos_data_directory__ = 'data/' -__license__ = 'GPL-3' - -VERSION = '1.1.2' - -import os - -class project_path_not_found(Exception): - pass - -ui_files = { - 'about': 'AboutPithosDialog.ui', - 'preferences': 'PreferencesPithosDialog.ui', - 'search': 'SearchDialog.ui', - 'stations': 'StationsDialog.ui', - 'main': 'PithosWindow.ui', - 'menu': 'app_menu.ui' -} - -media_files = { - 'icon': 'icon.svg', - 'rate': 'rate_bg.png', - 'album': 'album_default.png' -} - -def get_media_file(name): - media = os.path.join(getdatapath(), 'media', media_files[name]) - if not os.path.exists(media): - media = None - - return media - -def get_ui_file(name): - ui_filename = os.path.join(getdatapath(), 'ui', ui_files[name]) - if not os.path.exists(ui_filename): - ui_filename = None - - return ui_filename - -def get_data_file(*path_segments): - """Get the full path to a data file. - - Returns the path to a file underneath the data directory (as defined by - `get_data_path`). Equivalent to os.path.join(get_data_path(), - *path_segments). - """ - return os.path.join(getdatapath(), *path_segments) - -def getdatapath(): - """Retrieve pithos data path - - This path is by default /../data/ in trunk - and /usr/share/pithos in an installed version but this path - is specified at installation time. - """ - - # get pathname absolute or relative - if __pithos_data_directory__.startswith('/'): - pathname = __pithos_data_directory__ - else: - pathname = os.path.dirname(__file__) + '/' + __pithos_data_directory__ - - abs_data_path = os.path.abspath(pathname) - if os.path.exists(abs_data_path): - return abs_data_path - else: - raise project_path_not_found - -if __name__=='__main__': - print(VERSION) diff -Nru pithos-1.1.2/pithos/plugin.py pithos-1.6.2/pithos/plugin.py --- pithos-1.1.2/pithos/plugin.py 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/plugin.py 2024-03-03 23:53:20.000000000 +0000 @@ -1,75 +1,109 @@ # -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- -### BEGIN LICENSE # Copyright (C) 2010-2012 Kevin Mehall -#This program is free software: you can redistribute it and/or modify it -#under the terms of the GNU General Public License version 3, as published -#by the Free Software Foundation. +# This program is 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. +# 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 +# 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' -class PithosPlugin: _PITHOS_PLUGIN = True # used to find the plugin class in a module preference = None description = "" - def __init__(self, name, window): + 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._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: - self.error = self.on_prepare() - self.prepared = True - if not self.error and not self.enabled: - logging.info("Enabling module %s"%(self.name)) - self.on_enable() - self.enabled = True - + 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 %s"%(self.name)) + 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 %s: %s"%(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): + + +def load_plugin(name, window, bus): try: - module = __import__('pithos.plugins.'+name) + 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": @@ -77,24 +111,62 @@ break else: return ErrorPlugin(name, "Could not find module class") - - return plugin_class(name, window) -def load_plugins(window): - plugins = window.plugins - prefs = window.preferences - - plugins_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "plugins") - discovered_plugins = [ fname.replace(".py", "") for fname in glob.glob1(plugins_dir, "*.py") if not fname.startswith("_") ] - - for name in discovered_plugins: - if not name in plugins: - plugin = plugins[name] = load_plugin(name, window) - else: - plugin = plugins[name] + return plugin_class(name, window, bus) - if plugin.preference and prefs.get(plugin.preference, False): - plugin.enable() - else: - plugin.disable() - + +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, + ) diff -Nru pithos-1.1.2/pithos/plugins/10_band_equalizer.py pithos-1.6.2/pithos/plugins/10_band_equalizer.py --- pithos-1.1.2/pithos/plugins/10_band_equalizer.py 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/pithos/plugins/10_band_equalizer.py 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,108 @@ +# +# 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) diff -Nru pithos-1.1.2/pithos/plugins/_dbus_service.py pithos-1.6.2/pithos/plugins/_dbus_service.py --- pithos-1.1.2/pithos/plugins/_dbus_service.py 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/plugins/_dbus_service.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,82 +0,0 @@ -# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- -### BEGIN LICENSE -# Copyright (C) 2010 Kevin Mehall -#This program is free software: you can redistribute it and/or modify it -#under the terms of the GNU General Public License version 3, as published -#by the Free Software Foundation. -# -#This program is distributed in the hope that it will be useful, but -#WITHOUT ANY WARRANTY; without even the implied warranties of -#MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR -#PURPOSE. See the GNU General Public License for more details. -# -#You should have received a copy of the GNU General Public License along -#with this program. If not, see . -### END LICENSE - -import dbus.service - -DBUS_BUS = "net.kevinmehall.Pithos" -DBUS_OBJECT_PATH = "/net/kevinmehall/Pithos" - -def song_to_dict(song): - d = {} - if song: - for i in ['artist', 'title', 'album', 'songDetailURL']: - d[i] = getattr(song, i) - return d - -class PithosDBusProxy(dbus.service.Object): - def __init__(self, window): - self.bus = dbus.SessionBus() - bus_name = dbus.service.BusName(DBUS_BUS, bus=self.bus) - dbus.service.Object.__init__(self, bus_name, DBUS_OBJECT_PATH) - self.window = window - self.window.connect("song-changed", self.songchange_handler) - self.window.connect("play-state-changed", self.playstate_handler) - - def playstate_handler(self, window, state): - self.PlayStateChanged(state) - - def songchange_handler(self, window, song): - self.SongChanged(song_to_dict(song)) - - @dbus.service.method(DBUS_BUS) - def PlayPause(self): - self.window.playpause_notify() - - @dbus.service.method(DBUS_BUS) - def SkipSong(self): - self.window.next_song() - - @dbus.service.method(DBUS_BUS) - def LoveCurrentSong(self): - self.window.love_song() - - @dbus.service.method(DBUS_BUS) - def BanCurrentSong(self): - self.window.ban_song() - - @dbus.service.method(DBUS_BUS) - def TiredCurrentSong(self): - self.window.tired_song() - - @dbus.service.method(DBUS_BUS) - def Present(self): - self.window.bring_to_top() - - @dbus.service.method(DBUS_BUS, out_signature='a{sv}') - def GetCurrentSong(self): - return song_to_dict(self.window.current_song) - - @dbus.service.method(DBUS_BUS, out_signature='b') - def IsPlaying(self): - return self.window.playing - - @dbus.service.signal(DBUS_BUS, signature='b') - def PlayStateChanged(self, state): - pass - - @dbus.service.signal(DBUS_BUS, signature='a{sv}') - def SongChanged(self, songinfo): - pass diff -Nru pithos-1.1.2/pithos/plugins/_mpris.py pithos-1.6.2/pithos/plugins/_mpris.py --- pithos-1.1.2/pithos/plugins/_mpris.py 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/plugins/_mpris.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,276 +0,0 @@ -# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- -### BEGIN LICENSE -# Copyright (C) 2011 Rick Spencer -# Copyright (C) 2011-2012 Kevin Mehall -#This program is free software: you can redistribute it and/or modify it -#under the terms of the GNU General Public License version 3, as published -#by the Free Software Foundation. -# -#This program is distributed in the hope that it will be useful, but -#WITHOUT ANY WARRANTY; without even the implied warranties of -#MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR -#PURPOSE. See the GNU General Public License for more details. -# -#You should have received a copy of the GNU General Public License along -#with this program. If not, see . -### END LICENSE - -import dbus -import dbus.service -from xml.etree import ElementTree - -class PithosMprisService(dbus.service.Object): - MEDIA_PLAYER2_IFACE = 'org.mpris.MediaPlayer2' - MEDIA_PLAYER2_PLAYER_IFACE = 'org.mpris.MediaPlayer2.Player' - - def __init__(self, window): - """ - Creates a PithosSoundMenu object. - - Requires a dbus loop to be created before the gtk mainloop, - typically by calling DBusGMainLoop(set_as_default=True). - """ - - bus_str = """org.mpris.MediaPlayer2.pithos""" - bus_name = dbus.service.BusName(bus_str, bus=dbus.SessionBus()) - dbus.service.Object.__init__(self, bus_name, "/org/mpris/MediaPlayer2") - self.window = window - - self.song_changed() - - self.window.connect("song-changed", self.songchange_handler) - self.window.connect("song-rating-changed", self.ratingchange_handler) - self.window.connect("play-state-changed", self.playstate_handler) - - def playstate_handler(self, window, state): - if state: - self.signal_playing() - else: - self.signal_paused() - - def songchange_handler(self, window, song): - self.song_changed([song.artist], song.album, song.title, song.artRadio, - song.rating) - self.signal_playing() - - def ratingchange_handler(self, window, song): - """Handle rating changes and update MPRIS metadata accordingly""" - # Pithos fires rating-changed signals for all songs, not just the - # currently playing one, so we need ignore signals for irrelevant songs. - if song is not self.window.current_song: - return - - self.__metadata["pithos:rating"] = song.rating or "" - self.PropertiesChanged("org.mpris.MediaPlayer2.Player", - dbus.Dictionary({"Metadata": self.__metadata}, - "sv", - variant_level=1), - []) - - def song_changed(self, artists=None, album=None, title=None, artUrl='', - rating=None): - """song_changed - sets the info for the current song. - - This method is not typically overriden. It should be called - by implementations of this class when the player has changed - songs. - - named arguments: - artists - a list of strings representing the artists" - album - a string for the name of the album - title - a string for the title of the song - - """ - - self.__metadata = dbus.Dictionary({ - "xesam:title": title or "Title Unknown", - "xesam:artist": artists or ["Artist Unknown"], - "xesam:album": album or "Album Unknown", - "mpris:artUrl": artUrl or "", - "pithos:rating": rating or "", - }, "sv", variant_level=1) - - # Properties - def _get_playback_status(self): - """Current status "Playing", "Paused", or "Stopped".""" - if not self.window.current_song: - return "Stopped" - if self.window.playing: - return "Playing" - else: - return "Paused" - - def _get_metadata(self): - """The info for the current song.""" - return self.__metadata - - def _get_volume(self): - return self.window.player.get_property("volume") - - def _set_volume(self, new_volume): - self.window.player.set_property('volume', new_volume) - - def _get_position(self): - return self.window.query_position() / 1000 - - @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature='ss', out_signature='v') - def Get(self, interface_name, property_name): - try: - return self.GetAll(interface_name)[property_name] - except KeyError: - raise dbus.exceptions.DBusException( - interface_name, 'Property %s was not found.' %property_name) - - @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature='ssv') - def Set(self, interface_name, property_name, new_value): - if interface_name == self.MEDIA_PLAYER2_IFACE: - pass - elif interface_name == self.MEDIA_PLAYER2_PLAYER_IFACE: - if property_name == 'Volume': - self._set_volume(new_value) - else: - raise dbus.exceptions.DBusException( - 'org.mpris.MediaPlayer2.pithos', - 'This object does not implement the %s interface' - % interface_name) - - @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature='s', out_signature='a{sv}') - def GetAll(self, interface_name): - if interface_name == self.MEDIA_PLAYER2_IFACE: - return { - 'CanQuit': True, - 'CanRaise': True, - 'HasTrackList': False, - 'Identity': 'Pithos', - 'DesktopEntry': 'pithos', - 'SupportedUriSchemes': [''], - 'SupportedMimeTypes': [''], - } - elif interface_name == self.MEDIA_PLAYER2_PLAYER_IFACE: - return { - 'PlaybackStatus': self._get_playback_status(), - 'LoopStatus': "None", - 'Rate': dbus.Double(1.0), - 'Shuffle': False, - 'Metadata': dbus.Dictionary(self._get_metadata(), signature='sv'), - 'Volume': dbus.Double(self._get_volume()), - 'Position': dbus.Int64(self._get_position()), - 'MinimumRate': dbus.Double(1.0), - 'MaximumRate': dbus.Double(1.0), - 'CanGoNext': self.window.waiting_for_playlist is not True, - 'CanGoPrevious': False, - 'CanPlay': self.window.current_song is not None, - 'CanPause': self.window.current_song is not None, - 'CanSeek': False, - 'CanControl': True, - } - else: - raise dbus.exceptions.DBusException( - 'org.mpris.MediaPlayer2.pithos', - 'This object does not implement the %s interface' - % interface_name) - - @dbus.service.method(MEDIA_PLAYER2_IFACE) - def Raise(self): - """Bring the media player to the front when selected by the sound menu""" - - self.window.bring_to_top() - - @dbus.service.method(MEDIA_PLAYER2_IFACE) - def Quit(self): - """Exit the player""" - - self.window.quit() - - @dbus.service.method(MEDIA_PLAYER2_PLAYER_IFACE) - def Previous(self): - """Play prvious song, not implemented""" - - pass - - @dbus.service.method(MEDIA_PLAYER2_PLAYER_IFACE) - def Next(self): - """Play next song""" - - self.window.next_song() - - @dbus.service.method(MEDIA_PLAYER2_PLAYER_IFACE) - def PlayPause(self): - self.window.playpause() - - @dbus.service.method(MEDIA_PLAYER2_PLAYER_IFACE) - def Play(self): - self.window.play() - - @dbus.service.method(MEDIA_PLAYER2_PLAYER_IFACE) - def Pause(self): - self.window.pause() - - @dbus.service.method(MEDIA_PLAYER2_PLAYER_IFACE) - def Stop(self): - self.window.stop() - - def signal_playing(self): - """signal_playing - Tell the Sound Menu that the player has - started playing. - """ - - self.__playback_status = "Playing" - d = dbus.Dictionary({"PlaybackStatus":self.__playback_status, "Metadata":self.__metadata}, - "sv",variant_level=1) - self.PropertiesChanged("org.mpris.MediaPlayer2.Player",d,[]) - - def signal_paused(self): - """signal_paused - Tell the Sound Menu that the player has - been paused - """ - - self.__playback_status = "Paused" - d = dbus.Dictionary({"PlaybackStatus":self.__playback_status}, - "sv",variant_level=1) - self.PropertiesChanged("org.mpris.MediaPlayer2.Player",d,[]) - - @dbus.service.signal(dbus.PROPERTIES_IFACE, signature='sa{sv}as') - def PropertiesChanged(self, interface_name, changed_properties, - invalidated_properties): - """PropertiesChanged - - A function necessary to implement dbus properties. - - Typically, this function is not overriden or called directly. - - """ - - pass - - # python-dbus does not have our properties for introspection, so we must manually add them - @dbus.service.method(dbus.INTROSPECTABLE_IFACE, in_signature="", out_signature="s", - path_keyword="object_path", connection_keyword="connection") - def Introspect(self, object_path, connection): - data = dbus.service.Object.Introspect(self, object_path, connection) - xml = ElementTree.fromstring(data) - - for iface in xml.findall("interface"): - name = iface.attrib["name"] - if name.startswith(self.MEDIA_PLAYER2_IFACE): - for item, value in self.GetAll(name).items(): - prop = {"name": item, "access": "read"} - if item == "Volume": # Hardcode the only writable property.. - prop["access"] = "readwrite" - - # Ugly mapping of types to signatures, is there a helper for this? - # KEEP IN SYNC! - if isinstance(value, str): - prop["type"] = "s" - elif isinstance(value, bool): - prop["type"] = "b" - elif isinstance(value, float): - prop["type"] = "d" - elif isinstance(value, int): - prop["type"] = "x" - elif isinstance(value, list): - prop["type"] = "as" - elif isinstance(value, dict): - prop["type"] = "a{sv}" - iface.append(ElementTree.Element("property", prop)) - return ElementTree.tostring(xml, encoding="UTF-8") diff -Nru pithos-1.1.2/pithos/plugins/auto_volume_normalization.py pithos-1.6.2/pithos/plugins/auto_volume_normalization.py --- pithos-1.1.2/pithos/plugins/auto_volume_normalization.py 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/pithos/plugins/auto_volume_normalization.py 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,67 @@ +# +# 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() diff -Nru pithos-1.1.2/pithos/plugins/dbus_util/DBusServiceObject.py pithos-1.6.2/pithos/plugins/dbus_util/DBusServiceObject.py --- pithos-1.1.2/pithos/plugins/dbus_util/DBusServiceObject.py 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/pithos/plugins/dbus_util/DBusServiceObject.py 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,354 @@ +# +# 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 + diff -Nru pithos-1.1.2/pithos/plugins/inhibit_screensaver.py pithos-1.6.2/pithos/plugins/inhibit_screensaver.py --- pithos-1.1.2/pithos/plugins/inhibit_screensaver.py 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/pithos/plugins/inhibit_screensaver.py 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,79 @@ +# +# 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 diff -Nru pithos-1.1.2/pithos/plugins/journald_logging.py pithos-1.6.2/pithos/plugins/journald_logging.py --- pithos-1.1.2/pithos/plugins/journald_logging.py 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/pithos/plugins/journald_logging.py 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,148 @@ +# +# 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() diff -Nru pithos-1.1.2/pithos/plugins/lastfm.py pithos-1.6.2/pithos/plugins/lastfm.py --- pithos-1.1.2/pithos/plugins/lastfm.py 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/plugins/lastfm.py 2024-03-03 23:53:20.000000000 +0000 @@ -1,177 +1,328 @@ # -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- -### BEGIN LICENSE # Copyright (C) 2010-2012 Kevin Mehall -#This program is free software: you can redistribute it and/or modify it -#under the terms of the GNU General Public License version 3, as published -#by the Free Software Foundation. +# This program is 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. +# 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 +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . -from gi.repository import Gtk +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 +# getting an API account: http://www.last.fm/api/account API_KEY = '997f635176130d5d6fe3a7387de601a8' API_SECRET = '3243b876f6bf880b923a3c9fb955720c' -#client id, client version info: http://www.last.fm/api/submissions#1.1 -CLIENT_ID = 'pth' -CLIENT_VERSION = '1.0' - -_worker = None -def get_worker(): - # so it can be shared between the plugin and the authorizer - global _worker - if not _worker: - _worker = GObjectWorker() - return _worker class LastfmPlugin(PithosPlugin): preference = 'enable_lastfm' - description = 'Scrobble tracks listened to on Last.fm' - + 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.") - return "pylast not found" - - self.pylast = pylast - self.worker = get_worker() - self.is_really_enabled = False - self.preferences_dialog = LastFmAuth(self.pylast, self.window.preferences, "lastfm_key", self.window) - self.preferences_dialog.connect('delete-event', self.auth_closed) + 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.window.preferences['lastfm_key']: + 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 auth_closed(self, widget, event): - if self.window.preferences['lastfm_key']: + 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: - self.window.preferences['enable_lastfm'] = False - widget.hide() - return True # Don't delete window + 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.window.preferences['lastfm_key']) - self.song_ended_handle = self.window.connect('song-ended', self.song_ended) - self.song_changed_handle = self.window.connect('song-changed', self.song_changed) + self._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: - self.window.disconnect(self.song_ended_handle) - self.window.disconnect(self.song_changed_handle) - self.is_really_enabled = False - - def song_ended(self, window, song): - self.scrobble(song) - - def connect(self, session_key): - self.network = self.pylast.get_lastfm_network( + 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 + session_key=session_key ) - self.scrobbler = self.network.get_scrobbler(CLIENT_ID, CLIENT_VERSION) - - def song_changed(self, window, song): - self.worker.send(self.scrobbler.report_now_playing, (song.artist, song.title, song.album)) - - def send_rating(self, song, rating): - if song.rating: - track = self.network.get_track(song.artist, song.title) - if rating == 'love': - self.worker.send(track.love) - elif rating == 'ban': - self.worker.send(track.ban) - logging.info("Sending song rating to last.fm") - def scrobble(self, song): + 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): - logging.info("Scrobbling song") - mode = self.pylast.SCROBBLE_MODE_PLAYED - source = self.pylast.SCROBBLE_SOURCE_PERSONALIZED_BROADCAST - self.worker.send(self.scrobbler.scrobble, (song.artist, song.title, int(song.start_time), source, mode, duration, song.album)) + 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): - def __init__(self, pylast, d, prefname, parent): - Gtk.Dialog.__init__(self) - self.set_default_size(200, -1) + __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.dict = d - self.prefname = prefname + self.worker = GObjectWorker() + self.settings = settings self.pylast = pylast - self.auth_url= False + self.auth_url = '' - label = Gtk.Label.new('In order to use LastFM you must authorize this with your account') - label.set_line_wrap(True) + 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_button_text() - self.button.connect('clicked', self.clicked) + 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')) - self.get_content_area().add(label) - self.get_content_area().show_all() - self.get_action_area().add(self.button) - self.get_action_area().set_layout(Gtk.ButtonBoxStyle.EXPAND) - - @property - def enabled(self): - return self.dict[self.prefname] - def setkey(self, key): - self.dict[self.prefname] = key - self.set_button_text() - - def set_button_text(self): + 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) - if self.auth_url: - self.button.set_label("Click once authorized on web site") - elif self.enabled: - self.button.set_label("Disable") - else: - self.button.set_label("Authorize") - - def clicked(self, *ignore): - if self.auth_url: - def err(e): - logging.error(e) - self.set_button_text() - - get_worker().send(self.sg.get_web_auth_session_key, (self.auth_url,), self.setkey, err) - self.button.set_label("Checking...") - self.button.set_sensitive(False) - self.auth_url = False - - elif self.enabled: - self.setkey(False) - else: - self.network = self.pylast.get_lastfm_network(api_key=API_KEY, api_secret=API_SECRET) - self.sg = self.pylast.SessionKeyGenerator(self.network) - - def callback(url): - self.auth_url = url - self.set_button_text() - open_browser(self.auth_url) - - get_worker().send(self.sg.get_web_auth_url, (), callback) - self.button.set_label("Connecting...") - self.button.set_sensitive(False) + 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('') diff -Nru pithos-1.1.2/pithos/plugins/mediakeys.py pithos-1.6.2/pithos/plugins/mediakeys.py --- pithos-1.1.2/pithos/plugins/mediakeys.py 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/plugins/mediakeys.py 2024-03-03 23:53:20.000000000 +0000 @@ -1,141 +1,173 @@ # -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- -### BEGIN LICENSE # Copyright (C) 2010-2012 Kevin Mehall -#This program is free software: you can redistribute it and/or modify it -#under the terms of the GNU General Public License version 3, as published -#by the Free Software Foundation. +# This program is 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. +# 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 +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . -from pithos.plugin import PithosPlugin -import sys import logging -APP_ID = 'Pithos' +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' - def bind_dbus(self): - try: - import dbus - from dbus.mainloop.glib import DBusGMainLoop - DBusGMainLoop(set_as_default=True) - except ImportError: - return False - - try: - bus = dbus.Bus(dbus.Bus.TYPE_SESSION) - except dbus.DBusException: - return False + 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 - bound = False - for de in ('gnome', 'mate'): - try: - mk = bus.get_object("org.%s.SettingsDaemon" %de, "/org/%s/SettingsDaemon/MediaKeys" %de) - mk.GrabMediaPlayerKeys(APP_ID, 0, dbus_interface='org.%s.SettingsDaemon.MediaKeys' %de) - mk.connect_to_signal("MediaPlayerKeyPressed", self.mediakey_pressed) - bound = True - logging.info("Bound media keys with DBUS (%s)" %de) - break - except dbus.DBusException as e: - logging.debug(e) - - if bound: - self.method = 'dbus' - return True - - def mediakey_pressed(self, app, action): - if app == APP_ID: + app, action = param.unpack() + if app == APP_ID: if action == 'Play': self.window.playpause_notify() elif action == 'Next': self.window.next_song() - elif action == 'Stop': - self.window.user_pause() elif action == 'Previous': self.window.bring_to_top() - - def bind_keybinder(self): - try: - import gi - gi.require_version('Keybinder', '3.0') - # Gdk needed for Keybinder - from gi.repository import Keybinder, Gdk - Keybinder.init() - except: - return False - - Keybinder.bind('XF86AudioPlay', self.window.playpause, None) - Keybinder.bind('XF86AudioStop', self.window.user_pause, None) - Keybinder.bind('XF86AudioNext', self.window.next_song, None) - Keybinder.bind('XF86AudioPrev', self.window.bring_to_top, None) - - logging.info("Bound media keys with keybinder") - self.method = 'keybinder' - return True - - def kbevent(self, event): - if event.KeyID == 179 or event.Key == 'Media_Play_Pause': - self.window.playpause_notify() - if event.KeyID == 176 or event.Key == 'Media_Next_Track': - self.window.next_song() - return True - - def bind_win32(self): - try: - import pyHook - except ImportError: - logging.warning('Please install PyHook: http://www.lfd.uci.edu/~gohlke/pythonlibs/#pyhook') - return False - self.hookman = pyHook.HookManager() - self.hookman.KeyDown = self.kbevent - self.hookman.HookKeyboard() - return True - - def osx_playpause_handler(self): - self.window.playpause_notify() - return False # Don't let others get event - - def osx_skip_handler(self): - self.window.next_song() - return False - - def bind_osx(self): - try: - import osxmmkeys - except ImportError: - logging.warning('Please install osxmmkeys: https://github.com/pushrax/osxmmkeys') - return False - except RuntimeError as e: - logging.warning('osxmmkeys failed to import: {}'.format(e)) - return False - - tap = osxmmkeys.Tap() - tap.on('play_pause', self.osx_playpause_handler) - tap.on('next_track', self.osx_skip_handler) - tap.start() + elif action in ('Stop', 'Pause'): + self.window.user_pause() - return True - - def on_enable(self): - if sys.platform == 'win32': - loaded = self.bind_win32() - elif sys.platform == 'darwin': - loaded = self.bind_osx() + 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: - loaded = self.bind_dbus() or self.bind_keybinder() + 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') - if not loaded: - logging.error("Could not bind media keys") - def on_disable(self): - logging.error("Not implemented: Can't disable media keys") + 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') diff -Nru pithos-1.1.2/pithos/plugins/mpris.py pithos-1.6.2/pithos/plugins/mpris.py --- pithos-1.1.2/pithos/plugins/mpris.py 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/plugins/mpris.py 2024-03-03 23:53:20.000000000 +0000 @@ -1,45 +1,890 @@ # -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- -### BEGIN LICENSE # Copyright (C) 2011 Rick Spencer # Copyright (C) 2011-2012 Kevin Mehall -#This program is free software: you can redistribute it and/or modify it -#under the terms of the GNU General Public License version 3, as published -#by the Free Software Foundation. +# 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. +# 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 +# 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 = 'Allows control with external programs' + description = 'Control with external programs' def on_prepare(self): - try: - from dbus.mainloop.glib import DBusGMainLoop - DBusGMainLoop(set_as_default=True) - from . import _mpris - from . import _dbus_service - except ImportError: - return "python-dbus not found" - - self.PithosMprisService = _mpris.PithosMprisService - self.PithosDBusProxy = _dbus_service.PithosDBusProxy - self.was_enabled = False + 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): - if not self.was_enabled: - self.mpris = self.PithosMprisService(self.window) - self.service = self.PithosDBusProxy(self.window) - self.was_enabled = True + '''Enables the mpris plugin.''' + self.mpris.connect() def on_disable(self): - logging.error("Not implemented: Can't disable mpris") + '''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) diff -Nru pithos-1.1.2/pithos/plugins/notification_icon.py pithos-1.6.2/pithos/plugins/notification_icon.py --- pithos-1.1.2/pithos/plugins/notification_icon.py 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/plugins/notification_icon.py 2024-03-03 23:53:20.000000000 +0000 @@ -1,96 +1,249 @@ # -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- -### BEGIN LICENSE # Copyright (C) 2010-2012 Kevin Mehall -#This program is free software: you can redistribute it and/or modify it -#under the terms of the GNU General Public License version 3, as published -#by the Free Software Foundation. +# This program is 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. +# 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 +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . -import os +import logging import gi -from gi.repository import Gtk -from pithos.pithosconfig import get_data_file -from pithos.plugin import PithosPlugin -# Use appindicator if installed +from gi.repository import ( + GLib, + Gio, + Gtk +) + try: - gi.require_version('AppIndicator3', '0.1') - from gi.repository import AppIndicator3 as AppIndicator - indicator_capable = True -except: - indicator_capable = False + 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' -class PithosNotificationIcon(PithosPlugin): + @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 icon to system tray' - + description = 'Adds Pithos StatusNotifier to tray' + def on_prepare(self): - if indicator_capable: - self.ind = AppIndicator.Indicator.new_with_path("pithos-tray-icon", \ - "pithos-tray-icon", \ - AppIndicator.IndicatorCategory.APPLICATION_STATUS, \ - get_data_file('media')) - - def on_enable(self): - self.delete_callback_handle = self.window.connect("delete-event", self.toggle_visible) - self.state_callback_handle = self.window.connect("play-state-changed", self.play_state_changed) - self.song_callback_handle = self.window.connect("song-changed", self.song_changed) - - if indicator_capable: - self.ind.set_status(AppIndicator.IndicatorStatus.ACTIVE) - else: - icon_info = Gtk.IconTheme.lookup_icon (Gtk.IconTheme.get_default(), 'pithos-tray-icon', 48, 0) - if icon_info and Gtk.IconInfo.get_filename (icon_info): - filename = Gtk.IconInfo.get_filename (icon_info) - else: - filename = get_data_file('media', 'pithos-tray-icon.png') - - self.statusicon = Gtk.StatusIcon.new () - self.statusicon.set_from_file (filename) - self.statusicon.connect('activate', self.toggle_visible) - - self.build_context_menu() - - def scroll(self, steps): - if indicator_capable: - direction = steps.value_nick - else: - direction = steps.direction.value_nick + self.playpausebtn = None - if direction == 'down': - self.window.adjust_volume(-1) - elif direction == 'up': - self.window.adjust_volume(+1) + # 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): + def _build_context_menu(self): menu = Gtk.Menu() - - def button(text, action, checked=False): - if checked: - item = Gtk.CheckMenuItem(text) - item.set_active(True) - else: - item = Gtk.MenuItem(text) - item.connect('activate', action) + + def button(text, action): + item = Gtk.MenuItem(text) + item.connect('activate', action) item.show() menu.append(item) return item - - if indicator_capable: - # We have to add another entry for show / hide Pithos window - self.visible_check = button("Show Pithos", self._toggle_visible, True) - - # On middle-click - self.ind.set_secondary_activate_target(self.visible_check) - + self.playpausebtn = button("Pause", self.window.playpause) button("Skip", self.window.next_song) button("Love", (lambda *i: self.window.love_song())) @@ -98,63 +251,76 @@ button("Tired", (lambda *i: self.window.tired_song())) button("Quit", self.window.quit) - # connect our new menu to the statusicon or the appindicator - if indicator_capable: - self.ind.set_menu(menu) - self.ind.connect('scroll-event', lambda _x, _y, steps: self.scroll(steps)) - else: - self.statusicon.connect('popup-menu', self.context_menu, menu) - self.statusicon.connect('scroll-event', lambda _, steps: self.scroll(steps)) - self.menu = menu + def _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 play_state_changed(self, window, playing): - """ play or pause and rotate the text """ - - button = self.playpausebtn - if not playing: - button.set_label("Play") - else: - button.set_label("Pause") - - if indicator_capable: # menu needs to be reset to get updated icon - self.ind.set_menu(self.menu) - - def song_changed(self, window, song): - if not indicator_capable: - self.statusicon.set_tooltip_text("%s by %s"%(song.title, song.artist)) - def _toggle_visible(self, *args): - self.window.set_visible(not self.window.get_visible()) + if self.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) - if self.window.get_visible(): # Ensure it's on top - self.window.bring_to_top() - - def toggle_visible(self, *args): - if hasattr(self, 'visible_check'): - self.visible_check.set_active(not self.window.get_visible()) - else: - self._toggle_visible() - - return True - - def context_menu(self, widget, button, time, data=None): - if button == 3: - if data: - data.show_all() - data.popup(None, None, None, None, 3, time) - def on_disable(self): - if indicator_capable: - self.ind.set_status(AppIndicator.IndicatorStatus.PASSIVE) - else: - self.statusicon.set_visible(False) - self.window.disconnect(self.delete_callback_handle) self.window.disconnect(self.state_callback_handle) - self.window.disconnect(self.song_callback_handle) - - # Pithos window needs to be reconnected to on_destro() - self.window.connect('delete-event',self.window.on_destroy) + 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() diff -Nru pithos-1.1.2/pithos/plugins/notify.py pithos-1.6.2/pithos/plugins/notify.py --- pithos-1.1.2/pithos/plugins/notify.py 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/plugins/notify.py 2024-03-03 23:53:20.000000000 +0000 @@ -1,159 +1,79 @@ # -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- -### BEGIN LICENSE # Copyright (C) 2010-2012 Kevin Mehall -#This program is free software: you can redistribute it and/or modify it -#under the terms of the GNU General Public License version 3, as published -#by the Free Software Foundation. +# This program is 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. +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranties of +# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR +# PURPOSE. See the GNU General Public License for more details. # -#You should have received a copy of the GNU General Public License along -#with this program. If not, see . -### END LICENSE - -import logging -import html -from sys import platform +# 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.pithosconfig import get_data_file +from pithos.util import is_flatpak -import gi -gi.require_version('Notify', '0.7') -from gi.repository import (GLib, Gtk) class NotifyPlugin(PithosPlugin): preference = 'notify' description = 'Shows notifications on song change' - has_notifications = False - supports_actions = False - escape_markup = False + _app = None + _app_id = None + _fallback_icon = None def on_prepare(self): - if platform == 'darwin': - return self.prepare_osx() - else: - return self.prepare_notify() - - def prepare_osx(self): - try: - from pync import Notifier - self.has_notifications = True - except ImportError: - logging.warning("pync not found.") - return "pync not found" - - self.notifier = Notifier - - def prepare_notify(self): - try: - from gi.repository import Notify - self.has_notifications = True - except ImportError: - logging.warning ("libnotify not found.") - return "libnotify not found" - - # Work-around Ubuntu's incompatible workaround for Gnome's API breaking mistake. - # https://bugzilla.gnome.org/show_bug.cgi?id=702390 - old_add_action = Notify.Notification.add_action - def new_add_action(*args): - try: - old_add_action(*args) - except TypeError: - old_add_action(*(args + (None,))) - Notify.Notification.add_action = new_add_action - - Notify.init('pithos') - self.notification = Notify.Notification() - self.notification.set_category('x-gnome.music') - self.notification.set_hint('desktop-entry', GLib.Variant.new_string('pithos')) - - caps = Notify.get_server_caps() - if 'actions' in caps: - logging.info('Notify supports actions') - self.supports_actions = True - - if 'body-markup' in caps: - self.escape_markup = True - - if 'action-icons' in caps: - self.notification.set_hint('action-icons', GLib.Variant.new_boolean(True)) - - # TODO: On gnome this can replace the tray icon, just need to add love/hate buttons - #if 'persistence' in caps: - # self.notification.set_hint('resident', GLib.Variant.new_boolean(True)) + # 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): - if self.has_notifications: - self.song_callback_handle = self.window.connect("song-changed", self.song_changed) - self.state_changed_handle = self.window.connect("user-changed-play-state", self.playstate_changed) - - def set_actions(self, playing=True): - self.notification.clear_actions() - - pause_action = 'media-playback-pause' - play_action = 'media-playback-start' - skip_action = 'media-skip-forward' - - if Gtk.Widget.get_default_direction() == Gtk.TextDirection.RTL: - play_action += '-rtl' - skip_action += '-rtl' - - if playing: - self.notification.add_action(pause_action, 'Pause', - self.notification_playpause_cb, None) - else: - self.notification.add_action(play_action, 'Play', - self.notification_playpause_cb, None) + self._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)) - self.notification.add_action(skip_action, 'Skip', - self.notification_skip_cb, None) - - def set_notification_notify(self, song, playing): - if self.supports_actions: - self.set_actions(playing) - - if song.art_pixbuf: - self.notification.set_image_from_pixbuf(song.art_pixbuf) - else: - self.notification.set_hint('image-data', None) - - msg = 'by {} from {}'.format(song.artist, song.album) - if self.escape_markup: - msg = html.escape(msg, quote=False) - self.notification.update(song.title, msg, 'audio-x-generic' if not song.art_pixbuf else None) - self.notification.show() - - def set_notification_osx(self, song, playing): - # TODO: Icons (buttons not possible?) - if playing: - self.notifier.notify('by {} from {}'.format(song.artist, song.album), - title=song.title) - - def set_notification(self, song, playing=True): - if platform == 'darwin': - self.set_notification_osx(song, playing) + 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: - self.set_notification_notify(song, playing) - - def notification_playpause_cb(self, notification, action, data, ignore=None): - self.window.playpause_notify() - - def notification_skip_cb(self, notification, action, data, ignore=None): - self.window.next_song() + 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) - def song_changed(self, window, song): - if not self.window.is_active(): - GLib.idle_add(self.set_notification, window.current_song) + notification.add_button(_('Skip'), 'app.next-song') - def playstate_changed(self, window, state): - if not self.window.is_active(): - GLib.idle_add(self.set_notification, window.current_song, state) + self._app.send_notification(self._app_id, notification) def on_disable(self): - if self.has_notifications: - self.window.disconnect(self.song_callback_handle) - self.window.disconnect(self.state_changed_handle) + 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 diff -Nru pithos-1.1.2/pithos/plugins/screensaver_pause.py pithos-1.6.2/pithos/plugins/screensaver_pause.py --- pithos-1.1.2/pithos/plugins/screensaver_pause.py 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/plugins/screensaver_pause.py 2024-03-03 23:53:20.000000000 +0000 @@ -1,99 +1,49 @@ # -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- -### BEGIN LICENSE # Copyright (C) 2010-2012 Kevin Mehall -#This program is free software: you can redistribute it and/or modify it -#under the terms of the GNU General Public License version 3, as published -#by the Free Software Foundation. +# This program is 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. +# 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 +# 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 -import logging -dbus = None + class ScreenSaverPausePlugin(PithosPlugin): preference = 'enable_screensaverpause' - description = 'Pause playback when screensaver starts' + description = 'Pause playback on screensaver' - session_bus = None + _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 bind_session_bus(self): - global dbus - try: - import dbus - from dbus.mainloop.glib import DBusGMainLoop - DBusGMainLoop(set_as_default=True) - except ImportError: - return False - - try: - self.session_bus = dbus.SessionBus() - return True - except dbus.DBusException: - return False + def _on_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): - if not self.bind_session_bus(): - logging.error("Could not bind session bus") - return - self.connect_events() or logging.error("Could not connect events") - - self.locked = 0 - self.wasplaying = False + self._signal_handle = self._app.connect('notify::screensaver-active', + self._on_screensaver_active) def on_disable(self): - if self.session_bus: - self.disconnect_events() - - self.session_bus = None - - def connect_events(self): - try: - self.receivers = [ - self.session_bus.add_signal_receiver(*args) - for args in ((self.playPause, 'ActiveChanged', 'org.gnome.ScreenSaver'), - (self.playPause, 'ActiveChanged', 'org.cinnamon.ScreenSaver'), - (self.playPause, 'ActiveChanged', 'org.freedesktop.ScreenSaver'), - (self.pause, 'Locked', 'com.canonical.Unity.Session'), - (self.play, 'Unlocked', 'com.canonical.Unity.Session'), - ) - ] - - return True - except dbus.DBusException: - logging.info("Enable failed") - return False - - def disconnect_events(self): - try: - for r in self.receivers: - r.remove() - return True - except dbus.DBusException: - return False - - def play(self): - self.locked -= 1 - if self.locked < 0: - self.locked = 0 - if not self.locked and self.wasplaying: - self.window.user_play() - - def pause(self): - if not self.locked: - self.wasplaying = self.window.playing - self.window.pause() - self.locked += 1 - - def playPause(self, screensaver_on): - if screensaver_on: - self.pause() - else: - self.play() + if self._signal_handle: + self._app.disconnect(self._signal_handle) + self._signal_handle = 0 diff -Nru pithos-1.1.2/pithos/util.py pithos-1.6.2/pithos/util.py --- pithos-1.1.2/pithos/util.py 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/pithos/util.py 2024-03-03 23:53:20.000000000 +0000 @@ -1,23 +1,204 @@ # -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- -### BEGIN LICENSE # Copyright (C) 2010-2012 Kevin Mehall -#This program is free software: you can redistribute it and/or modify it -#under the terms of the GNU General Public License version 3, as published -#by the Free Software Foundation. +# This program is 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. +# 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 +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . + import logging -import webbrowser +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) @@ -42,11 +223,32 @@ user = password = None return scheme, user, password, hostport -def open_browser(url): + +def open_browser(url, parent=None, timestamp=0): logging.info("Opening URL {}".format(url)) - webbrowser.open(url) - if isinstance(webbrowser.get(), webbrowser.BackgroundBrowser): - try: - os.wait() # workaround for http://bugs.python.org/issue5993 - except: - pass + 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 diff -Nru pithos-1.1.2/po/POTFILES pithos-1.6.2/po/POTFILES --- pithos-1.1.2/po/POTFILES 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/po/POTFILES 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,18 @@ +data/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 diff -Nru pithos-1.1.2/po/meson.build pithos-1.6.2/po/meson.build --- pithos-1.1.2/po/meson.build 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/po/meson.build 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1 @@ +i18n.gettext(meson.project_name(), preset: 'glib') diff -Nru pithos-1.1.2/requirements-osx.txt pithos-1.6.2/requirements-osx.txt --- pithos-1.1.2/requirements-osx.txt 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/requirements-osx.txt 1970-01-01 00:00:00.000000000 +0000 @@ -1,11 +0,0 @@ -# scrobble -pylast - -# notify -pync - -# mediakeys -pyobjc-core -pyobjc-framework-Cocoa -pyobjc-framework-Quartz -osxmmkeys diff -Nru pithos-1.1.2/setup.cfg pithos-1.6.2/setup.cfg --- pithos-1.1.2/setup.cfg 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/setup.cfg 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,11 @@ +[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 = _ diff -Nru pithos-1.1.2/setup.py pithos-1.6.2/setup.py --- pithos-1.1.2/setup.py 2015-11-23 11:14:23.000000000 +0000 +++ pithos-1.6.2/setup.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,112 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -### BEGIN LICENSE -# Copyright (C) 2010 Kevin Mehall -#This program is free software: you can redistribute it and/or modify it -#under the terms of the GNU General Public License version 3, as published -#by the Free Software Foundation. -# -#This program is distributed in the hope that it will be useful, but -#WITHOUT ANY WARRANTY; without even the implied warranties of -#MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR -#PURPOSE. See the GNU General Public License for more details. -# -#You should have received a copy of the GNU General Public License along -#with this program. If not, see . -### END LICENSE - -###################### DO NOT TOUCH THIS (HEAD TO THE SECOND PART) ###################### - -import sys - -if sys.version_info[0] != 3: - sys.exit("Only python 3 is supported!") - -try: - from setuptools import setup, find_packages, Command -except ImportError: - import ez_setup - ez_setup.use_setuptools() - from setuptools import setup, find_packages, Command - -try: - from sphinx.setup_command import BuildDoc -except ImportError: - class BuildDoc(Command): - description = "Build documentation with Sphinx." - user_options = [] - version = None - release = None - - def initialize_options(self): - pass - def finalize_options(self): - pass - def run(self): - print("Error: Sphinx not found!") - -import os -import sys -from pithos.pithosconfig import VERSION - -# Utility function to read the README file. -# Used for the long_description. It's nice, because now 1) we have a top level -# README file and 2) it's easier to type in the README file than to put a raw -# string in below ... -def read(fname): - return open(os.path.join(os.path.dirname(__file__), fname)).read() - -if sys.platform != 'win32': - data_files = [ - ('/usr/share/icons/hicolor/scalable/apps', ['data/icons/hicolor/pithos.svg']), - ('/usr/share/icons/hicolor/48x48/apps', ['data/icons/hicolor/pithos-tray-icon.png']), - ('/usr/share/icons/ubuntu-mono-dark/apps/16', ['data/icons/ubuntu-mono-dark/pithos-tray-icon.svg']), - ('/usr/share/icons/ubuntu-mono-light/apps/16', ['data/icons/ubuntu-mono-light/pithos-tray-icon.svg']), - ('/usr/share/appdata', ['data/pithos.appdata.xml']), - ('/usr/share/applications', ['data/pithos.desktop']) - ] -else: - data_files = [] - -setup( - name='pithos', - version=VERSION, - ext_modules=[], - license='GPL-3', - author='Kevin Mehall', - author_email='km@kevinmehall.net', - description='Pandora.com client for the GNOME desktop', - long_description=read('README.md'), - url='http://pithos.github.io', - classifiers=[ - 'Development Status :: 4 - Beta', - 'Intended Audience :: End Users/Desktop', - 'Topic :: Media', - 'License :: OSI Approved :: GPL License', - 'Programming Language :: Python', - 'Programming Language :: Python :: 3' - ], - cmdclass={ - 'build_doc': BuildDoc - }, - command_options={ - 'build_doc': { - 'version': ('setup.py', VERSION), - 'release': ('setup.py', VERSION) - } - }, - data_files=data_files, - package_data={ - 'pithos': [ - 'data/ui/*.ui', - 'data/ui/*.xml', - 'data/media/*.png', - 'data/media/*.svg' - ] - }, - packages=find_packages(), - include_package_data=True, - entry_points={ - 'gui_scripts': ['pithos = pithos.pithos:main'] - } -) diff -Nru pithos-1.1.2/zanata.xml pithos-1.6.2/zanata.xml --- pithos-1.1.2/zanata.xml 1970-01-01 00:00:00.000000000 +0000 +++ pithos-1.6.2/zanata.xml 2024-03-03 23:53:20.000000000 +0000 @@ -0,0 +1,16 @@ + + + https://translate.zanata.org/zanata + pithos + master + gettext + po + po + + {locale}.po + + + es + + +