├── clay ├── __init__.py ├── pages │ ├── __init__.py │ ├── page.py │ ├── playerqueue.py │ ├── mylibrary.py │ ├── search.py │ ├── debug.py │ ├── myplaylists.py │ ├── mystations.py │ └── settings.py ├── clipboard.py ├── eventhook.py ├── meta.py ├── config.yaml ├── colours.yaml ├── osd.py ├── log.py ├── notifications.py ├── hotkeys.py ├── playbar.py ├── settings.py ├── app.py ├── player.py ├── gp.py └── songlist.py ├── .dockerignore ├── images ├── clay-banner.png └── clay-screenshot.png ├── requirements.txt ├── docs ├── source │ ├── ref │ │ ├── gp.rst │ │ ├── app.rst │ │ ├── meta.rst │ │ ├── page.rst │ │ ├── player.rst │ │ ├── hotkeys.rst │ │ ├── playbar.rst │ │ ├── eventhook.rst │ │ ├── search.rst │ │ ├── songlist.rst │ │ ├── appsettings.rst │ │ ├── settings.rst │ │ ├── mylibrary.rst │ │ ├── myplaylists.rst │ │ ├── playerqueue.rst │ │ └── notifications.rst │ ├── index.rst │ └── conf.py └── Makefile ├── activate.sh ├── tox.ini ├── .travis.yml ├── .flake8 ├── .pylintrc ├── .codeclimate.yml ├── setup.py ├── Makefile ├── Dockerfile ├── .gitignore ├── CHANGELOG.rst ├── README.md └── LICENSE /clay/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /clay/pages/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | dist 2 | docs 3 | .env2 4 | .env3 5 | .git 6 | .gitignore 7 | .tox 8 | -------------------------------------------------------------------------------- /images/clay-banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/and3rson/clay/HEAD/images/clay-banner.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | gmusicapi==10.1.2 2 | PyYAML==3.12 3 | urwid==2.0.0 4 | codename==1.1 5 | -------------------------------------------------------------------------------- /images/clay-screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/and3rson/clay/HEAD/images/clay-screenshot.png -------------------------------------------------------------------------------- /docs/source/ref/gp.rst: -------------------------------------------------------------------------------- 1 | gp.py 2 | ##### 3 | 4 | .. automodule:: clay.gp 5 | :members: 6 | :private-members: 7 | :special-members: 8 | 9 | -------------------------------------------------------------------------------- /docs/source/ref/app.rst: -------------------------------------------------------------------------------- 1 | app.py 2 | ###### 3 | 4 | .. automodule:: clay.app 5 | :members: 6 | :private-members: 7 | :special-members: 8 | 9 | -------------------------------------------------------------------------------- /docs/source/ref/meta.rst: -------------------------------------------------------------------------------- 1 | meta.py 2 | ####### 3 | 4 | .. automodule:: clay.meta 5 | :members: 6 | :private-members: 7 | :special-members: 8 | 9 | -------------------------------------------------------------------------------- /docs/source/ref/page.rst: -------------------------------------------------------------------------------- 1 | page 2 | #### 3 | 4 | .. automodule:: clay.pages.page 5 | :members: 6 | :private-members: 7 | :special-members: 8 | 9 | -------------------------------------------------------------------------------- /docs/source/ref/player.rst: -------------------------------------------------------------------------------- 1 | player.py 2 | ######### 3 | 4 | .. automodule:: clay.player 5 | :members: 6 | :private-members: 7 | :special-members: 8 | 9 | -------------------------------------------------------------------------------- /docs/source/ref/hotkeys.rst: -------------------------------------------------------------------------------- 1 | hotkeys.py 2 | ########## 3 | 4 | .. automodule:: clay.hotkeys 5 | :members: 6 | :private-members: 7 | :special-members: 8 | 9 | -------------------------------------------------------------------------------- /docs/source/ref/playbar.rst: -------------------------------------------------------------------------------- 1 | playbar.py 2 | ########## 3 | 4 | .. automodule:: clay.playbar 5 | :members: 6 | :private-members: 7 | :special-members: 8 | 9 | -------------------------------------------------------------------------------- /activate.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if ! [[ -d ".env" ]] 4 | then 5 | virtualenv .env 6 | fi 7 | 8 | . .env/bin/activate 9 | pip install -r requirements.txt 10 | 11 | -------------------------------------------------------------------------------- /docs/source/ref/eventhook.rst: -------------------------------------------------------------------------------- 1 | eventhook.py 2 | ############ 3 | 4 | .. automodule:: clay.eventhook 5 | :members: 6 | :private-members: 7 | :special-members: 8 | 9 | -------------------------------------------------------------------------------- /docs/source/ref/search.rst: -------------------------------------------------------------------------------- 1 | settings.py 2 | ########### 3 | 4 | .. automodule:: clay.pages.search 5 | :members: 6 | :private-members: 7 | :special-members: 8 | 9 | -------------------------------------------------------------------------------- /docs/source/ref/songlist.rst: -------------------------------------------------------------------------------- 1 | songlist.py 2 | ########### 3 | 4 | .. automodule:: clay.songlist 5 | :members: 6 | :private-members: 7 | :special-members: 8 | 9 | -------------------------------------------------------------------------------- /docs/source/ref/appsettings.rst: -------------------------------------------------------------------------------- 1 | appsettings.py 2 | ############## 3 | 4 | .. automodule:: clay.settings 5 | :members: 6 | :private-members: 7 | :special-members: 8 | 9 | -------------------------------------------------------------------------------- /docs/source/ref/settings.rst: -------------------------------------------------------------------------------- 1 | settings.py 2 | ########### 3 | 4 | .. automodule:: clay.pages.settings 5 | :members: 6 | :private-members: 7 | :special-members: 8 | 9 | -------------------------------------------------------------------------------- /docs/source/ref/mylibrary.rst: -------------------------------------------------------------------------------- 1 | mylibrary.py 2 | ############ 3 | 4 | .. automodule:: clay.pages.mylibrary 5 | :members: 6 | :private-members: 7 | :special-members: 8 | 9 | -------------------------------------------------------------------------------- /docs/source/ref/myplaylists.rst: -------------------------------------------------------------------------------- 1 | myplaylists.py 2 | ############## 3 | 4 | .. automodule:: clay.pages.myplaylists 5 | :members: 6 | :private-members: 7 | :special-members: 8 | 9 | -------------------------------------------------------------------------------- /docs/source/ref/playerqueue.rst: -------------------------------------------------------------------------------- 1 | playerqueue.py 2 | ############## 3 | 4 | .. automodule:: clay.pages.playerqueue 5 | :members: 6 | :private-members: 7 | :special-members: 8 | 9 | -------------------------------------------------------------------------------- /docs/source/ref/notifications.rst: -------------------------------------------------------------------------------- 1 | notifications.py 2 | ################ 3 | 4 | .. automodule:: clay.notifications 5 | :members: 6 | :private-members: 7 | :special-members: 8 | 9 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = 3 | py27 4 | py36 5 | 6 | [testenv] 7 | usedevelop = true 8 | deps = 9 | setuptools 10 | urwid 11 | pyyaml 12 | gmusicapi 13 | pylint 14 | commands = 15 | make check 16 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | matrix: 3 | include: 4 | - python: 2.7 5 | env: TOXENV=py27 6 | - python: 3.6 7 | env: TOXENV=py36 8 | before_install: 9 | - "sudo apt-get update" 10 | - "sudo apt-get install python-gi python3-gi" 11 | install: 12 | - "pip install tox radon" 13 | script: 14 | - "tox" 15 | 16 | -------------------------------------------------------------------------------- /.flake8: -------------------------------------------------------------------------------- 1 | [flake8] 2 | # ignore = D203 3 | max-line-length=120 4 | 5 | ignore = 6 | # blank line at end of file 7 | W391 8 | 9 | exclude = 10 | # Generated stuff 11 | gen, 12 | # Coverage HTML report 13 | htmlcov, 14 | # Logs 15 | log, 16 | # Requirements 17 | requirements, 18 | # Temporary stuff 19 | tmp, 20 | # Virtual envs 21 | .env, 22 | .env2, 23 | .env3, 24 | .env36, 25 | .venv, 26 | .git, 27 | wsgi.py, 28 | utils, 29 | # VLC bindings 30 | vlc.py 31 | 32 | -------------------------------------------------------------------------------- /.pylintrc: -------------------------------------------------------------------------------- 1 | [pylint] 2 | max-line-length = 100 3 | max-args = 8 4 | 5 | [messages control] 6 | disable = 7 | duplicate-code, # Meh. 8 | too-few-public-methods, # Namespaces are great. (c) 9 | too-many-public-methods, # Namespaces are really great! 10 | too-many-instance-attributes, # Ditto. 11 | no-self-use, # Makes code less readable. 12 | too-many-ancestors, # Mixins FTW. 13 | useless-object-inheritance # Silly pylint, you forgot Python 2.x! 14 | 15 | 16 | [miscellaneous] 17 | # List of note tags to take in consideration, separated by a comma. 18 | notes= 19 | -------------------------------------------------------------------------------- /clay/pages/page.py: -------------------------------------------------------------------------------- 1 | """ 2 | Generic page classes. 3 | """ 4 | 5 | 6 | class AbstractPage(object): 7 | """ 8 | Represents app page. 9 | """ 10 | @property 11 | def name(self): 12 | """ 13 | Return page name. 14 | """ 15 | raise NotImplementedError() 16 | 17 | @property 18 | def key(self): 19 | """ 20 | Return page key (``int``), used for hotkeys. 21 | """ 22 | raise NotImplementedError() 23 | 24 | def activate(self): 25 | """ 26 | Notify page that it is activated. 27 | """ 28 | raise NotImplementedError() 29 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | SPHINXPROJ = Clay 8 | SOURCEDIR = source 9 | BUILDDIR = build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) -------------------------------------------------------------------------------- /clay/clipboard.py: -------------------------------------------------------------------------------- 1 | """ 2 | Clipboard utils. 3 | """ 4 | from subprocess import Popen, PIPE 5 | 6 | from clay.notifications import notification_area 7 | 8 | 9 | COMMANDS = [ 10 | ('xclip', '-selection', 'clipboard'), 11 | ('xsel', '-bi'), 12 | ] 13 | 14 | 15 | def copy(text): 16 | """ 17 | Copy text to clipboard. 18 | 19 | Return True on success. 20 | """ 21 | for cmd in COMMANDS: 22 | proc = Popen(cmd, stdin=PIPE) 23 | proc.communicate(text.encode('utf-8')) 24 | if proc.returncode == 0: 25 | return True 26 | 27 | notification_area.notify( 28 | 'Failed to copy text to clipboard. ' 29 | 'Please install "xclip" or "xsel".' 30 | ) 31 | return False 32 | -------------------------------------------------------------------------------- /docs/source/index.rst: -------------------------------------------------------------------------------- 1 | .. Clay documentation master file, created by 2 | sphinx-quickstart on Sat Jan 6 13:35:04 2018. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to Clay's documentation! 7 | ================================ 8 | 9 | .. toctree:: 10 | :maxdepth: 2 11 | :caption: Contents: 12 | 13 | ref/app 14 | ref/appsettings 15 | ref/gp 16 | ref/player 17 | ref/songlist 18 | ref/playbar 19 | ref/mylibrary 20 | ref/myplaylists 21 | ref/playerqueue 22 | ref/search 23 | ref/settings 24 | ref/page 25 | ref/notifications 26 | ref/hotkeys 27 | ref/eventhook 28 | ref/meta 29 | 30 | -------------------------------------------------------------------------------- /.codeclimate.yml: -------------------------------------------------------------------------------- 1 | version: "2" # required to adjust maintainability checks 2 | exclude_patterns: 3 | - "clay/vlc.py" 4 | engines: 5 | duplication: 6 | enabled: false 7 | checks: 8 | argument-count: 9 | config: 10 | threshold: 8 # maximum complexity for ~ B mark in Radon 11 | complex-logic: 12 | config: 13 | threshold: 4 14 | file-lines: 15 | config: 16 | threshold: 1000 17 | method-complexity: 18 | config: 19 | threshold: 10 20 | method-count: 21 | config: 22 | threshold: 40 23 | method-lines: 24 | config: 25 | threshold: 40 # to fit in 1366x768 screen 26 | nested-control-flow: 27 | config: 28 | threshold: 4 29 | return-statements: 30 | config: 31 | threshold: 5 32 | -------------------------------------------------------------------------------- /clay/eventhook.py: -------------------------------------------------------------------------------- 1 | """ 2 | Events implemetation for signal handling. 3 | """ 4 | 5 | 6 | class EventHook(object): 7 | """ 8 | Event that can have handlers attached. 9 | """ 10 | def __init__(self): 11 | self.event_handlers = [] 12 | 13 | def __iadd__(self, handler): 14 | """ 15 | Add event handler. 16 | """ 17 | self.event_handlers.append(handler) 18 | return self 19 | 20 | def __isub__(self, handler): 21 | """ 22 | Remove event handler. 23 | """ 24 | self.event_handlers.remove(handler) 25 | return self 26 | 27 | def fire(self, *args, **kwargs): 28 | """ 29 | Execute all handlers. 30 | """ 31 | for handler in self.event_handlers: 32 | handler(*args, **kwargs) 33 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from setuptools import setup, find_packages 4 | from clay.meta import VERSION 5 | 6 | setup( 7 | name='clay-player', 8 | version=VERSION, 9 | description='Command Line Player for Google Play Music', 10 | long_description=open('README.md', 'r').read(), 11 | long_description_content_type='text/markdown', 12 | author='Andrew Dunai', 13 | author_email='a@dun.ai', 14 | url='https://github.com/and3rson/clay', 15 | install_requires=[ 16 | 'gmusicapi', 17 | 'PyYAML', 18 | 'urwid', 19 | 'codename' 20 | ], 21 | packages=find_packages(), 22 | entry_points={ 23 | 'console_scripts': [ 24 | 'clay=clay.app:main' 25 | ] 26 | }, 27 | package_data={ 28 | 'clay': ['config.yaml', 'colours.yaml'], 29 | }, 30 | ) 31 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | CMD ?= "./clay/app.py" 2 | 3 | # Build Clay Docker image 4 | build: 5 | echo $(shell id -u) 6 | docker build -t clay --build-arg HOST_USER=${USER} --build-arg HOST_UID=$(shell id -u) . 7 | 8 | # Run Clay Docker image 9 | run: | build 10 | docker run -it \ 11 | --rm \ 12 | --name clay \ 13 | -v ${HOME}/.config/clay:/home/${USER}/.config/clay \ 14 | -v /dev/shm:/dev/shm \ 15 | -v /etc/machine-id:/etc/machine-id \ 16 | -v /run/user/${UID}/pulse:/run/user/${UID}/pulse \ 17 | -v /var/lib/dbus:/var/lib/dbus \ 18 | -v ${HOME}/.pulse:/home/${USER}/.pulse \ 19 | -v ${HOME}/.config/pulse:/home/${USER}/.config/pulse \ 20 | --tty \ 21 | -u ${USER} \ 22 | clay \ 23 | ${CMD} 24 | 25 | # Generate Sphinx docs 26 | .PHONY: docs 27 | docs: 28 | make -C docs html 29 | 30 | # Run pylint & radon 31 | check: 32 | pylint clay --ignore-imports=y 33 | radon cc -a -s -nC -e clay/vlc.py clay 34 | -------------------------------------------------------------------------------- /clay/meta.py: -------------------------------------------------------------------------------- 1 | """ 2 | Predefined values. 3 | """ 4 | APP_NAME = 'Clay Player' 5 | VERSION = '1.1.0' 6 | AUTHOR = "Andrew Dunai" 7 | DESCRIPTION = "Awesome standalone command line player for Google Play Music" 8 | 9 | try: 10 | from codename import codename 11 | except ImportError: 12 | VERSION_WITH_CODENAME = VERSION 13 | else: 14 | VERSION_WITH_CODENAME = VERSION + ' (' + codename(separator=' ', id=VERSION) + ')' 15 | 16 | COPYRIGHT_MESSAGE = """{app_name} {version} 17 | 18 | Copyright 2017 - {year} (C) {author} and {app_name} contributors. 19 | License GPLv3+: GNU GPL version 3 or later 20 | This is free software; you are free to change it and redistribute it. 21 | There is NO WARRANTY, to the extent permitted by law 22 | """.format(app_name=APP_NAME, year=2018, 23 | version=VERSION_WITH_CODENAME, author=AUTHOR) 24 | 25 | USER_AGENT = ' '.join([ 26 | 'Mozilla/5.0 (X11; Linux x86_64)' 27 | 'AppleWebKit/537.36 (KHTML, like Gecko)' 28 | 'Chrome/62.0.3202.94 Safari/537.36' 29 | ]) 30 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:18.04 2 | MAINTAINER Andrew Dunai 3 | 4 | ARG HOST_USER 5 | ARG HOST_UID 6 | 7 | ENV PYTHONIOENCODING UTF-8 8 | ENV LANG en_US.UTF-8 9 | ENV LANGUAGE en_US:en 10 | ENV LC_ALL en_US.UTF-8 11 | 12 | RUN apt-get update 13 | RUN apt-get install -y python3.6-dev python3-pip libvlc-dev vlc locales language-pack-en wget 14 | 15 | RUN locale-gen en_US.UTF-8 16 | 17 | RUN useradd ${HOST_USER} -m -G audio -u ${HOST_UID} 18 | 19 | WORKDIR /home/${HOST_USER} 20 | 21 | RUN wget https://launchpad.net/ubuntu/+archive/primary/+files/python3-stdlib-extensions_3.6.4.orig.tar.xz && \ 22 | tar -xvf python3-stdlib-extensions_3.6.4.orig.tar.xz && \ 23 | cp -r python3-stdlib-extensions-3.6.4/3.6/Lib/lib2to3/ /usr/lib/python3.6/ && \ 24 | rm -rf python3-stdlib-extensions-3.6.4 python3-stdlib-extensions-3.6.4.orig.tar.xz 25 | 26 | COPY requirements.txt . 27 | 28 | RUN python3.6 -m pip install -r requirements.txt 29 | 30 | RUN echo "default-server = 172.17.0.1" >> /etc/pulse/client.conf 31 | ENV PULSE_SERVER 172.17.0.1 32 | 33 | USER ${HOST_USER} 34 | RUN mkdir .config 35 | 36 | COPY clay ./clay 37 | -------------------------------------------------------------------------------- /clay/config.yaml: -------------------------------------------------------------------------------- 1 | #: pylint:skip-file 2 | hotkeys: 3 | mod_key: ctrl 4 | 5 | x_hotkeys: 6 | play_pause: XF86AudioPlay 7 | next: XF86AudioNext 8 | prev: XF86AudioPrev 9 | 10 | clay_hotkeys: 11 | global: 12 | seek_start: mod + q 13 | play_pause: mod + p 14 | seek_backward: shift + left 15 | seek_forward: shift + right 16 | quit: mod + x 17 | toggle_shuffle: mod + r 18 | next_song: mod + d 19 | prev_song: mod + a 20 | toggle_repeat_one: mod + o 21 | handle_escape: esc, mod + _ 22 | show_debug: meta + 0 23 | show_library: meta + 1 24 | show_playlists: meta + 2 25 | show_stations: meta + 3 26 | show_queue: meta + 4 27 | show_search: meta + 5 28 | show_settings: meta + 9 29 | 30 | library_item: 31 | activate: enter 32 | append: mod + a 33 | unappend: mod + u 34 | request_station: meta + s 35 | show_context_menu: meta + p 36 | thumbs_up: meta + u 37 | thumbs_down: meta + d 38 | 39 | library_view: 40 | move_to_beginning: home 41 | move_to_end: end 42 | move_up: up 43 | move_down: down 44 | hide_context_menu: meta + p 45 | 46 | playlist_page: 47 | start_playlist: enter 48 | 49 | station_page: 50 | start_station: enter 51 | 52 | debug_page: 53 | copy_message: enter 54 | 55 | search_page: 56 | send_query: enter 57 | 58 | settings_page: 59 | equalizer_up: "+" 60 | equalizer_down: "-" 61 | 62 | clay_settings: 63 | x_keybinds: false 64 | unicode: true 65 | 66 | play_settings: 67 | authtoken: 68 | device_id: 69 | download_tracks: false 70 | password: 71 | username: 72 | -------------------------------------------------------------------------------- /clay/pages/playerqueue.py: -------------------------------------------------------------------------------- 1 | """ 2 | Components for "Queue" page. 3 | """ 4 | import urwid 5 | 6 | from clay.songlist import SongListBox 7 | from clay.player import player 8 | from clay.pages.page import AbstractPage 9 | 10 | 11 | class QueuePage(urwid.Columns, AbstractPage): 12 | """ 13 | Queue page. 14 | """ 15 | @property 16 | def name(self): 17 | return 'Queue' 18 | 19 | @property 20 | def key(self): 21 | return 4 22 | 23 | @property 24 | def slug(self): 25 | """ 26 | Return page ID (str). 27 | """ 28 | return "queue" 29 | 30 | def __init__(self, app): 31 | self.app = app 32 | self.songlist = SongListBox(app) 33 | 34 | self.songlist.populate(player.get_queue_tracks()) 35 | player.queue_changed += self.queue_changed 36 | player.track_appended += self.track_appended 37 | player.track_removed += self.track_removed 38 | 39 | super(QueuePage, self).__init__([ 40 | self.songlist 41 | ]) 42 | 43 | def queue_changed(self): 44 | """ 45 | Called when player queue is changed. 46 | Updates this queue widget. 47 | """ 48 | self.songlist.populate(player.get_queue_tracks()) 49 | 50 | def track_appended(self, track): 51 | """ 52 | Called when new track is appended to the player queue. 53 | Appends track to this queue widget. 54 | """ 55 | self.songlist.append_track(track) 56 | 57 | def track_removed(self, track): 58 | """ 59 | Called when a track is removed from the player queue. 60 | Removes track from this queue widget. 61 | """ 62 | self.songlist.remove_track(track) 63 | 64 | def activate(self): 65 | pass 66 | -------------------------------------------------------------------------------- /clay/colours.yaml: -------------------------------------------------------------------------------- 1 | default: &default 2 | foreground: "#FFF" 3 | background: null 4 | 5 | primary: &primary 6 | foreground: "#F54" 7 | background: null 8 | 9 | primary_inv: &primary_inv 10 | foreground: "#FFF" 11 | background: "#F54" 12 | 13 | secondary: &secondary 14 | foreground: "#17F" 15 | background: "#FFF" 16 | 17 | secondary_inv: &secondary_inv 18 | foreground: "#FFF" 19 | background: "#17F" 20 | 21 | background: *default 22 | None: *default 23 | '': *default 24 | 25 | logo: *primary 26 | progress: *primary 27 | progressbar_done: *primary 28 | selected: *primary_inv 29 | 30 | progress_remaining: 31 | foreground: "#FFF" 32 | background: "#444" 33 | 34 | progressbar_done_paused: 35 | <<: *default 36 | foreground: null 37 | 38 | progressbar_remaining: 39 | <<: *default 40 | foreground: "#222" 41 | 42 | title-idle: 43 | <<: *default 44 | foreground: null 45 | 46 | title-playing: *primary 47 | 48 | panel: 49 | foreground: "#FFF" 50 | background: "#222" 51 | 52 | panel_focus: *primary_inv 53 | 54 | panel_divider: 55 | foreground: "#444" 56 | background: "#222" 57 | 58 | panel_divider_focus: 59 | foreground: "#444" 60 | background: '#F54' 61 | 62 | line1: *default 63 | line1_focus: 64 | foreground: "#FFF" 65 | background: "#333" 66 | 67 | line1_active: *primary 68 | 69 | line1_active_focus: 70 | foreground: "#F54" 71 | background: "#333" 72 | 73 | line2: 74 | <<: *default 75 | foreground: "#AAA" 76 | 77 | line2_focus: 78 | foreground: "#AAA" 79 | background: "#333" 80 | 81 | input: 82 | foreground: "#FFF" 83 | background: "#444" 84 | 85 | input_focus: *primary_inv 86 | 87 | flag: 88 | <<: *default 89 | foreground: "#AAA" 90 | 91 | flag-active: *primary 92 | 93 | notification: 94 | foreground: "#F54" 95 | background: "#222" 96 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | docs/build/ 67 | 68 | # PyBuilder 69 | target/ 70 | 71 | # Jupyter Notebook 72 | .ipynb_checkpoints 73 | 74 | # pyenv 75 | .python-version 76 | 77 | # celery beat schedule file 78 | celerybeat-schedule 79 | 80 | # SageMath parsed files 81 | *.sage.py 82 | 83 | # dotenv 84 | .env 85 | .env2 86 | .env3 87 | 88 | # virtualenv 89 | .venv 90 | .venv2 91 | .venv3 92 | venv/ 93 | ENV/ 94 | 95 | # Spyder project settings 96 | .spyderproject 97 | .spyproject 98 | 99 | # Rope project settings 100 | .ropeproject 101 | 102 | # mkdocs documentation 103 | /site 104 | 105 | # mypy 106 | .mypy_cache/ 107 | 108 | # Editor 109 | #* 110 | *~ 111 | -------------------------------------------------------------------------------- /clay/pages/mylibrary.py: -------------------------------------------------------------------------------- 1 | """ 2 | Library page. 3 | """ 4 | import urwid 5 | 6 | from clay.gp import gp 7 | from clay.songlist import SongListBox 8 | from clay.notifications import notification_area 9 | from clay.pages.page import AbstractPage 10 | 11 | 12 | class MyLibraryPage(urwid.Columns, AbstractPage): 13 | """ 14 | My library page. 15 | 16 | Displays :class:`clay.songlist.SongListBox` with all songs in library. 17 | """ 18 | @property 19 | def name(self): 20 | return 'Library' 21 | 22 | @property 23 | def key(self): 24 | return 1 25 | 26 | @property 27 | def slug(self): 28 | """ 29 | Return page ID (str). 30 | """ 31 | return "library" 32 | 33 | def __init__(self, app): 34 | self.app = app 35 | self.songlist = SongListBox(app) 36 | self.notification = None 37 | 38 | gp.auth_state_changed += self.get_all_songs 39 | gp.caches_invalidated += self.get_all_songs 40 | 41 | super(MyLibraryPage, self).__init__([ 42 | self.songlist 43 | ]) 44 | 45 | def on_get_all_songs(self, tracks, error): 46 | """ 47 | Called when all library songs are fetched from server. 48 | Populate song list. 49 | """ 50 | if error: 51 | notification_area.notify('Failed to load my library: {}'.format(str(error))) 52 | return 53 | tracks.sort(key=lambda k: k.original_data['title']) 54 | self.songlist.populate(tracks) 55 | self.app.redraw() 56 | 57 | def get_all_songs(self, *_): 58 | """ 59 | Called when auth state changes or GP caches are invalidated. 60 | """ 61 | if gp.is_authenticated: 62 | self.songlist.set_placeholder(u'\n \uf01e Loading song list...') 63 | 64 | gp.get_all_tracks_async(callback=self.on_get_all_songs) 65 | self.app.redraw() 66 | 67 | def activate(self): 68 | pass 69 | -------------------------------------------------------------------------------- /clay/osd.py: -------------------------------------------------------------------------------- 1 | """ 2 | On-screen display stuff. 3 | """ 4 | from threading import Thread 5 | 6 | from clay.notifications import notification_area 7 | from clay import meta 8 | 9 | IS_INIT = False 10 | 11 | try: 12 | from dbus import SessionBus, Interface 13 | IS_INIT = True 14 | except ImportError: 15 | ERROR_MESSAGE = 'Could not import dbus. OSD notifications will be disabled.' 16 | except Exception as exception: # pylint: disable=broad-except 17 | ERROR_MESSAGE = 'Error while importing dbus: \'{}\''.format(str(exception)) 18 | 19 | if not IS_INIT: 20 | notification_area.notify(ERROR_MESSAGE) 21 | 22 | 23 | class _OSDManager(object): 24 | """ 25 | Manages OSD notifications via DBus. 26 | """ 27 | def __init__(self): 28 | self._last_id = 0 29 | 30 | if IS_INIT: 31 | self.bus = SessionBus() 32 | self.notifcations = self.bus.get_object( 33 | "org.freedesktop.Notifications", 34 | "/org/freedesktop/Notifications" 35 | ) 36 | self.notify_interface = Interface(self.notifcations, "org.freedesktop.Notifications") 37 | 38 | def notify(self, track): 39 | """ 40 | Create new or update existing notification. 41 | """ 42 | if IS_INIT: 43 | thread = Thread(target=self._notify, args=(track,)) 44 | thread.daemon = True 45 | thread.start() 46 | 47 | def _notify(self, track): 48 | artist_art_filename = track.get_artist_art_filename() 49 | self._last_id = self.notify_interface.Notify( 50 | meta.APP_NAME, 51 | self._last_id, 52 | artist_art_filename if artist_art_filename is not None else 'audio-headphones', 53 | track.title, 54 | u'by {}\nfrom {}'.format(track.artist, track.album_name), 55 | [], 56 | dict(), 57 | 5000 58 | ) 59 | 60 | 61 | osd_manager = _OSDManager() # pylint: disable=invalid-name 62 | -------------------------------------------------------------------------------- /clay/log.py: -------------------------------------------------------------------------------- 1 | """ 2 | Logger implementation. 3 | """ 4 | # pylint: disable=too-few-public-methods 5 | from threading import Lock 6 | from datetime import datetime 7 | 8 | from clay.eventhook import EventHook 9 | 10 | 11 | class _LoggerRecord(object): 12 | """ 13 | Represents a logger record. 14 | """ 15 | def __init__(self, verbosity, message, args): 16 | self._timestamp = datetime.now() 17 | self._verbosity = verbosity 18 | self._message = message 19 | self._args = args 20 | 21 | @property 22 | def formatted_timestamp(self): 23 | """ 24 | Return timestamp. 25 | """ 26 | return str(self._timestamp) 27 | 28 | @property 29 | def verbosity(self): 30 | """ 31 | Return verbosity. 32 | """ 33 | return self._verbosity 34 | 35 | @property 36 | def formatted_message(self): 37 | """ 38 | Return formatted message. 39 | """ 40 | return self._message % self._args 41 | 42 | 43 | class _Logger(object): 44 | """ 45 | Global logger. 46 | 47 | Allows subscribing to log events. 48 | """ 49 | 50 | def __init__(self): 51 | self.logs = [] 52 | self.logfile = open('/tmp/clay.log', 'w') 53 | 54 | self._lock = Lock() 55 | 56 | self.on_log_event = EventHook() 57 | 58 | def log(self, level, message, *args): 59 | """ 60 | Add log item. 61 | """ 62 | self._lock.acquire() 63 | try: 64 | logger_record = _LoggerRecord(level, message, args) 65 | self.logs.append(logger_record) 66 | self.logfile.write('{} {:8} {}\n'.format( 67 | logger_record.formatted_timestamp, 68 | logger_record.verbosity, 69 | logger_record.formatted_message 70 | )) 71 | self.logfile.flush() 72 | self.on_log_event.fire(logger_record) 73 | finally: 74 | self._lock.release() 75 | 76 | def debug(self, message, *args): 77 | """ 78 | Add debug log item. 79 | """ 80 | self.log('DEBUG', message, *args) 81 | 82 | def info(self, message, *args): 83 | """ 84 | Add info log item. 85 | """ 86 | self.log('INFO', message, *args) 87 | 88 | def warn(self, message, *args): 89 | """ 90 | Add warning log item. 91 | """ 92 | self.log('WARNING', message, *args) 93 | 94 | warning = warn 95 | 96 | def error(self, message, *args): 97 | """ 98 | Add error log item. 99 | """ 100 | self.log('ERROR', message, *args) 101 | 102 | def get_logs(self): 103 | """ 104 | Return all logs. 105 | """ 106 | return self.logs 107 | 108 | 109 | logger = _Logger() # pylint: disable=invalid-name 110 | -------------------------------------------------------------------------------- /CHANGELOG.rst: -------------------------------------------------------------------------------- 1 | Changelog 2 | --------- 3 | 4 | Clay 1.2.0 5 | ========== 6 | 7 | TBA 8 | 9 | Clay 1.1.0 10 | ========== 11 | 12 | 2018-08-09 13 | 14 | * Liked Songs Playlist (by Valentijn) 15 | * Thumbs Up / Thumbs Down (by Valentijn) 16 | * Alphabetical Sorting in Library View (by Valentijn) 17 | * Explicit Rating Icon (by Valentijn) 18 | * OSD notifications 19 | * setproctitle to nicely display clay in process list 20 | * Various bugfixes 21 | * Fix #29 (customizable tab activation hotkeys) 22 | * Fix #31 (rating issues) 23 | 24 | Clay 1.0.0 25 | ========== 26 | 27 | 2018-04-06 28 | 29 | * Configurable keybinds (by Valentijn) 30 | * Configurable colors (by Valentijn) 31 | * Pluggable X keybinds (by Valentijn) 32 | * "My stations" page (by @Fluctuz) 33 | * Better settings management (by Valentijn) 34 | * Equalizer 35 | * Track caching indicator 36 | * Optimized settings & cache 37 | * Code complexity & code climate integration 38 | * Countless fixes 39 | * Badges! 40 | * IRC channel! 41 | 42 | Clay 0.7.2 43 | ========== 44 | 45 | 2018-02-12 46 | 47 | * Added --transparent flag 48 | 49 | Clay 0.7.1 50 | ========== 51 | 52 | 2018-02-08 53 | 54 | * Late fix for broken setup.py entrypoint support 55 | 56 | Clay 0.7.0 57 | ========== 58 | 59 | 2018-02-08 60 | 61 | * Added Dockerfile 62 | * Fixed installation instructions in README (by Valentijn) 63 | * Load global hotkeys when X is running only (by Valentijn) 64 | * Clarified in README that keybinder and pygobject are optional (by Valentijn) 65 | * Improved error handling and reporting (by Valentijn) 66 | * Version, help and keybinder command line arguments (by Valentijn) 67 | * Added copyright (by Valentijn) 68 | 69 | Clay 0.6.2 70 | ========== 71 | 72 | 2018-02-02 73 | 74 | * Fixed playback for non-subscribed accounts 75 | 76 | Clay 0.6.1 77 | ========== 78 | 79 | 2018-02-02 80 | 81 | * Attempt to fix purchased song while not on paid subscription 82 | 83 | Clay 0.6.0 84 | ========== 85 | 86 | 2018-02-01 87 | 88 | * Added track caching option 89 | * More debugging 90 | 91 | Clay 0.5.6 92 | ========== 93 | 94 | 2018-01-31 95 | 96 | * Added debug page 97 | 98 | Clay 0.5.5 99 | ========== 100 | 101 | 2018-01-31 102 | 103 | * Added CLAY_DEBUG to log Google Play Music traffic 104 | * Fixed typo in install_requires 105 | * Updated README 106 | 107 | Clay 0.5.3 108 | ========== 109 | 110 | 2018-01-30 111 | 112 | * Added codename 113 | * Linter fixes 114 | 115 | Clay 0.5.2 116 | ========== 117 | 118 | 2018-01-30 119 | 120 | * Fixed versioning 121 | 122 | Clay 0.5.1 123 | ========== 124 | 125 | 2018-01-30 126 | 127 | * Debugging 128 | * Cleanup & typos 129 | * Fixed issue with uploaded tracks 130 | 131 | Clay 0.5 132 | ======== 133 | 134 | 2018-01-29 135 | 136 | * Added slider for eqializer 137 | * Updated README 138 | * Misc fixes 139 | 140 | Clay 0.4 141 | ======== 142 | * Added equalizer 143 | 144 | 2018-01-29 145 | 146 | Clay 0.3 147 | ======== 148 | 149 | 2018-01-26 150 | 151 | * Initial functionality 152 | * Cleanups 153 | * Notifications 154 | * Hotkeys 155 | * Linting 156 | * Documentation 157 | * Song search 158 | * Song context menu 159 | * Clearer song IDs 160 | * Auth token caching 161 | * Colors 162 | * Copy URL to clipboard 163 | -------------------------------------------------------------------------------- /clay/pages/search.py: -------------------------------------------------------------------------------- 1 | """ 2 | Components for search page. 3 | """ 4 | import urwid 5 | 6 | from clay.gp import gp 7 | from clay.songlist import SongListBox 8 | from clay.notifications import notification_area 9 | from clay.hotkeys import hotkey_manager 10 | from clay.pages.page import AbstractPage 11 | 12 | 13 | class ArtistListBox(urwid.ListBox): 14 | """ 15 | Widget that displays list of artists. 16 | """ 17 | def __init__(self): 18 | self.walker = urwid.SimpleListWalker([]) 19 | super(ArtistListBox, self).__init__(self.walker) 20 | 21 | 22 | class SearchBox(urwid.Columns): 23 | """ 24 | Widget that displays search input and results. 25 | """ 26 | signals = ['search-requested'] 27 | 28 | def __init__(self): 29 | self.query = urwid.Edit() 30 | super(SearchBox, self).__init__([ 31 | ('pack', urwid.Text('Search: ')), 32 | urwid.AttrWrap(self.query, 'input', 'input_focus') 33 | ]) 34 | 35 | def keypress(self, size, key): 36 | """ 37 | Handle keypress. 38 | """ 39 | return hotkey_manager.keypress("search_page", self, super(SearchBox, self), size, key) 40 | 41 | def send_query(self): 42 | """ 43 | Send a message to urwid to search the filled in search query 44 | """ 45 | urwid.emit_signal(self, 'search-requested', self.query.edit_text) 46 | 47 | 48 | class SearchPage(urwid.Pile, AbstractPage): 49 | """ 50 | Search page. 51 | 52 | Allows to perform searches & displays search results. 53 | """ 54 | @property 55 | def name(self): 56 | return 'Search' 57 | 58 | @property 59 | def key(self): 60 | return 5 61 | 62 | @property 63 | def slug(self): 64 | """ 65 | Return page ID (str). 66 | """ 67 | return "search" 68 | 69 | def __init__(self, app): 70 | self.app = app 71 | self.songlist = SongListBox(app) 72 | 73 | self.search_box = SearchBox() 74 | 75 | urwid.connect_signal(self.search_box, 'search-requested', self.perform_search) 76 | 77 | super(SearchPage, self).__init__([ 78 | ('pack', self.search_box), 79 | ('pack', urwid.Divider(u'\u2500')), 80 | self.songlist 81 | ]) 82 | 83 | def perform_search(self, query): 84 | """ 85 | Search tracks by query. 86 | """ 87 | self.songlist.set_placeholder(u' \U0001F50D Searching for "{}"...'.format( 88 | query 89 | )) 90 | gp.search_async(query, callback=self.search_finished) 91 | 92 | def search_finished(self, results, error): 93 | """ 94 | Populate song list with search results. 95 | """ 96 | if error: 97 | notification_area.notify('Failed to search: {}'.format(str(error))) 98 | else: 99 | self.songlist.populate(results.get_tracks()) 100 | self.app.redraw() 101 | 102 | def activate(self): 103 | pass 104 | 105 | def keypress(self, size, key): 106 | if key == 'tab': 107 | if self.focus == self.search_box: 108 | self.focus_position = 2 109 | else: 110 | self.focus_position = 0 111 | return None 112 | return super(SearchPage, self).keypress(size, key) 113 | -------------------------------------------------------------------------------- /clay/pages/debug.py: -------------------------------------------------------------------------------- 1 | """ 2 | Debug page. 3 | """ 4 | import urwid 5 | 6 | from clay.pages.page import AbstractPage 7 | from clay.log import logger 8 | from clay.clipboard import copy 9 | from clay.gp import gp 10 | from clay.hotkeys import hotkey_manager 11 | 12 | 13 | class DebugItem(urwid.AttrMap): 14 | """ 15 | Represents a single debug log item. 16 | """ 17 | def selectable(self): 18 | return True 19 | 20 | def __init__(self, log_record): 21 | self.log_record = log_record 22 | 23 | self.columns = urwid.Columns([ 24 | ('pack', urwid.Text(self.log_record.verbosity.ljust(8))), 25 | urwid.Text( 26 | ( 27 | self.log_record.formatted_timestamp + 28 | '\n' + 29 | self.log_record.formatted_message 30 | ) 31 | ) 32 | ]) 33 | 34 | super(DebugItem, self).__init__(self.columns, 'line1', 'line1_focus') 35 | 36 | def keypress(self, _, key): 37 | """ 38 | Handle heypress. 39 | """ 40 | return hotkey_manager.keypress("debug_page", self, None, None, key) 41 | 42 | def copy_message(self): 43 | """Copy the selected error message to the clipboard""" 44 | copy(self.log_record.formatted_message) 45 | 46 | 47 | class DebugPage(urwid.Pile, AbstractPage): 48 | """ 49 | Represents debug page. 50 | """ 51 | def __init__(self, app): 52 | self.app = app 53 | self.walker = urwid.SimpleListWalker([]) 54 | for log_record in logger.get_logs(): 55 | self._append_log(log_record) 56 | logger.on_log_event += self._append_log 57 | self.listbox = urwid.ListBox(self.walker) 58 | 59 | self.debug_data = urwid.Text('') 60 | 61 | super(DebugPage, self).__init__([ 62 | ('pack', self.debug_data), 63 | ('pack', urwid.Text('')), 64 | ('pack', urwid.Text('Hit "Enter" to copy selected message to clipboard.')), 65 | ('pack', urwid.Divider(u'\u2550')), 66 | self.listbox 67 | ]) 68 | 69 | gp.auth_state_changed += self.update 70 | 71 | self.update() 72 | 73 | def update(self, *_): 74 | """ 75 | Update this widget. 76 | """ 77 | self.debug_data.set_text( 78 | '- Is authenticated: {}\n' 79 | '- Is subscribed: {}'.format( 80 | gp.is_authenticated, 81 | gp.is_subscribed if gp.is_authenticated else None 82 | ) 83 | ) 84 | 85 | def _append_log(self, log_record): 86 | """ 87 | Add log record to list. 88 | """ 89 | self.walker.insert(0, urwid.Divider(u'\u2500')) 90 | self.walker.insert(0, DebugItem(log_record)) 91 | 92 | @property 93 | def name(self): 94 | """ 95 | Return page name. 96 | """ 97 | return "Debug" 98 | 99 | @property 100 | def slug(self): 101 | """ 102 | Return page ID (str). 103 | """ 104 | return "debug" 105 | 106 | @property 107 | def key(self): 108 | """ 109 | Return page key (``int``), used for hotkeys. 110 | """ 111 | return 0 112 | 113 | def activate(self): 114 | """ 115 | Notify page that it is activated. 116 | """ 117 | pass 118 | -------------------------------------------------------------------------------- /clay/notifications.py: -------------------------------------------------------------------------------- 1 | """ 2 | Notification widgets. 3 | """ 4 | import urwid 5 | 6 | 7 | class _Notification(urwid.Columns): 8 | """ 9 | Single notification widget. 10 | Can be updated or closed. 11 | """ 12 | TEMPLATE = u' \u26A1 {}' 13 | 14 | def __init__(self, area, notification_id, message): 15 | self.area = area 16 | self._id = notification_id 17 | self.text = urwid.Text('') 18 | self._set_text(message) 19 | super(_Notification, self).__init__([ 20 | urwid.AttrWrap( 21 | urwid.Columns([ 22 | self.text, 23 | ('pack', urwid.Text('[Hit ESC to close] ')) 24 | ]), 25 | 'notification' 26 | ) 27 | ]) 28 | 29 | @property 30 | def id(self): # pylint: disable=invalid-name 31 | """ 32 | Notification ID. 33 | """ 34 | return self._id 35 | 36 | def _set_text(self, message): 37 | """ 38 | Set contents for this notification. 39 | """ 40 | message = message.split('\n') 41 | message = '\n'.join([ 42 | message[0] 43 | ] + [' {}'.format(line) for line in message[1:]]) 44 | self.text.set_text(_Notification.TEMPLATE.format(message)) 45 | 46 | def update(self, message): 47 | """ 48 | Update notification message. 49 | """ 50 | self._set_text(message) 51 | if not self.is_alive: 52 | self.area.append_notification(self) 53 | self.area.app.redraw() 54 | 55 | @property 56 | def is_alive(self): 57 | """ 58 | Return True if notification is currently visible. 59 | """ 60 | for notification, _ in self.area.contents: 61 | if notification is self: 62 | return True 63 | return False 64 | 65 | def close(self): 66 | """ 67 | Close notification. 68 | """ 69 | for notification, props in reversed(self.area.contents): 70 | if notification is self: 71 | self.area.contents.remove((notification, props)) 72 | 73 | if self.area.app is not None: 74 | self.area.app.redraw() 75 | 76 | 77 | class _NotificationArea(urwid.Pile): 78 | """ 79 | Notification area widget. 80 | """ 81 | 82 | def __init__(self): 83 | self.app = None 84 | self.last_id = 0 85 | self.notifications = {} 86 | super(_NotificationArea, self).__init__([]) 87 | 88 | def set_app(self, app): 89 | """ 90 | Set app instance. 91 | 92 | Required for proper screen redraws when 93 | new notifications are created asynchronously. 94 | """ 95 | self.app = app 96 | 97 | def notify(self, message): 98 | """ 99 | Create new notification with message. 100 | """ 101 | self.last_id += 1 102 | notification = _Notification(self, self.last_id, message) 103 | self.append_notification(notification) 104 | return notification 105 | 106 | def append_notification(self, notification): 107 | """ 108 | Append an existing notification (that was probably closed). 109 | """ 110 | self.contents.append( 111 | ( 112 | notification, 113 | ('weight', 1) 114 | ) 115 | ) 116 | if self.app is not None: 117 | self.app.redraw() 118 | 119 | def close_all(self): 120 | """ 121 | Close all notifications. 122 | """ 123 | while self.contents: 124 | self.contents[0][0].close() 125 | 126 | def close_newest(self): 127 | """ 128 | Close newest notification 129 | """ 130 | if not self.contents: 131 | return 132 | self.contents[-1][0].close() 133 | 134 | 135 | notification_area = _NotificationArea() # pylint: disable=invalid-name 136 | -------------------------------------------------------------------------------- /clay/pages/myplaylists.py: -------------------------------------------------------------------------------- 1 | """ 2 | Components for "My playlists" page. 3 | """ 4 | import urwid 5 | 6 | from clay.gp import gp 7 | from clay.songlist import SongListBox 8 | from clay.notifications import notification_area 9 | from clay.pages.page import AbstractPage 10 | from clay.hotkeys import hotkey_manager 11 | 12 | 13 | class MyPlaylistListItem(urwid.Columns): 14 | """ 15 | One playlist in the list of playlists. 16 | """ 17 | signals = ['activate'] 18 | 19 | def __init__(self, playlist): 20 | self.playlist = playlist 21 | self.text = urwid.SelectableIcon(u' \u2630 {} ({})'.format( 22 | self.playlist.name, 23 | len(self.playlist.tracks) 24 | ), cursor_position=3) 25 | self.text.set_layout('left', 'clip', None) 26 | self.content = urwid.AttrWrap( 27 | self.text, 28 | 'default', 29 | 'selected' 30 | ) 31 | super(MyPlaylistListItem, self).__init__([self.content]) 32 | 33 | def keypress(self, size, key): 34 | """ 35 | Handle keypress. 36 | """ 37 | return hotkey_manager.keypress("playlist_page", self, super(MyPlaylistListItem, self), 38 | size, key) 39 | 40 | def start_playlist(self): 41 | """ 42 | Start playing the selected playlist 43 | """ 44 | urwid.emit_signal(self, 'activate', self) 45 | 46 | def get_tracks(self): 47 | """ 48 | Returns a list of :class:`clay.gp.Track` instances. 49 | """ 50 | return self.playlist.tracks 51 | 52 | 53 | class MyPlaylistListBox(urwid.ListBox): 54 | """ 55 | List of playlists. 56 | """ 57 | signals = ['activate'] 58 | 59 | def __init__(self, app): 60 | self.app = app 61 | 62 | self.walker = urwid.SimpleListWalker([ 63 | urwid.Text('Not ready') 64 | ]) 65 | self.notification = None 66 | 67 | gp.auth_state_changed += self.auth_state_changed 68 | 69 | super(MyPlaylistListBox, self).__init__(self.walker) 70 | 71 | def auth_state_changed(self, is_auth): 72 | """ 73 | Called when auth state changes (e. g. user is logged in). 74 | Requests fetching of playlists. 75 | """ 76 | if is_auth: 77 | self.walker[:] = [ 78 | urwid.Text(u'\n \uf01e Loading playlists...', align='center') 79 | ] 80 | 81 | gp.get_all_user_playlist_contents_async(callback=self.on_get_playlists) 82 | 83 | def on_get_playlists(self, playlists, error): 84 | """ 85 | Called when a list of playlists fetch completes. 86 | Populates list of playlists. 87 | """ 88 | if error: 89 | notification_area.notify('Failed to get playlists: {}'.format(str(error))) 90 | 91 | items = [] 92 | for playlist in playlists: 93 | myplaylistlistitem = MyPlaylistListItem(playlist) 94 | urwid.connect_signal( 95 | myplaylistlistitem, 'activate', self.item_activated 96 | ) 97 | items.append(myplaylistlistitem) 98 | 99 | self.walker[:] = items 100 | 101 | self.app.redraw() 102 | 103 | def item_activated(self, myplaylistlistitem): 104 | """ 105 | Called when a specific playlist is selected. 106 | Re-emits this event. 107 | """ 108 | urwid.emit_signal(self, 'activate', myplaylistlistitem) 109 | 110 | 111 | class MyPlaylistsPage(urwid.Columns, AbstractPage): 112 | """ 113 | Playlists page. 114 | 115 | Contains two parts: 116 | 117 | - List of playlists (:class:`.MyPlaylistListBox`) 118 | - List of songs in selected playlist (:class:`clay:songlist:SongListBox`) 119 | """ 120 | @property 121 | def name(self): 122 | return 'Playlists' 123 | 124 | @property 125 | def key(self): 126 | return 2 127 | 128 | @property 129 | def slug(self): 130 | """ 131 | Return page ID (str). 132 | """ 133 | return "playlists" 134 | 135 | def __init__(self, app): 136 | self.app = app 137 | 138 | self.myplaylistlist = MyPlaylistListBox(app) 139 | self.songlist = SongListBox(app) 140 | self.songlist.set_placeholder('\n Select a playlist.') 141 | 142 | urwid.connect_signal( 143 | self.myplaylistlist, 'activate', self.myplaylistlistitem_activated 144 | ) 145 | 146 | super(MyPlaylistsPage, self).__init__([ 147 | self.myplaylistlist, 148 | self.songlist 149 | ]) 150 | 151 | def myplaylistlistitem_activated(self, myplaylistlistitem): 152 | """ 153 | Called when specific playlist is selected. 154 | Populates songlist with tracks from the selected playlist. 155 | """ 156 | self.songlist.populate( 157 | myplaylistlistitem.get_tracks() 158 | ) 159 | 160 | def activate(self): 161 | pass 162 | -------------------------------------------------------------------------------- /clay/pages/mystations.py: -------------------------------------------------------------------------------- 1 | """ 2 | Components for "My stations" page. 3 | """ 4 | import urwid 5 | 6 | from clay.gp import gp 7 | from clay.songlist import SongListBox 8 | from clay.notifications import notification_area 9 | from clay.pages.page import AbstractPage 10 | from clay.hotkeys import hotkey_manager 11 | 12 | 13 | class MyStationListItem(urwid.Columns): 14 | """ 15 | One station in the list of stations. 16 | """ 17 | signals = ['activate'] 18 | 19 | def __init__(self, station): 20 | self.station = station 21 | self.text = urwid.SelectableIcon(u' \u2708 {} '.format( 22 | self.station.name 23 | ), cursor_position=3) 24 | self.text.set_layout('left', 'clip', None) 25 | self.content = urwid.AttrWrap( 26 | self.text, 27 | 'default', 28 | 'selected' 29 | ) 30 | super(MyStationListItem, self).__init__([self.content]) 31 | 32 | def keypress(self, size, key): 33 | """ 34 | Handle keypress. 35 | """ 36 | return hotkey_manager.keypress("station_page", self, super(MyStationListItem, self), 37 | size, key) 38 | 39 | def start_station(self): 40 | """ 41 | Start playing the selected station 42 | """ 43 | urwid.emit_signal(self, 'activate', self) 44 | 45 | 46 | class MyStationListBox(urwid.ListBox): 47 | """ 48 | List of stations. 49 | """ 50 | signals = ['activate'] 51 | 52 | def __init__(self, app): 53 | self.app = app 54 | 55 | self.walker = urwid.SimpleListWalker([ 56 | urwid.Text('Not ready') 57 | ]) 58 | self.notification = None 59 | 60 | gp.auth_state_changed += self.auth_state_changed 61 | 62 | super(MyStationListBox, self).__init__(self.walker) 63 | 64 | def auth_state_changed(self, is_auth): 65 | """ 66 | Called when auth state changes (e. g. user is logged in). 67 | Requests fetching of station. 68 | """ 69 | if is_auth: 70 | self.walker[:] = [ 71 | urwid.Text(u'\n \uf01e Loading stations...', align='center') 72 | ] 73 | 74 | gp.get_all_user_station_contents_async(callback=self.on_get_stations) 75 | 76 | def on_get_stations(self, stations, error): 77 | """ 78 | Called when a list of stations fetch completes. 79 | Populates list of stations. 80 | """ 81 | if error: 82 | notification_area.notify('Failed to get stations: {}'.format(str(error))) 83 | 84 | items = [] 85 | for station in stations: 86 | mystationlistitem = MyStationListItem(station) 87 | urwid.connect_signal( 88 | mystationlistitem, 'activate', self.item_activated 89 | ) 90 | items.append(mystationlistitem) 91 | 92 | self.walker[:] = items 93 | 94 | self.app.redraw() 95 | 96 | def item_activated(self, mystationlistitem): 97 | """ 98 | Called when a specific station is selected. 99 | Re-emits this event. 100 | """ 101 | urwid.emit_signal(self, 'activate', mystationlistitem) 102 | 103 | 104 | class MyStationsPage(urwid.Columns, AbstractPage): 105 | """ 106 | Stations page. 107 | 108 | Contains two parts: 109 | 110 | - List of stations (:class:`.MyStationBox`) 111 | - List of songs in selected station (:class:`clay:songlist:SongListBox`) 112 | """ 113 | @property 114 | def name(self): 115 | return 'Stations' 116 | 117 | @property 118 | def key(self): 119 | return 3 120 | 121 | @property 122 | def slug(self): 123 | """ 124 | Return page ID (str). 125 | """ 126 | return "stations" 127 | 128 | def __init__(self, app): 129 | self.app = app 130 | 131 | self.stationlist = MyStationListBox(app) 132 | self.songlist = SongListBox(app) 133 | self.songlist.set_placeholder('\n Select a station.') 134 | 135 | urwid.connect_signal( 136 | self.stationlist, 'activate', self.mystationlistitem_activated 137 | ) 138 | 139 | super(MyStationsPage, self).__init__([ 140 | self.stationlist, 141 | self.songlist 142 | ]) 143 | 144 | def mystationlistitem_activated(self, mystationlistitem): 145 | """ 146 | Called when specific station is selected. 147 | Requests fetching of station tracks 148 | """ 149 | self.songlist.set_placeholder(u'\n \uf01e Loading station tracks...') 150 | mystationlistitem.station.load_tracks_async(callback=self.on_station_loaded) 151 | 152 | def on_station_loaded(self, station, error): 153 | """ 154 | Called when station tracks fetch completes. 155 | Populates songlist with tracks from the selected station. 156 | """ 157 | if error: 158 | notification_area.notify('Failed to get station tracks: {}'.format(str(error))) 159 | 160 | self.songlist.populate( 161 | station.get_tracks() 162 | ) 163 | self.app.redraw() 164 | 165 | def activate(self): 166 | pass 167 | -------------------------------------------------------------------------------- /clay/hotkeys.py: -------------------------------------------------------------------------------- 1 | """ 2 | Hotkeys management. 3 | Requires "gi" package and "Gtk" & "Keybinder" modules. 4 | """ 5 | # pylint: disable=broad-except 6 | import threading 7 | 8 | from clay.settings import settings 9 | from clay.eventhook import EventHook 10 | from clay.notifications import notification_area 11 | from clay.log import logger 12 | 13 | 14 | IS_INIT = False 15 | 16 | 17 | def report_error(exc): 18 | "Print an error message to the debug screen" 19 | logger.error("{0}: {1}".format(exc.__class__.__name__, exc)) 20 | 21 | 22 | try: 23 | # pylint: disable=import-error 24 | import gi 25 | gi.require_version('Keybinder', '3.0') # noqa 26 | gi.require_version('Gtk', '3.0') # noqa 27 | from gi.repository import Keybinder, Gtk 28 | # pylint: enable=import-error 29 | except ImportError as error: 30 | report_error(error) 31 | ERROR_MESSAGE = "Couldn't import PyGObject" 32 | except ValueError as error: 33 | report_error(error) 34 | ERROR_MESSAGE = "Couldn't find the Keybinder and/or Gtk modules" 35 | except Exception as error: 36 | report_error(error) 37 | ERROR_MESSAGE = "There was unknown error: '{}'".format(error) 38 | else: 39 | IS_INIT = True 40 | 41 | 42 | class _HotkeyManager(object): 43 | """ 44 | Manages configs. 45 | Runs Gtk main loop in a thread. 46 | """ 47 | def __init__(self): 48 | self._x_hotkeys = {} 49 | self._hotkeys = self._parse_hotkeys() 50 | self.config = None 51 | 52 | self.play_pause = EventHook() 53 | self.next = EventHook() 54 | self.prev = EventHook() 55 | 56 | if IS_INIT: 57 | Keybinder.init() 58 | self.initialize() 59 | threading.Thread(target=Gtk.main).start() 60 | else: 61 | logger.debug("Not loading the global shortcuts.") 62 | notification_area.notify( 63 | ERROR_MESSAGE + 64 | ", this means the global shortcuts will not work.\n" + 65 | "You can check the log for more details." 66 | ) 67 | 68 | @staticmethod 69 | def _to_gtk_modifier(key): 70 | """ 71 | Translates the modifies to the way that GTK likes them. 72 | """ 73 | key = key.strip() 74 | 75 | if key == "meta": 76 | key = "" 77 | elif key in ("ctrl", "alt", "shift"): 78 | key = "<" + key + ">" 79 | else: 80 | key = key 81 | 82 | return key 83 | 84 | def _parse_x_hotkeys(self): 85 | """ 86 | Reads out them configuration file and parses them into hotkeys readable by GTK. 87 | """ 88 | hotkey_default_config = settings.get_default_config_section('hotkeys', 'x_hotkeys') 89 | mod_key = settings.get('mod_key', 'hotkeys') 90 | hotkeys = {} 91 | 92 | for action in hotkey_default_config: 93 | key_seq = settings.get(action, 'hotkeys', 'x_hotkeys') 94 | 95 | for key in key_seq.split(', '): 96 | hotkey = key.split(' + ') 97 | 98 | if hotkey[0].strip() == 'mod': 99 | hotkey[0] = mod_key 100 | 101 | hotkey = [self._to_gtk_modifier(key) for key in hotkey] 102 | 103 | hotkeys[action] = ''.join(hotkey) 104 | 105 | return hotkeys 106 | 107 | def _parse_hotkeys(self): 108 | """ 109 | Reads out the configuration file and parse them into a hotkeys for urwid. 110 | """ 111 | hotkey_config = settings.get_default_config_section('hotkeys', 'clay_hotkeys') 112 | mod_key = settings.get('mod_key', 'hotkeys') 113 | hotkeys = {} 114 | 115 | for hotkey_name, hotkey_dict in hotkey_config.items(): 116 | hotkeys[hotkey_name] = {} 117 | for action in hotkey_dict.keys(): 118 | key_seq = settings.get(action, 'hotkeys', 'clay_hotkeys', hotkey_name) 119 | 120 | for key in key_seq.split(', '): 121 | hotkey = key.split(' + ') 122 | 123 | if hotkey[0].strip() == 'mod': 124 | hotkey[0] = mod_key 125 | 126 | hotkeys[hotkey_name][' '.join(hotkey)] = action 127 | 128 | return hotkeys 129 | 130 | def keypress(self, name, caller, super_, size, key): 131 | """ 132 | Process the pressed key by looking it up in the configuration file 133 | 134 | """ 135 | method_name = self._hotkeys[name].get(key) 136 | 137 | if method_name: 138 | ret = getattr(caller, method_name)() 139 | elif super_ is not None: 140 | ret = super_.keypress(size, key) 141 | else: 142 | ret = key 143 | 144 | return ret 145 | 146 | def initialize(self): 147 | """ 148 | Unbind previous hotkeys, re-read config & bind new hotkeys. 149 | """ 150 | for operation, key in self._x_hotkeys.items(): 151 | Keybinder.unbind(key) 152 | 153 | self._x_hotkeys = self._parse_x_hotkeys() 154 | 155 | for operation, key in self._x_hotkeys.items(): 156 | Keybinder.bind(key, self.fire_hook, operation) 157 | 158 | def fire_hook(self, key, operation): 159 | """ 160 | Fire hook by name. 161 | """ 162 | assert key 163 | getattr(self, operation).fire() 164 | 165 | 166 | hotkey_manager = _HotkeyManager() # pylint: disable=invalid-name 167 | -------------------------------------------------------------------------------- /clay/playbar.py: -------------------------------------------------------------------------------- 1 | """ 2 | PlayBar widget. 3 | """ 4 | # pylint: disable=too-many-instance-attributes 5 | import urwid 6 | 7 | from clay.player import player 8 | from clay.settings import settings 9 | from clay import meta 10 | 11 | 12 | class ProgressBar(urwid.Widget): 13 | """ 14 | Thin progress bar. 15 | """ 16 | _sizing = frozenset([urwid.FLOW]) 17 | 18 | # CHARS = u'\u2580' 19 | # CHARS = u'\u2581' 20 | CHARS = u'\u2501' 21 | 22 | def __init__(self): 23 | self.value = 0 24 | self.done_style = 'progressbar_done' 25 | super(ProgressBar, self).__init__() 26 | 27 | def render(self, size, focus=False): 28 | """ 29 | Render canvas. 30 | """ 31 | (width,) = size 32 | text = urwid.Text('foo', urwid.LEFT, urwid.CLIP) 33 | 34 | frac = width * self.value 35 | whole = int(frac) 36 | 37 | text.set_text([ 38 | ( 39 | self.done_style, 40 | whole * ProgressBar.CHARS[-1] 41 | # + ProgressBar.CHARS[partial] 42 | ), 43 | ( 44 | 'progressbar_remaining', 45 | (width - whole) * ProgressBar.CHARS[-1] 46 | ) 47 | ]) 48 | return text.render(size, focus) 49 | 50 | @staticmethod 51 | def rows(*_): 52 | """ 53 | Return number of rows required for rendering. 54 | """ 55 | return 1 56 | 57 | def set_progress(self, value): 58 | """ 59 | Set progress value in range [0..1]. 60 | """ 61 | self.value = value 62 | self._invalidate() 63 | 64 | def set_done_style(self, done_style): 65 | """ 66 | Set style for "done" part. 67 | """ 68 | self.done_style = done_style 69 | 70 | 71 | class PlayBar(urwid.Pile): 72 | """ 73 | A widget that shows currently played track, playback progress and flags. 74 | """ 75 | _unicode = settings.get('unicode', 'clay_settings') 76 | ROTATING = u'|' u'/' u'\u2014' u'\\' 77 | RATING_ICONS = {0: ' ', 78 | 1: u'\U0001F593' if _unicode else '-', 79 | 4: u'\U0001F592' if _unicode else '+', 80 | 5: u'\U0001F592' if _unicode else '+'} 81 | 82 | def __init__(self, app): 83 | # super(PlayBar, self).__init__(*args, **kwargs) 84 | self.app = app 85 | self.rotating_index = 0 86 | self.text = urwid.Text('', align=urwid.LEFT) 87 | self.flags = [ 88 | ] 89 | self.progressbar = ProgressBar() 90 | 91 | self.shuffle_el = urwid.AttrWrap(urwid.Text(u' \u22cd SHUF '), 'flag') 92 | self.repeat_el = urwid.AttrWrap(urwid.Text(u' \u27f2 REP '), 'flag') 93 | 94 | self.infobar = urwid.Columns([ 95 | self.text, 96 | ('pack', self.shuffle_el), 97 | # ('pack', urwid.Text(' ')), 98 | ('pack', self.repeat_el) 99 | ]) 100 | super(PlayBar, self).__init__([ 101 | ('pack', self.progressbar), 102 | ('pack', self.infobar), 103 | ]) 104 | self.update() 105 | 106 | player.media_position_changed += self.update 107 | player.media_state_changed += self.update 108 | player.track_changed += self.update 109 | player.playback_flags_changed += self.update 110 | 111 | def get_rotating_bar(self): 112 | """ 113 | Return a spinner char for current rotating_index. 114 | """ 115 | return PlayBar.ROTATING[self.rotating_index % len(PlayBar.ROTATING)] 116 | 117 | @staticmethod 118 | def get_style(): 119 | """ 120 | Return the style for current playback state. 121 | """ 122 | if player.is_loading or player.is_playing: 123 | return 'title-playing' 124 | return 'title-idle' 125 | 126 | def get_text(self): 127 | """ 128 | Return text for display in this bar. 129 | """ 130 | track = player.get_current_track() 131 | if track is None: 132 | return u'{} {}'.format( 133 | meta.APP_NAME, 134 | meta.VERSION_WITH_CODENAME 135 | ) 136 | progress = player.get_play_progress_seconds() 137 | total = player.get_length_seconds() 138 | return (self.get_style(), u' {} {} - {} {} [{:02d}:{:02d} / {:02d}:{:02d}]'.format( 139 | # u'|>' if player.is_playing else u'||', 140 | # self.get_rotating_bar(), 141 | u'\u2505' if player.is_loading 142 | else u'\u25B6' if player.is_playing 143 | else u'\u25A0', 144 | track.artist, 145 | track.title, 146 | self.RATING_ICONS[track.rating], 147 | progress // 60, 148 | progress % 60, 149 | total // 60, 150 | total % 60, 151 | )) 152 | 153 | def update(self, *_): 154 | """ 155 | Force update of this widget. 156 | Called when something unrelated to completion value changes, 157 | e.g. current track or playback flags. 158 | """ 159 | self.text.set_text(self.get_text()) 160 | self.progressbar.set_progress(player.get_play_progress()) 161 | self.progressbar.set_done_style( 162 | 'progressbar_done' 163 | if player.is_playing 164 | else 'progressbar_done_paused' 165 | ) 166 | self.shuffle_el.attr = 'flag-active' \ 167 | if player.get_is_random() \ 168 | else 'flag' 169 | self.repeat_el.attr = 'flag-active' \ 170 | if player.get_is_repeat_one() \ 171 | else 'flag' 172 | self.app.redraw() 173 | 174 | def tick(self): 175 | """ 176 | Increase rotating index & trigger redraw. 177 | """ 178 | self.rotating_index += 1 179 | self.update() 180 | -------------------------------------------------------------------------------- /docs/source/conf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # Clay documentation build configuration file, created by 5 | # sphinx-quickstart on Sat Jan 6 13:35:04 2018. 6 | # 7 | # This file is execfile()d with the current directory set to its 8 | # containing dir. 9 | # 10 | # Note that not all possible configuration values are present in this 11 | # autogenerated file. 12 | # 13 | # All configuration values have a default; values that are commented out 14 | # serve to show the default. 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | # 20 | import os 21 | import sys 22 | sys.path.insert(0, os.path.abspath('../..')) 23 | try: 24 | from unittest.mock import MagicMock 25 | except ImportError: 26 | from mock import Mock as MagicMock 27 | 28 | 29 | # -- General configuration ------------------------------------------------ 30 | 31 | # If your documentation needs a minimal Sphinx version, state it here. 32 | # 33 | # needs_sphinx = '1.0' 34 | 35 | # Add any Sphinx extension module names here, as strings. They can be 36 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 37 | # ones. 38 | extensions = [ 39 | 'sphinx.ext.autodoc', 40 | 'sphinx.ext.todo', 41 | 'sphinx.ext.viewcode' 42 | ] 43 | 44 | # Add any paths that contain templates here, relative to this directory. 45 | templates_path = ['_templates'] 46 | 47 | # The suffix(es) of source filenames. 48 | # You can specify multiple suffix as a list of string: 49 | # 50 | # source_suffix = ['.rst', '.md'] 51 | source_suffix = '.rst' 52 | 53 | # The master toctree document. 54 | master_doc = 'index' 55 | 56 | # General information about the project. 57 | project = 'Clay' 58 | copyright = '2018, Andrew Dunai' 59 | author = 'Andrew Dunai' 60 | 61 | # The version info for the project you're documenting, acts as replacement for 62 | # |version| and |release|, also used in various other places throughout the 63 | # built documents. 64 | # 65 | # The short X.Y version. 66 | version = '1.0a1' 67 | # The full version, including alpha/beta/rc tags. 68 | release = '1.0a1' 69 | 70 | # The language for content autogenerated by Sphinx. Refer to documentation 71 | # for a list of supported languages. 72 | # 73 | # This is also used if you do content translation via gettext catalogs. 74 | # Usually you set "language" from the command line for these cases. 75 | language = None 76 | 77 | # List of patterns, relative to source directory, that match files and 78 | # directories to ignore when looking for source files. 79 | # This patterns also effect to html_static_path and html_extra_path 80 | exclude_patterns = [] 81 | 82 | # The name of the Pygments (syntax highlighting) style to use. 83 | pygments_style = 'sphinx' 84 | 85 | # If true, `todo` and `todoList` produce output, else they produce nothing. 86 | todo_include_todos = True 87 | 88 | 89 | # -- Options for HTML output ---------------------------------------------- 90 | 91 | # The theme to use for HTML and HTML Help pages. See the documentation for 92 | # a list of builtin themes. 93 | # 94 | html_theme = 'sphinx_rtd_theme' 95 | 96 | # Theme options are theme-specific and customize the look and feel of a theme 97 | # further. For a list of options available for each theme, see the 98 | # documentation. 99 | # 100 | # html_theme_options = {} 101 | 102 | # Add any paths that contain custom static files (such as style sheets) here, 103 | # relative to this directory. They are copied after the builtin static files, 104 | # so a file named "default.css" will overwrite the builtin "default.css". 105 | html_static_path = ['_static'] 106 | 107 | # Custom sidebar templates, must be a dictionary that maps document names 108 | # to template names. 109 | # 110 | # This is required for the alabaster theme 111 | # refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars 112 | html_sidebars = { 113 | '**': [ 114 | 'relations.html', # needs 'show_related': True theme option to display 115 | 'searchbox.html', 116 | ] 117 | } 118 | 119 | 120 | # -- Options for HTMLHelp output ------------------------------------------ 121 | 122 | # Output file base name for HTML help builder. 123 | htmlhelp_basename = 'Claydoc' 124 | 125 | 126 | # -- Options for LaTeX output --------------------------------------------- 127 | 128 | latex_elements = { 129 | # The paper size ('letterpaper' or 'a4paper'). 130 | # 131 | # 'papersize': 'letterpaper', 132 | 133 | # The font size ('10pt', '11pt' or '12pt'). 134 | # 135 | # 'pointsize': '10pt', 136 | 137 | # Additional stuff for the LaTeX preamble. 138 | # 139 | # 'preamble': '', 140 | 141 | # Latex figure (float) alignment 142 | # 143 | # 'figure_align': 'htbp', 144 | } 145 | 146 | # Grouping the document tree into LaTeX files. List of tuples 147 | # (source start file, target name, title, 148 | # author, documentclass [howto, manual, or own class]). 149 | latex_documents = [ 150 | (master_doc, 'Clay.tex', 'Clay Documentation', 151 | 'Andrew Dunai', 'manual'), 152 | ] 153 | 154 | 155 | # -- Options for manual page output --------------------------------------- 156 | 157 | # One entry per manual page. List of tuples 158 | # (source start file, name, description, authors, manual section). 159 | man_pages = [ 160 | (master_doc, 'clay', 'Clay Documentation', 161 | [author], 1) 162 | ] 163 | 164 | 165 | # -- Options for Texinfo output ------------------------------------------- 166 | 167 | # Grouping the document tree into Texinfo files. List of tuples 168 | # (source start file, target name, title, author, 169 | # dir menu entry, description, category) 170 | texinfo_documents = [ 171 | (master_doc, 'Clay', 'Clay Documentation', 172 | author, 'Clay', 'One line description of project.', 173 | 'Miscellaneous'), 174 | ] 175 | 176 | 177 | class Mock(MagicMock): 178 | @classmethod 179 | def __getattr__(cls, name): 180 | return MagicMock() 181 | 182 | # MOCK_MODULES = ['gi', 'gi.repository', 'urwid'] 183 | # sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES) 184 | 185 | -------------------------------------------------------------------------------- /clay/pages/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Components for "Settings" page. 3 | """ 4 | import urwid 5 | 6 | from clay.pages.page import AbstractPage 7 | from clay.settings import settings 8 | from clay.player import player 9 | from clay.hotkeys import hotkey_manager 10 | 11 | 12 | class Slider(urwid.Widget): 13 | """ 14 | Represents a (TODO: vertical) slider for equalizer band modification. 15 | TODO: Save equalizer settings in config file. 16 | """ 17 | _sizing = frozenset([urwid.FLOW]) 18 | 19 | CHARS = [ 20 | u'\u2584', 21 | u'\u25A0', 22 | u'\u2580', 23 | ] 24 | ZERO_CHAR = u'\u2500' 25 | 26 | def selectable(self): 27 | return True 28 | 29 | def __init__(self, index, freq): 30 | self.index = index 31 | if int(freq) == freq: 32 | freq = int(freq) 33 | self.freq = freq 34 | if freq >= 1000: 35 | self.freq_str = str(freq // 1000) + '\nKHz' 36 | else: 37 | self.freq_str = str(freq) + '\nHz' 38 | self.value = 0 39 | self.slider_height = 13 40 | self.max_value = 20 41 | super(Slider, self).__init__() 42 | 43 | def rows(self, *_): 44 | """ 45 | Return count of rows required to render this widget. 46 | """ 47 | return self.slider_height + 3 48 | 49 | def render(self, size, focus=None): 50 | """ 51 | Render widget. 52 | """ 53 | rows = [('+' if self.value > 0 else '') + str(self.value) + ' dB'] 54 | 55 | chars = [' '] * self.slider_height 56 | 57 | if self.value == 0: 58 | chars[self.slider_height // 2] = Slider.ZERO_CHAR 59 | else: 60 | k = ((float(self.value) / (self.max_value + 1)) + 1) / 2 # Convert value to [0;1] range 61 | section_index = int(k * self.slider_height) 62 | char_index = int(k * self.slider_height * len(Slider.CHARS)) % len(Slider.CHARS) 63 | chars[section_index] = Slider.CHARS[char_index] 64 | 65 | rows.extend([ 66 | ( 67 | u'\u2524{}\u251C' 68 | if i == self.slider_height // 2 69 | else u'\u2502{}\u2502' 70 | ).format(x) 71 | for i, x 72 | in enumerate(reversed(chars)) 73 | ]) 74 | rows.append(self.freq_str) 75 | text = urwid.AttrMap(urwid.Text('\n'.join( 76 | rows 77 | ), align=urwid.CENTER), 'default', 'panel_focus') 78 | return text.render(size, focus) 79 | 80 | def keypress(self, _, key): 81 | """ 82 | Handle equalizer band modification. 83 | """ 84 | return hotkey_manager.keypress("settings_page", self, None, None, key) 85 | 86 | def equalizer_up(self): 87 | """ 88 | Turn the equalizer band up 89 | """ 90 | if self.value < self.max_value: 91 | self.value += 1 92 | self.update() 93 | 94 | def equalizer_down(self): 95 | """ 96 | Turn the equalizer band down 97 | """ 98 | if self.value > -self.max_value: 99 | self.value -= 1 100 | self.update() 101 | 102 | def update(self): 103 | """ 104 | Update player equalizer & toggle redraw. 105 | """ 106 | player.set_equalizer_value(self.index, self.value) 107 | self._invalidate() 108 | 109 | 110 | class Equalizer(urwid.Columns): 111 | """ 112 | Represents an equalizer. 113 | """ 114 | def __init__(self): 115 | self.bands = [ 116 | Slider(index, freq) 117 | for index, freq 118 | in enumerate(player.get_equalizer_freqs()) 119 | ] 120 | super(Equalizer, self).__init__( 121 | self.bands 122 | ) 123 | 124 | 125 | class SettingsPage(urwid.Columns, AbstractPage): 126 | """ 127 | Settings page. 128 | """ 129 | @property 130 | def name(self): 131 | return 'Settings' 132 | 133 | @property 134 | def key(self): 135 | return 9 136 | 137 | @property 138 | def slug(self): 139 | """ 140 | Return page ID (str). 141 | """ 142 | return "settings" 143 | 144 | def __init__(self, app): 145 | self.app = app 146 | self.username = urwid.Edit( 147 | edit_text=settings.get('username', 'play_settings') or '' 148 | ) 149 | self.password = urwid.Edit( 150 | mask='*', edit_text=settings.get('password', 'play_settings') or '' 151 | ) 152 | self.device_id = urwid.Edit( 153 | edit_text=settings.get('device_id', 'play_settings') or '' 154 | ) 155 | self.download_tracks = urwid.CheckBox( 156 | 'Download tracks before playback', 157 | state=settings.get('download_tracks', 'play_settings') or False 158 | ) 159 | self.equalizer = Equalizer() 160 | super(SettingsPage, self).__init__([urwid.ListBox(urwid.SimpleListWalker([ 161 | urwid.Text('Settings'), 162 | urwid.Divider(' '), 163 | urwid.Text('Username'), 164 | urwid.AttrWrap(self.username, 'input', 'input_focus'), 165 | urwid.Divider(' '), 166 | urwid.Text('Password'), 167 | urwid.AttrWrap(self.password, 'input', 'input_focus'), 168 | urwid.Divider(' '), 169 | urwid.Text('Device ID'), 170 | urwid.AttrWrap(self.device_id, 'input', 'input_focus'), 171 | urwid.Divider(' '), 172 | self.download_tracks, 173 | urwid.Divider(' '), 174 | urwid.AttrWrap(urwid.Button( 175 | 'Save', on_press=self.on_save 176 | ), 'input', 'input_focus'), 177 | urwid.Divider(u'\u2500'), 178 | self.equalizer, 179 | ]))]) 180 | 181 | def on_save(self, *_): 182 | """ 183 | Called when "Save" button is pressed. 184 | """ 185 | with settings.edit() as config: 186 | if 'play_settings' not in config: 187 | config['play_settings'] = {} 188 | config['play_settings']['username'] = self.username.edit_text 189 | config['play_settings']['password'] = self.password.edit_text 190 | config['play_settings']['device_id'] = self.device_id.edit_text 191 | config['play_settings']['download_tracks'] = self.download_tracks.state 192 | 193 | self.app.set_page('MyLibraryPage') 194 | self.app.log_in() 195 | 196 | def activate(self): 197 | pass 198 | -------------------------------------------------------------------------------- /clay/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Application settings manager. 3 | """ 4 | from threading import Lock 5 | import os 6 | import copy 7 | import errno 8 | import yaml 9 | import appdirs 10 | import pkg_resources 11 | 12 | 13 | class _SettingsEditor(dict): 14 | """ 15 | Thread-safe settings editor context manager. 16 | 17 | For example see :py:meth:`~._Settings.edit`. 18 | """ 19 | _lock = Lock() 20 | 21 | def __init__(self, original_config, commit_callback): 22 | super(_SettingsEditor, self).__init__() 23 | _SettingsEditor._lock.acquire() 24 | self._commit_callback = commit_callback 25 | self.update(copy.deepcopy(original_config)) 26 | 27 | def __enter__(self): 28 | return self 29 | 30 | def __exit__(self, exc_type, exc_value, exc_tb): 31 | _SettingsEditor._lock.release() 32 | if exc_tb is None: 33 | self._commit_callback(self) 34 | else: 35 | # TODO: Handle this 36 | pass 37 | 38 | 39 | class _Settings(object): 40 | """ 41 | Settings management class. 42 | """ 43 | def __init__(self): 44 | self._config = {} 45 | self._default_config = {} 46 | self._cached_files = set() 47 | 48 | self._config_dir = None 49 | self._config_file_path = None 50 | self._cache_dir = None 51 | 52 | self._ensure_directories() 53 | self._load_config() 54 | self._load_cache() 55 | 56 | def _ensure_directories(self): 57 | """ 58 | Create config dir, config file & cache dir if they do not exist yet. 59 | """ 60 | self._config_dir = appdirs.user_config_dir('clay', 'Clay') 61 | self._config_file_path = os.path.join(self._config_dir, 'config.yaml') 62 | self._colours_file_path = os.path.join(self._config_dir, 'colours.yaml') 63 | 64 | try: 65 | os.makedirs(self._config_dir) 66 | except OSError as error: 67 | if error.errno != errno.EEXIST: 68 | raise 69 | 70 | self._cache_dir = appdirs.user_cache_dir('clay', 'Clay') 71 | try: 72 | os.makedirs(self._cache_dir) 73 | except OSError as error: 74 | if error.errno != errno.EEXIST: 75 | raise 76 | 77 | if not os.path.exists(self._config_file_path): 78 | with open(self._config_file_path, 'w') as settings_file: 79 | settings_file.write('{}') 80 | 81 | def _load_config(self): 82 | """ 83 | Read config from file. 84 | """ 85 | with open(self._config_file_path, 'r') as settings_file: 86 | self._config = yaml.load(settings_file.read()) 87 | 88 | # Load the configuration from Setuptools' ResourceManager API 89 | self._default_config = yaml.load(pkg_resources.resource_string(__name__, "config.yaml")) 90 | 91 | # We only either the user colour or the default colours to ease parsing logic. 92 | if os.path.exists(self._colours_file_path): 93 | with open(self._colours_file_path, 'r') as colours_file: 94 | self.colours_config = yaml.load(colours_file.read()) 95 | else: 96 | self.colours_config = yaml.load(pkg_resources.resource_string(__name__, "colours.yaml")) 97 | 98 | 99 | def _load_cache(self): 100 | """ 101 | Load cached files. 102 | """ 103 | self._cached_files = set(os.listdir(self._cache_dir)) 104 | 105 | def _commit_edits(self, config): 106 | """ 107 | Write config to file. 108 | 109 | This method is supposed to be called only 110 | from :py:meth:`~._SettingsEditor.__exit__`. 111 | """ 112 | self._config.update(config) 113 | with open(self._config_file_path, 'w') as settings_file: 114 | settings_file.write(yaml.dump(self._config, default_flow_style=False)) 115 | 116 | def get(self, key, *sections): 117 | """ 118 | Return their configuration key in a specified section 119 | By default it looks in play_settings. 120 | """ 121 | section = self.get_section(*sections) 122 | 123 | try: 124 | return section.get(key) 125 | except (KeyError, TypeError): 126 | section = self.get_default_config_section(*sections) 127 | return section.get(key) 128 | 129 | def _get_section(self, config, *sections): 130 | config = config.copy() 131 | 132 | for section in sections: 133 | config = config[section] 134 | 135 | return config 136 | 137 | def get_section(self, *sections): 138 | """ 139 | Get a section from the user configuration file if it can find it, 140 | else load it from the system config 141 | """ 142 | try: 143 | return self._get_section(self._config, *sections) 144 | except (KeyError, TypeError): 145 | return self._get_section(self._default_config, *sections) 146 | 147 | def get_default_config_section(self, *sections): 148 | """ 149 | Always get a section from the default/system configuration. You would use this whenever 150 | you need to loop through all the values in a section. In the user config they might be 151 | incomplete. 152 | """ 153 | return self._get_section(self._default_config, *sections) 154 | 155 | def edit(self): 156 | """ 157 | Return :py:class:`._SettingsEditor` context manager to edit config. 158 | 159 | Settings are saved to file once the returned context manager exists. 160 | 161 | Example usage: 162 | 163 | .. code-block:: python 164 | 165 | from clay.settings import settings 166 | 167 | with settings.edit() as config: 168 | config['foo']['bar'] = 'baz' 169 | """ 170 | return _SettingsEditor(self._config, self._commit_edits) 171 | 172 | def get_cached_file_path(self, filename): 173 | """ 174 | Get full path to cached file. 175 | """ 176 | path = os.path.join(self._cache_dir, filename) 177 | if os.path.exists(path): 178 | return path 179 | return None 180 | 181 | def get_is_file_cached(self, filename): 182 | """ 183 | Return ``True`` if *filename* is present in cache. 184 | """ 185 | return filename in self._cached_files 186 | 187 | def save_file_to_cache(self, filename, content): 188 | """ 189 | Save content into file in cache. 190 | """ 191 | path = os.path.join(self._cache_dir, filename) 192 | with open(path, 'wb') as cachefile: 193 | cachefile.write(content) 194 | self._cached_files.add(filename) 195 | return path 196 | 197 | 198 | settings = _Settings() # pylint: disable=invalid-name 199 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Clay Player](./images/clay-banner.png) 2 | 3 | - [About](#clay-beta) 4 | - [Quick start](#quick-start) 5 | - [Documentation](#documentation) 6 | - [Requirements](#requirements) 7 | - [What works](#what-works) 8 | - [What is being developed](#what-is-being-developed) 9 | - [Installation](#installation) 10 | * [Method 1 (PyPi, automatic)](#method-1-pypi-automatic) 11 | * [Method 2 (from source, manual)](#method-2-from-source-manual) 12 | * [Method 3 (in Docker)](#method-3-in-docker) 13 | - [Configuration](#configuration) 14 | - [Controls](#controls) 15 | * [General](#general) 16 | * [Songs](#songs) 17 | * [Playback](#playback) 18 | * [Equalizer](#equalizer) 19 | * [Misc](#misc) 20 | - [Troubleshooting](#troubleshooting) 21 | - [Credits](#credits) 22 | - [Changelog](./CHANGELOG.rst) 23 | 24 | # Clay [beta] 25 | 26 | [![Build Status](https://travis-ci.org/and3rson/clay.svg?branch=master)](https://travis-ci.org/and3rson/clay) [![Documentation Status](https://readthedocs.org/projects/clay/badge/?version=latest)](http://clay.readthedocs.io/en/latest/?badge=latest) [![PyPI version](https://badge.fury.io/py/clay-player.svg)](https://badge.fury.io/py/clay-player) [![Maintainability](https://api.codeclimate.com/v1/badges/33fc2ac7949ddd9a51ee/maintainability?1)](https://codeclimate.com/github/and3rson/clay/maintainability) 27 | 28 | Standalone command line player for Google Play Music. 29 | 30 | This app wouldn't be possible without the wonderful [gmusicapi] and [VLC] libraries. 31 | 32 | This project is neither affiliated nor endorsed by Google. 33 | 34 | It's being actively developed, but is still in the early beta stage, so many features are missing and/or may be bugged. 35 | 36 | We're on IRC! 37 | 38 | - Server: irc.oftc.net 39 | - Channel: **#clay** 40 | 41 | Screenshot: 42 | 43 | ![Clay Player screenshot](./images/clay-screenshot.png) 44 | 45 | Click the image below to see the screencast: 46 | 47 | [![asciicast](https://asciinema.org/a/69ygwYGRDyB5a7pFgyrwWo1ea.png?1)](https://asciinema.org/a/69ygwYGRDyB5a7pFgyrwWo1ea) 48 | 49 | # Quick start 50 | 51 | ```bash 52 | sudo apt install python-gi python-gi-cairo python3-gi python3-gi-cairo vlc keybinder python-keybinder 53 | pip install --user clay-player 54 | clay 55 | ``` 56 | 57 | # Documentation 58 | 59 | Documentation is [available here](http://clay.readthedocs.io/en/latest/). 60 | 61 | # Requirements 62 | 63 | - Python 3.x (native) 64 | - [gmusicapi] (PYPI) 65 | - [urwid] (PYPI) 66 | - [PyYAML] (PYPI) 67 | - lib[VLC] (native, distributed with VLC player) 68 | - [PyGObject] (optional) (native, used for global X keybinds) 69 | - [Keybinder] (optional) (native, used for global X keybinds) 70 | - [setproctitle] (optional) PYPI, used to change clay process name from 'python' to 'clay') 71 | - python-dbus (optional) 72 | 73 | # What works 74 | - Audio equalizer 75 | - Caching (not for song data, that one is coming soon) 76 | - Configurable keybinds and colours 77 | - Configuration UI 78 | - Filtering results 79 | - Global hotkeys 80 | - Like/dislike tracks 81 | - Liked songs playlist 82 | - Music library browsing & management 83 | - Notifications - in-app & OSD (via DBus) 84 | - PYPI package 85 | - Playback 86 | - Playlists 87 | - Queue management 88 | - Radio stations 89 | - Song file caching 90 | - Song operations (add to library, start station etc.) 91 | - Song search 92 | - Token caching for faster authorizations 93 | 94 | # What is being developed 95 | - Artist/album display 96 | - Artist/album search 97 | - Other functionality that is supported by [gmusicapi] 98 | - Playlist editing 99 | 100 | # Installation 101 | 102 | **Warning:** The AUR and PyPy packages called `python3-keybinder` will 103 | not work with Clay since you need to use the official bindings. Since 104 | Ubuntu seperated the official bindings into a different package but 105 | with the same name as the unofficial one it can cause some 106 | confusion. So if you get a `Namespace Keybinder not available` warning 107 | it is probably caused by this. So, for example, on Arch Linux you need 108 | the `libkeybinder3` package instead. 109 | 110 | 1. Install Python 3, and VLC from your package manager. 111 | 2. Optionally, you can install PyGObject, DBus for Python and keybinder plus bindings 112 | if you want global X keybinds. 113 | 114 | ## Method 1 (PyPi, automatic) 115 | 116 | Just install the player using `pip`: 117 | 118 | ```bash 119 | pip install --user clay-player 120 | clay 121 | ``` 122 | 123 | ## Method 2 (from source, manual) 124 | 125 | 1. Clone the source code. 126 | 127 | 2. Create & activate virtualenv with system packages: 128 | 129 | ```bash 130 | virtualenv --system-site-packages --prompt="(clay) " .env 131 | source .env/bin/activate 132 | ``` 133 | 134 | 3. Install the requirements: 135 | 136 | ```bash 137 | pip install -r requirements.txt 138 | ``` 139 | 140 | 4. Run the player: 141 | 142 | ```bash 143 | ./clay/app.py 144 | ``` 145 | 146 | ## Method 3 (in Docker) 147 | 148 | Sometimes you want to run stuff in Docker. You can run Clay in docker as well. 149 | 150 | There are two strict requirements: 151 | 152 | - You need to build the container by yourself (bacause of PulseAudio related paths & magic cookies.) 153 | - You must have PulseAudio running on host with `module-native-protocol-tcp` module enabled. 154 | 155 | Here's how you do it: 156 | 157 | 1. Clone the source code 158 | 159 | 2. Create "~/.config/clay" directory (to have proper volume permissions in docker) 160 | 161 | ```bash 162 | mkdir ~/.config/clay 163 | ``` 164 | 165 | 3. Build & run the image 166 | 167 | ```bash 168 | make run 169 | ``` 170 | 171 | You *should* get the sound working. Also docker will reuse the Clay config file from host (if you have one). 172 | 173 | # Configuration 174 | 175 | - Once you launch the app, use the "Settings" page to enter your login and password. 176 | - You will also need to know your Device ID. Thanks to [gmusicapi], the app should display possible IDs once you enter a wrong one. 177 | - Please be aware that this app has not been tested with 2FA yet. 178 | - For people with 2FA, you can just create an app password in Google accounts page and proceed normally. (Thanks @j605) 179 | 180 | # Controls 181 | 182 | ## General 183 | 184 | - `` - nagivate around 185 | - ` + 0..9` - switch active tab 186 | 187 | ## Songs 188 | 189 | - `` - play highlighted track 190 | - ` w` - play/pause 191 | - ` e` - play next song 192 | - ` a` - append highlighted song to the queue 193 | - ` u` - remove highlighted song from the queue 194 | - ` p` - start station from highlighted song 195 | - ` m` - show context menu for this song 196 | - ` u` - thumb up the highlighted song 197 | - ` d` - thumb down the highlighted song 198 | 199 | ## Playback 200 | 201 | - ` s` - toggle shuffle 202 | - ` r` - toggle song repeat 203 | - ` ` - seek backward/forward by 5% of the song duration 204 | - ` q` - seek to song beginning 205 | 206 | ## Equalizer 207 | - `+` - increase amplification 208 | - `-` - decrease amplification 209 | 210 | ## Misc 211 | 212 | - `` or ` /` or _ - close most recent notification or popup 213 | - ` x` - exit app 214 | - To filter songs just start typing words. Hit `` to cancel. 215 | 216 | ## X keybinds 217 | **NOTE:** you need to pass the `--with-x-keybinds` flag for these to work 218 | - `` - play/pause the song 219 | - `` - play the next song 220 | - `` - play previous song 221 | 222 | # Troubleshooting 223 | 224 | At some point, the app may fail. Possible reasons are app bugs, 225 | Google Play Music API issues, [gmusicapi] bugs, [urwid] bugs etc. 226 | 227 | If you encounter a problem, please feel free to submit an [issue](https://github.com/and3rson/clay/issues). 228 | I'll try to figure it out ASAP. 229 | 230 | Most issues can be reproduced only with specific data coming from Google Play Music servers. 231 | 232 | Use "Debug" tab within app to select the error and hit "Enter" to copy it into clipboard. 233 | This will help me to investigate this issue. 234 | 235 | # Credits 236 | 237 | Made by Andrew Dunai. 238 | 239 | Regards to [gmusicapi] and [VLC] who made this possible. 240 | 241 | People who contribute to this project: 242 | 243 | - [@ValentijnvdBeek (Valentijn)](https://github.com/ValentijnvdBeek) 244 | - [@Fluctuz](https://github.com/Fluctuz) 245 | - [@sjkingo (Sam Kingston)](https://github.com/sjkingo) 246 | 247 | [gmusicapi]: https://github.com/simon-weber/gmusicapi 248 | [VLC]: https://wiki.videolan.org/python_bindings 249 | [urwid]: http://www.urwid.org/ 250 | [pyyaml]: https://github.com/yaml/pyyaml 251 | [PyGObject]: https://pygobject.readthedocs.io/en/latest/getting_started.html 252 | [Keybinder]: https://github.com/kupferlauncher/keybinder 253 | [setproctitle]: https://pypi.org/project/setproctitle/ 254 | -------------------------------------------------------------------------------- /clay/app.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # pylint: disable=wrong-import-position 3 | """ 4 | Main app entrypoint. 5 | """ 6 | 7 | import sys 8 | sys.path.insert(0, '.') # noqa 9 | 10 | 11 | import argparse 12 | import os 13 | import urwid 14 | 15 | from clay import meta 16 | from clay.player import player 17 | from clay.playbar import PlayBar 18 | from clay.pages.debug import DebugPage 19 | from clay.pages.mylibrary import MyLibraryPage 20 | from clay.pages.myplaylists import MyPlaylistsPage 21 | from clay.pages.mystations import MyStationsPage 22 | from clay.pages.playerqueue import QueuePage 23 | from clay.pages.search import SearchPage 24 | from clay.pages.settings import SettingsPage 25 | from clay.settings import settings 26 | from clay.notifications import notification_area 27 | from clay.gp import gp 28 | from clay.hotkeys import hotkey_manager 29 | 30 | 31 | class AppWidget(urwid.Frame): 32 | """ 33 | Root widget. 34 | 35 | Handles tab switches, global keypresses etc. 36 | """ 37 | class Tab(urwid.Text): 38 | """ 39 | Represents a single tab in header tabbar. 40 | """ 41 | def __init__(self, page): 42 | self.page = page 43 | super(AppWidget.Tab, self).__init__( 44 | self.get_title() 45 | ) 46 | self.set_active(False) 47 | 48 | def set_active(self, active): 49 | """ 50 | Mark tab visually as active. 51 | """ 52 | self.set_text( 53 | [ 54 | ('panel_divider_focus' if active else 'panel_divider', u'\u23b8 '), 55 | ('panel_focus' if active else 'panel', self.get_title() + ' ') 56 | ] 57 | ) 58 | 59 | def get_title(self): 60 | """ 61 | Render tab title. 62 | """ 63 | return '{} {}'.format( 64 | self.page.key, 65 | self.page.name 66 | ) 67 | 68 | def __init__(self): 69 | self.pages = [ 70 | DebugPage(self), 71 | MyLibraryPage(self), 72 | MyPlaylistsPage(self), 73 | MyStationsPage(self), 74 | QueuePage(self), 75 | SearchPage(self), 76 | SettingsPage(self) 77 | ] 78 | self.tabs = [AppWidget.Tab(page) for page in self.pages] 79 | self.current_page = None 80 | self.loop = None 81 | 82 | notification_area.set_app(self) 83 | self._login_notification = None 84 | 85 | self._cancel_actions = [] 86 | 87 | self.header = urwid.Pile([ 88 | urwid.AttrWrap(urwid.Columns([ 89 | ('pack', tab) 90 | for tab 91 | in self.tabs 92 | ], dividechars=0), 'panel'), 93 | notification_area 94 | ]) 95 | self.playbar = PlayBar(self) 96 | super(AppWidget, self).__init__( 97 | header=self.header, 98 | footer=self.playbar, 99 | body=urwid.Filler(urwid.Text('Loading...', align='center')) 100 | ) 101 | 102 | self.set_page('library') 103 | self.log_in() 104 | 105 | def log_in(self, use_token=True): 106 | """ 107 | Called when this page is shown. 108 | 109 | Request user authorization. 110 | """ 111 | authtoken, device_id, username, password = [ 112 | settings.get(key, "play_settings") 113 | for key 114 | in ('authtoken', 'device_id', 'username', 'password') 115 | ] 116 | 117 | if self._login_notification: 118 | self._login_notification.close() 119 | if use_token and authtoken: 120 | self._login_notification = notification_area.notify('Using cached auth token...') 121 | gp.use_authtoken_async( 122 | authtoken, 123 | device_id, 124 | callback=self.on_check_authtoken 125 | ) 126 | elif username and password and device_id: 127 | self._login_notification = notification_area.notify('Logging in...') 128 | gp.login_async( 129 | username, 130 | password, 131 | device_id, 132 | callback=self.on_login 133 | ) 134 | else: 135 | self._login_notification = notification_area.notify( 136 | 'Please set your credentials on the settings page.' 137 | ) 138 | 139 | def on_check_authtoken(self, success, error): 140 | """ 141 | Called once cached auth token is validated. 142 | If *error* is ``None`` and *success* is ``True``, switch app to "My library" page. 143 | Otherwise attemt to log in via credentials. 144 | """ 145 | if error: 146 | self._login_notification.update( 147 | 'Failed to use cached auth token: {}'.format(str(error)) 148 | ) 149 | self.log_in(False) 150 | elif not success: 151 | self._login_notification.update( 152 | 'Failed to use cached auth token, proceeding to normal auth.' 153 | ) 154 | self.log_in(False) 155 | else: 156 | self._login_notification.close() 157 | 158 | def on_login(self, success, error): 159 | """ 160 | Called once user authorization finishes. 161 | If *error* is ``None`` and *success* is ``True``, switch app to "My library" page. 162 | """ 163 | if error: 164 | self._login_notification.update('Failed to log in: {}'.format(str(error))) 165 | return 166 | 167 | if not success: 168 | self._login_notification.update( 169 | 'Google Play Music login failed (API returned false)' 170 | ) 171 | return 172 | 173 | with settings.edit() as config: 174 | config['play_settings']['authtoken'] = gp.get_authtoken() 175 | 176 | self._login_notification.close() 177 | 178 | def set_loop(self, loop): 179 | """ 180 | Assign a MainLoop to this app. 181 | """ 182 | self.loop = loop 183 | 184 | def set_page(self, slug): 185 | """ 186 | Switch to a different tab. 187 | """ 188 | page = [page for page in self.pages if page.slug == slug][0] 189 | self.current_page = page 190 | self.contents['body'] = (page, None) 191 | 192 | for tab in self.tabs: 193 | tab.set_active(False) 194 | if tab.page == page: 195 | tab.set_active(True) 196 | 197 | self.redraw() 198 | 199 | page.activate() 200 | 201 | def redraw(self): 202 | """ 203 | Redraw screen. 204 | Needs to be called by other widgets if UI was changed from a different thread. 205 | """ 206 | if self.loop: 207 | self.loop.draw_screen() 208 | 209 | def append_cancel_action(self, action): 210 | """ 211 | Notify app about an action that can be cancelled by adding it to the action stack. 212 | It will be called once when "Escape" key is hit. 213 | """ 214 | self._cancel_actions.append(action) 215 | 216 | def unregister_cancel_action(self, action): 217 | """ 218 | Remove cancel action from action stack. 219 | """ 220 | if action in self._cancel_actions: 221 | self._cancel_actions.remove(action) 222 | 223 | def keypress(self, size, key): 224 | """ 225 | Handle keypress. 226 | Can switch tabs, control playback, flags, notifications and app state. 227 | """ 228 | # for tab in self.tabs: 229 | # if 'meta {}'.format(tab.page.key) == key: 230 | # self.set_page(tab.page.__class__.__name__) 231 | # return 232 | 233 | hotkey_manager.keypress("global", self, super(AppWidget, self), size, key) 234 | 235 | def show_debug(self): 236 | """ Show debug page. """ 237 | self.set_page('debug') 238 | 239 | def show_library(self): 240 | """ Show library page. """ 241 | self.set_page('library') 242 | 243 | def show_playlists(self): 244 | """ Show playlists page. """ 245 | self.set_page('playlists') 246 | 247 | def show_stations(self): 248 | """ Show stations page. """ 249 | self.set_page('stations') 250 | 251 | def show_queue(self): 252 | """ Show queue page. """ 253 | self.set_page('queue') 254 | 255 | def show_search(self): 256 | """ Show search page. """ 257 | self.set_page('search') 258 | 259 | def show_settings(self): 260 | """ Show settings page. """ 261 | self.set_page('settings') 262 | 263 | @staticmethod 264 | def seek_start(): 265 | """ 266 | Seek to the start of the song. 267 | """ 268 | player.seek_absolute(0) 269 | 270 | @staticmethod 271 | def play_pause(): 272 | """ 273 | Toggle play/pause. 274 | """ 275 | player.play_pause() 276 | 277 | @staticmethod 278 | def next_song(): 279 | """ 280 | Play next song. 281 | """ 282 | player.next(True) 283 | 284 | @staticmethod 285 | def prev_song(): 286 | """ 287 | Play the previous song. 288 | """ 289 | player.prev(True) 290 | 291 | @staticmethod 292 | def seek_backward(): 293 | """ 294 | Seek 5% backward. 295 | """ 296 | player.seek(-0.05) 297 | 298 | @staticmethod 299 | def seek_forward(): 300 | """ 301 | Seek 5% forward. 302 | """ 303 | player.seek(0.05) 304 | 305 | @staticmethod 306 | def toggle_shuffle(): 307 | """ 308 | Toggle random playback. 309 | """ 310 | player.set_random(not player.get_is_random()) 311 | 312 | @staticmethod 313 | def toggle_repeat_one(): 314 | """ 315 | Toggle repeat mode. 316 | """ 317 | player.set_repeat_one(not player.get_is_repeat_one()) 318 | 319 | def quit(self): 320 | """ 321 | Quit app. 322 | """ 323 | self.loop = None 324 | sys.exit(0) 325 | 326 | def handle_escape(self): 327 | """ 328 | Run escape actions. If none are pending, close newest notification. 329 | """ 330 | try: 331 | action = self._cancel_actions.pop() 332 | except IndexError: 333 | notification_area.close_newest() 334 | else: 335 | action() 336 | 337 | 338 | class MultilineVersionAction(argparse.Action): 339 | """ 340 | An argparser action for multiple lines so we can display the copyright notice 341 | Based on: https://stackoverflow.com/a/41147122 342 | """ 343 | def __init__(self, option_strings, dest, nargs=None, **kwargs): 344 | if nargs is not None: 345 | raise ValueError("nargs not allowed") 346 | 347 | self.prog = os.path.basename(sys.argv[0]) 348 | super(MultilineVersionAction, self).__init__(option_strings, dest, nargs=0, **kwargs) 349 | 350 | def __call__(self, parser, namespace, values, option_string=None): 351 | parser.exit(message=meta.COPYRIGHT_MESSAGE) 352 | 353 | 354 | def main(): 355 | """ 356 | Application entrypoint. 357 | 358 | This function is required to allow Clay to be ran as application when installed via setuptools. 359 | """ 360 | parser = argparse.ArgumentParser( 361 | prog=meta.APP_NAME, 362 | description=meta.DESCRIPTION, 363 | epilog="This project is neither affiliated nor endorsed by Google." 364 | ) 365 | 366 | parser.add_argument("-v", "--version", action=MultilineVersionAction) 367 | 368 | keybinds_group = parser.add_mutually_exclusive_group() 369 | 370 | keybinds_group.add_argument( 371 | "--with-x-keybinds", 372 | help="define global X keybinds (requires Keybinder and PyGObject)", 373 | action='store_true' 374 | ) 375 | 376 | keybinds_group.add_argument( 377 | "--without-x-keybinds", 378 | help="Don't define global keybinds (overrides configuration file)", 379 | action='store_true' 380 | ) 381 | 382 | args = parser.parse_args() 383 | 384 | if args.version: 385 | exit(0) 386 | 387 | if (args.with_x_keybinds or settings.get('x_keybinds', 'clay_settings')) \ 388 | and not args.without_x_keybinds: 389 | player.enable_xorg_bindings() 390 | 391 | # Create a 256 colour palette. 392 | palette = [(name, '', '', '', res['foreground'], res['background']) 393 | for name, res in settings.colours_config.items()] 394 | 395 | try: 396 | from setproctitle import setproctitle 397 | except ImportError: 398 | pass 399 | else: 400 | setproctitle('clay') 401 | 402 | # Run the actual program 403 | app_widget = AppWidget() 404 | loop = urwid.MainLoop(app_widget, palette) 405 | app_widget.set_loop(loop) 406 | loop.screen.set_terminal_properties(256) 407 | loop.run() 408 | 409 | 410 | if __name__ == '__main__': 411 | main() 412 | -------------------------------------------------------------------------------- /clay/player.py: -------------------------------------------------------------------------------- 1 | """ 2 | Media player built using libVLC. 3 | """ 4 | # pylint: disable=too-many-instance-attributes 5 | # pylint: disable=too-many-public-methods 6 | from random import randint 7 | from ctypes import CFUNCTYPE, c_void_p, c_int, c_char_p 8 | import json 9 | import os 10 | 11 | try: # Python 3.x 12 | from urllib.request import urlopen 13 | except ImportError: # Python 2.x 14 | from urllib2 import urlopen 15 | 16 | from clay import vlc, meta 17 | from clay.eventhook import EventHook 18 | from clay.notifications import notification_area 19 | from clay.osd import osd_manager 20 | from clay.settings import settings 21 | from clay.log import logger 22 | 23 | 24 | class _Queue(object): 25 | """ 26 | Model that represents player queue (local playlist), 27 | i.e. list of tracks to be played. 28 | 29 | Queue is used by :class:`.Player` to choose tracks for playback. 30 | 31 | Queue handles shuffling & repeating. 32 | 33 | Can be populated with :class:`clay.gp.Track` instances. 34 | """ 35 | def __init__(self): 36 | self.random = False 37 | self.repeat_one = False 38 | 39 | self.tracks = [] 40 | self._played_tracks = [] 41 | self.current_track_index = None 42 | 43 | def load(self, tracks, current_track_index=None): 44 | """ 45 | Load list of tracks into queue. 46 | 47 | *current_track_index* can be either ``None`` or ``int`` (zero-indexed). 48 | """ 49 | self.tracks = tracks[:] 50 | if (current_track_index is None) and self.tracks: 51 | current_track_index = 0 52 | self.current_track_index = current_track_index 53 | 54 | def append(self, track): 55 | """ 56 | Append track to playlist. 57 | """ 58 | self.tracks.append(track) 59 | 60 | def remove(self, track): 61 | """ 62 | Remove track from playlist if is present there. 63 | """ 64 | if track not in self.tracks: 65 | return 66 | 67 | index = self.tracks.index(track) 68 | self.tracks.remove(track) 69 | if self.current_track_index is None: 70 | return 71 | if index < self.current_track_index: 72 | self.current_track_index -= 1 73 | 74 | def get_current_track(self): 75 | """ 76 | Return current :class:`clay.gp.Track` 77 | """ 78 | if self.current_track_index is None: 79 | return None 80 | return self.tracks[self.current_track_index] 81 | 82 | def next(self, force=False): 83 | """ 84 | Advance to the next track and return it. 85 | 86 | If *force* is ``True`` then track will be changed even if 87 | track repetition is enabled. Otherwise current track may be yielded 88 | again. 89 | 90 | Manual track switching calls this method with ``force=True`` while 91 | :class:`.Player` end-of-track event will call it with ``force=False``. 92 | """ 93 | if self.current_track_index is None: 94 | if not self.tracks: 95 | return None 96 | self.current_track_index = self.tracks[0] 97 | else: 98 | self._played_tracks.append(self.current_track_index) 99 | 100 | if self.repeat_one and not force: 101 | return self.get_current_track() 102 | 103 | if self.random: 104 | self.current_track_index = randint(0, len(self.tracks) - 1) 105 | return self.get_current_track() 106 | 107 | self.current_track_index += 1 108 | if (self.current_track_index + 1) >= len(self.tracks): 109 | self.current_track_index = 0 110 | 111 | return self.get_current_track() 112 | 113 | def prev(self, force=False): 114 | """ 115 | Revert to their last song and return it. 116 | 117 | If *force* is ``True`` then tracks will be changed event if 118 | tracks repition is enabled. Otherwise current tracks may be 119 | yielded again. 120 | 121 | Manual tracks switching calls this method with ``force=True``. 122 | """ 123 | if self._played_tracks == []: 124 | return None 125 | 126 | if self.repeat_one and not force: 127 | return self.get_current_track() 128 | 129 | self.current_track_index = self._played_tracks.pop() 130 | return self.get_current_track() 131 | 132 | def get_tracks(self): 133 | """ 134 | Return current queue, i.e. a list of :class:`Track` instances. 135 | """ 136 | return self.tracks 137 | 138 | #+pylint: disable=unused-argument 139 | def _dummy_log(data, level, ctx, fmt, args): 140 | """ 141 | A dummy callback function for VLC so it doesn't write to stdout. 142 | Should probably do something in the future 143 | """ 144 | pass 145 | #+pylint: disable=unused-argument 146 | 147 | 148 | class _Player(object): 149 | """ 150 | Interface to libVLC. Uses Queue as a playback plan. 151 | Emits various events if playback state, tracks or play flags change. 152 | 153 | Singleton. 154 | """ 155 | media_position_changed = EventHook() 156 | media_state_changed = EventHook() 157 | track_changed = EventHook() 158 | playback_flags_changed = EventHook() 159 | queue_changed = EventHook() 160 | track_appended = EventHook() 161 | track_removed = EventHook() 162 | 163 | def __init__(self): 164 | self.instance = vlc.Instance() 165 | print_func = CFUNCTYPE(c_void_p, 166 | c_void_p, # data 167 | c_int, # level 168 | c_void_p, # context 169 | c_char_p, # fmt 170 | c_void_p) # args 171 | 172 | self.instance.log_set(print_func(_dummy_log), None) 173 | 174 | self.instance.set_user_agent( 175 | meta.APP_NAME, 176 | meta.USER_AGENT 177 | ) 178 | 179 | self.media_player = self.instance.media_player_new() 180 | 181 | self.media_player.event_manager().event_attach( 182 | vlc.EventType.MediaPlayerPlaying, 183 | self._media_state_changed 184 | ) 185 | self.media_player.event_manager().event_attach( 186 | vlc.EventType.MediaPlayerPaused, 187 | self._media_state_changed 188 | ) 189 | self.media_player.event_manager().event_attach( 190 | vlc.EventType.MediaPlayerEndReached, 191 | self._media_end_reached 192 | ) 193 | self.media_player.event_manager().event_attach( 194 | vlc.EventType.MediaPlayerPositionChanged, 195 | self._media_position_changed 196 | ) 197 | 198 | self.equalizer = vlc.libvlc_audio_equalizer_new() 199 | self.media_player.set_equalizer(self.equalizer) 200 | self._create_station_notification = None 201 | self._is_loading = False 202 | self.queue = _Queue() 203 | 204 | def enable_xorg_bindings(self): 205 | """Enable the global X bindings using keybinder""" 206 | if os.environ.get("DISPLAY") is None: 207 | logger.debug("X11 isn't running so we can't load the global keybinds") 208 | return 209 | 210 | from clay.hotkeys import hotkey_manager 211 | hotkey_manager.play_pause += self.play_pause 212 | hotkey_manager.next += self.next 213 | hotkey_manager.prev += lambda: self.seek_absolute(0) 214 | 215 | def broadcast_state(self): 216 | """ 217 | Write current playback state into a ``/tmp/clay.json`` file. 218 | """ 219 | track = self.queue.get_current_track() 220 | if track is None: 221 | data = dict( 222 | playing=False, 223 | artist=None, 224 | title=None, 225 | progress=None, 226 | length=None 227 | ) 228 | else: 229 | data = dict( 230 | loading=self.is_loading, 231 | playing=self.is_playing, 232 | artist=track.artist, 233 | title=track.title, 234 | progress=self.get_play_progress_seconds(), 235 | length=self.get_length_seconds(), 236 | album_name=track.album_name, 237 | album_url=track.album_url 238 | ) 239 | with open('/tmp/clay.json', 'w') as statefile: 240 | statefile.write(json.dumps(data, indent=4)) 241 | 242 | def _media_state_changed(self, event): 243 | """ 244 | Called when a libVLC playback state changes. 245 | Broadcasts playback state & fires :attr:`media_state_changed` event. 246 | """ 247 | assert event 248 | self.broadcast_state() 249 | self.media_state_changed.fire(self.is_loading, self.is_playing) 250 | 251 | def _media_end_reached(self, event): 252 | """ 253 | Called when end of currently played track is reached. 254 | Advances to the next track. 255 | """ 256 | assert event 257 | self.next() 258 | 259 | def _media_position_changed(self, event): 260 | """ 261 | Called when playback position changes (this happens few times each second.) 262 | Fires :attr:`.media_position_changed` event. 263 | """ 264 | assert event 265 | self.broadcast_state() 266 | self.media_position_changed.fire( 267 | self.get_play_progress() 268 | ) 269 | 270 | def load_queue(self, data, current_index=None): 271 | """ 272 | Load queue & start playback. 273 | Fires :attr:`.queue_changed` event. 274 | 275 | See :meth:`._Queue.load`. 276 | """ 277 | self.queue.load(data, current_index) 278 | self.queue_changed.fire() 279 | self._play() 280 | 281 | def append_to_queue(self, track): 282 | """ 283 | Append track to queue. 284 | Fires :attr:`.track_appended` event. 285 | 286 | See :meth:`._Queue.append` 287 | """ 288 | self.queue.append(track) 289 | self.track_appended.fire(track) 290 | # self.queue_changed.fire() 291 | 292 | def remove_from_queue(self, track): 293 | """ 294 | Remove track from queue. 295 | Fires :attr:`.track_removed` event. 296 | 297 | See :meth:`._Queue.remove` 298 | """ 299 | self.queue.remove(track) 300 | self.track_removed.fire(track) 301 | 302 | def create_station_from_track(self, track): 303 | """ 304 | Request creation of new station from some track. 305 | Runs in background. 306 | """ 307 | self._create_station_notification = notification_area.notify('Creating station...') 308 | track.create_station_async(callback=self._create_station_from_track_ready) 309 | 310 | def _create_station_from_track_ready(self, station, error): 311 | """ 312 | Called when a station is created. 313 | If *error* is ``None``, load new station's tracks into queue. 314 | """ 315 | if error: 316 | self._create_station_notification.update( 317 | 'Failed to create station: {}'.format(str(error)) 318 | ) 319 | return 320 | 321 | if not station.get_tracks(): 322 | self._create_station_notification.update( 323 | 'Newly created station is empty :(' 324 | ) 325 | return 326 | 327 | self.load_queue(station.get_tracks()) 328 | self._create_station_notification.update('Station ready!') 329 | 330 | def get_is_random(self): 331 | """ 332 | Return ``True`` if track selection from queue is randomed, ``False`` otherwise. 333 | """ 334 | return self.queue.random 335 | 336 | def get_is_repeat_one(self): 337 | """ 338 | Return ``True`` if track repetition in queue is enabled, ``False`` otherwise. 339 | """ 340 | return self.queue.repeat_one 341 | 342 | def set_random(self, value): 343 | """ 344 | Enable/disable random track selection. 345 | """ 346 | self.queue.random = value 347 | self.playback_flags_changed.fire() 348 | 349 | def set_repeat_one(self, value): 350 | """ 351 | Enable/disable track repetition. 352 | """ 353 | self.queue.repeat_one = value 354 | self.playback_flags_changed.fire() 355 | 356 | def get_queue_tracks(self): 357 | """ 358 | Return :attr:`._Queue.get_tracks` 359 | """ 360 | return self.queue.get_tracks() 361 | 362 | def _play(self): 363 | """ 364 | Pick current track from a queue and requests media stream URL. 365 | Completes in background. 366 | """ 367 | track = self.queue.get_current_track() 368 | if track is None: 369 | return 370 | self._is_loading = True 371 | self.broadcast_state() 372 | self.track_changed.fire(track) 373 | 374 | if settings.get('download_tracks', 'play_settings') or \ 375 | settings.get_is_file_cached(track.filename): 376 | path = settings.get_cached_file_path(track.filename) 377 | 378 | if path is None: 379 | logger.debug('Track %s not in cache, downloading...', track.store_id) 380 | track.get_url(callback=self._download_track) 381 | else: 382 | logger.debug('Track %s in cache, playing', track.store_id) 383 | self._play_ready(path, None, track) 384 | else: 385 | logger.debug('Starting to stream %s', track.store_id) 386 | track.get_url(callback=self._play_ready) 387 | 388 | def _download_track(self, url, error, track): 389 | if error: 390 | notification_area.notify('Failed to request media URL: {}'.format(str(error))) 391 | logger.error( 392 | 'Failed to request media URL for track %s: %s', 393 | track.original_data, 394 | str(error) 395 | ) 396 | return 397 | response = urlopen(url) 398 | path = settings.save_file_to_cache(track.filename, response.read()) 399 | self._play_ready(path, None, track) 400 | 401 | def _play_ready(self, url, error, track): 402 | """ 403 | Called once track's media stream URL request completes. 404 | If *error* is ``None``, tell libVLC to play media by *url*. 405 | """ 406 | self._is_loading = False 407 | if error: 408 | notification_area.notify('Failed to request media URL: {}'.format(str(error))) 409 | logger.error( 410 | 'Failed to request media URL for track %s: %s', 411 | track.original_data, 412 | str(error) 413 | ) 414 | return 415 | assert track 416 | media = vlc.Media(url) 417 | self.media_player.set_media(media) 418 | 419 | self.media_player.play() 420 | 421 | osd_manager.notify(track) 422 | 423 | @property 424 | def is_loading(self): 425 | """ 426 | True if current libVLC state is :attr:`vlc.State.Playing` 427 | """ 428 | return self._is_loading 429 | 430 | @property 431 | def is_playing(self): 432 | """ 433 | True if current libVLC state is :attr:`vlc.State.Playing` 434 | """ 435 | return self.media_player.get_state() == vlc.State.Playing 436 | 437 | def play_pause(self): 438 | """ 439 | Toggle playback, i.e. play if paused or pause if playing. 440 | """ 441 | if self.is_playing: 442 | self.media_player.pause() 443 | else: 444 | self.media_player.play() 445 | 446 | def get_play_progress(self): 447 | """ 448 | Return current playback position in range ``[0;1]`` (``float``). 449 | """ 450 | return self.media_player.get_position() 451 | 452 | def get_play_progress_seconds(self): 453 | """ 454 | Return current playback position in seconds (``int``). 455 | """ 456 | return int(self.media_player.get_position() * self.media_player.get_length() / 1000) 457 | 458 | def get_length_seconds(self): 459 | """ 460 | Return currently played track's length in seconds (``int``). 461 | """ 462 | return int(self.media_player.get_length() // 1000) 463 | 464 | def next(self, force=False): 465 | """ 466 | Advance to next track in queue. 467 | See :meth:`._Queue.next`. 468 | """ 469 | self.queue.next(force) 470 | self._play() 471 | 472 | def prev(self, force=False): 473 | """ 474 | Advance to their previous track in their queue 475 | seek :meth:`._Queue.prev` 476 | """ 477 | self.queue.prev(force) 478 | self._play() 479 | 480 | def get_current_track(self): 481 | """ 482 | Return currently played track. 483 | See :meth:`._Queue.get_current_track`. 484 | """ 485 | return self.queue.get_current_track() 486 | 487 | def seek(self, delta): 488 | """ 489 | Seek to relative position. 490 | *delta* must be a ``float`` in range ``[-1;1]``. 491 | """ 492 | self.media_player.set_position(self.get_play_progress() + delta) 493 | 494 | def seek_absolute(self, position): 495 | """ 496 | Seek to absolute position. 497 | *position* must be a ``float`` in range ``[0;1]``. 498 | """ 499 | self.media_player.set_position(position) 500 | 501 | @staticmethod 502 | def get_equalizer_freqs(): 503 | """ 504 | Return a list of equalizer frequencies for each band. 505 | """ 506 | return [ 507 | vlc.libvlc_audio_equalizer_get_band_frequency(index) 508 | for index 509 | in range(vlc.libvlc_audio_equalizer_get_band_count()) 510 | ] 511 | 512 | def get_equalizer_amps(self): 513 | """ 514 | Return a list of equalizer amplifications for each band. 515 | """ 516 | return [ 517 | vlc.libvlc_audio_equalizer_get_amp_at_index( 518 | self.equalizer, 519 | index 520 | ) 521 | for index 522 | in range(vlc.libvlc_audio_equalizer_get_band_count()) 523 | ] 524 | 525 | def set_equalizer_value(self, index, amp): 526 | """ 527 | Set equalizer amplification for specific band. 528 | """ 529 | assert vlc.libvlc_audio_equalizer_set_amp_at_index( 530 | self.equalizer, 531 | amp, 532 | index 533 | ) == 0 534 | self.media_player.set_equalizer(self.equalizer) 535 | 536 | def set_equalizer_values(self, amps): 537 | """ 538 | Set a list of equalizer amplifications for each band. 539 | """ 540 | assert len(amps) == vlc.libvlc_audio_equalizer_get_band_count() 541 | for index, amp in enumerate(amps): 542 | assert vlc.libvlc_audio_equalizer_set_amp_at_index( 543 | self.equalizer, 544 | amp, 545 | index 546 | ) == 0 547 | self.media_player.set_equalizer(self.equalizer) 548 | 549 | 550 | player = _Player() # pylint: disable=invalid-name 551 | -------------------------------------------------------------------------------- /clay/gp.py: -------------------------------------------------------------------------------- 1 | """ 2 | Google Play Music integration via gmusicapi. 3 | """ 4 | # pylint: disable=broad-except 5 | # pylint: disable=protected-access 6 | from __future__ import print_function 7 | try: # Python 3.x 8 | from urllib.request import urlopen 9 | except ImportError: # Python 2.x 10 | from urllib import urlopen 11 | try: 12 | from PIL import Image 13 | except ImportError: 14 | Image = None 15 | from io import BytesIO 16 | from hashlib import sha1 17 | from threading import Thread, Lock 18 | from uuid import UUID 19 | 20 | from gmusicapi.clients import Mobileclient 21 | 22 | from clay.eventhook import EventHook 23 | from clay.log import logger 24 | from clay.settings import settings 25 | 26 | STATION_FETCH_LEN = 50 27 | 28 | 29 | def asynchronous(func): 30 | """ 31 | Decorates a function to become asynchronous. 32 | 33 | Once called, runs original function in a new Thread. 34 | 35 | Must be called with a 'callback' argument that will be called 36 | once thread with original function finishes. Receives two args: 37 | result and error. 38 | 39 | - "result" contains function return value or None if there was an exception. 40 | - "error" contains None or Exception if there was one. 41 | """ 42 | def wrapper(*args, **kwargs): 43 | """ 44 | Inner function. 45 | """ 46 | callback = kwargs.pop('callback') 47 | extra = kwargs.pop('extra', dict()) 48 | 49 | def process(): 50 | """ 51 | Thread body. 52 | """ 53 | try: 54 | result = func(*args, **kwargs) 55 | except Exception as error: 56 | callback(None, error, **extra) 57 | else: 58 | callback(result, None, **extra) 59 | 60 | Thread(target=process).start() 61 | 62 | return wrapper 63 | 64 | 65 | def synchronized(func): 66 | """ 67 | Decorates a function to become thread-safe by preventing 68 | it from being executed multiple times before previous calls end. 69 | 70 | Lock is acquired on entrance and is released on return or Exception. 71 | """ 72 | lock = Lock() 73 | 74 | def wrapper(*args, **kwargs): 75 | """ 76 | Inner function. 77 | """ 78 | try: 79 | lock.acquire() 80 | return func(*args, **kwargs) 81 | finally: 82 | lock.release() 83 | 84 | return wrapper 85 | 86 | 87 | class Track(object): 88 | """ 89 | Model that represents single track from Google Play Music. 90 | """ 91 | TYPE_UPLOADED = 'uploaded' 92 | TYPE_STORE = 'store' 93 | 94 | SOURCE_LIBRARY = 'library' 95 | SOURCE_STATION = 'station' 96 | SOURCE_PLAYLIST = 'playlist' 97 | SOURCE_SEARCH = 'search' 98 | 99 | def __init__(self, source, data): 100 | # In playlist items and user uploaded songs the storeIds are missing so 101 | self.store_id = (data['storeId'] if 'storeId' in data else data.get('id')) 102 | self.playlist_item_id = (UUID(data['id']) if source == self.SOURCE_PLAYLIST else None) 103 | self.library_id = (UUID(data['id']) if source == self.SOURCE_LIBRARY else None) 104 | 105 | # To filter out the playlist items we need to reassign the store_id when fetching the track 106 | if 'track' in data: 107 | data = data['track'] 108 | self.store_id = data['storeId'] 109 | 110 | artist_art_ref = next(iter(sorted( 111 | [ 112 | ref 113 | for ref 114 | in data.get('artistArtRef', []) 115 | ], 116 | key=lambda x: x['aspectRatio'] 117 | )), None) 118 | self.title = data['title'] 119 | self.artist = data['artist'] 120 | self.duration = int(data['durationMillis']) 121 | self.rating = (int(data['rating']) if 'rating' in data else 0) 122 | self.source = source 123 | self.cached_url = None 124 | self.artist_art_url = None 125 | self.artist_art_filename = None 126 | if artist_art_ref is not None: 127 | self.artist_art_url = artist_art_ref['url'] 128 | self.artist_art_filename = sha1( 129 | self.artist_art_url.encode('utf-8') 130 | ).hexdigest() + u'.jpg' 131 | self.explicit_rating = (int(data['explicitType'])) 132 | 133 | if self.rating == 5: 134 | gp.cached_liked_songs.add_liked_song(self) 135 | 136 | # User uploaded songs miss a store_id 137 | self.album_name = data['album'] 138 | self.album_url = (data['albumArtRef'][0]['url'] if 'albumArtRef' in data else "") 139 | 140 | self.original_data = data 141 | 142 | @property 143 | def id(self): # pylint: disable=invalid-name 144 | """ 145 | Return ID for this track. 146 | """ 147 | if self.library_id: 148 | return self.library_id 149 | return self.store_id 150 | 151 | @property 152 | def filename(self): 153 | """ 154 | Return a filename for this track. 155 | """ 156 | return self.store_id + '.mp3' 157 | 158 | def __eq__(self, other): 159 | return ( 160 | (self.library_id and self.library_id == other.library_id) or 161 | (self.store_id and self.store_id == other.store_id) or 162 | (self.playlist_item_id and self.playlist_item_id == other.playlist_item_id) 163 | ) 164 | 165 | @classmethod 166 | def from_data(cls, data, source, many=False): 167 | """ 168 | Construct and return one or many :class:`.Track` instances 169 | from Google Play Music API response. 170 | """ 171 | if many: 172 | return [track for track in 173 | [cls.from_data(one, source) for one in data] 174 | if track is not None] 175 | try: 176 | if source == cls.SOURCE_PLAYLIST and 'track' not in data: 177 | track = gp.get_track_by_id(UUID(data['trackId'])) 178 | else: 179 | track = Track(source, data) 180 | 181 | return track 182 | except Exception as error: # pylint: disable=bare-except 183 | logger.error( 184 | 'Failed to parse track data: %s, failing data: %s', 185 | repr(error), 186 | data 187 | ) 188 | # TODO: Fix this. 189 | # print('Failed to create track from data.') 190 | # print('Failing payload was:') 191 | # print(data) 192 | # raise Exception( 193 | # 'Failed to create track from data. Original error: {}. Payload: {}'.format( 194 | # str(error), 195 | # data 196 | # ) 197 | # ) 198 | return None 199 | 200 | raise AssertionError() 201 | 202 | def get_url(self, callback): 203 | """ 204 | Gets playable stream URL for this track. 205 | 206 | "callback" is called with "(url, error)" args after URL is fetched. 207 | 208 | Keep in mind this URL is valid for a limited time. 209 | """ 210 | def on_get_url(url, error): 211 | """ 212 | Called when URL is fetched. 213 | """ 214 | self.cached_url = url 215 | callback(url, error, self) 216 | 217 | if gp.is_subscribed: 218 | track_id = self.store_id 219 | else: 220 | track_id = self.library_id 221 | gp.get_stream_url_async(track_id, callback=on_get_url) 222 | 223 | @synchronized 224 | def get_artist_art_filename(self): 225 | """ 226 | Return artist art filename, None if this track doesn't have any. 227 | Downloads if necessary. 228 | """ 229 | if self.artist_art_url is None: 230 | return None 231 | 232 | if not settings.get_is_file_cached(self.artist_art_filename): 233 | response = urlopen(self.artist_art_url) 234 | data = response.read() 235 | if Image: 236 | image = Image.open(BytesIO(data)) 237 | image.thumbnail((128, 128)) 238 | out = BytesIO() 239 | image.save(out, format='JPEG') 240 | data = out.getvalue() 241 | settings.save_file_to_cache(self.artist_art_filename, data) 242 | 243 | return settings.get_cached_file_path(self.artist_art_filename) 244 | 245 | # get_artist_arg_filename_async = asynchronous(get_artist_art_filename) 246 | 247 | @synchronized 248 | def create_station(self): 249 | """ 250 | Creates a new station from this :class:`.Track`. 251 | 252 | Returns :class:`.Station` instance. 253 | """ 254 | station_name = u'Station - {}'.format(self.title) 255 | station_id = gp.mobile_client.create_station( 256 | name=station_name, 257 | track_id=self.store_id 258 | ) 259 | station = Station(station_id, station_name) 260 | station.load_tracks() 261 | return station 262 | 263 | create_station_async = asynchronous(create_station) 264 | 265 | def add_to_my_library(self): 266 | """ 267 | Add a track to my library. 268 | """ 269 | return gp.add_to_my_library(self) 270 | 271 | add_to_my_library_async = asynchronous(add_to_my_library) 272 | 273 | def remove_from_my_library(self): 274 | """ 275 | Remove a track from my library. 276 | """ 277 | return gp.remove_from_my_library(self) 278 | 279 | remove_from_my_library_async = asynchronous(remove_from_my_library) 280 | 281 | def rate_song(self, rating): 282 | """ 283 | Rate the song either 0 (no thumb), 1 (down thumb) or 5 (up thumb). 284 | """ 285 | gp.mobile_client.rate_songs(self.original_data, rating) 286 | self.original_data['rating'] = rating 287 | self.rating = rating 288 | 289 | if rating == 5: 290 | gp.cached_liked_songs.add_liked_song(self) 291 | 292 | def __str__(self): 293 | return u''.format( 294 | self.artist, 295 | self.title, 296 | self.source 297 | ) 298 | 299 | __repr__ = __str__ 300 | 301 | 302 | class Artist(object): 303 | """ 304 | Model that represents an artist. 305 | """ 306 | def __init__(self, artist_id, name): 307 | self._id = artist_id 308 | self.name = name 309 | 310 | @property 311 | def id(self): # pylint: disable=invalid-name 312 | """ 313 | Artist ID. 314 | """ 315 | return self._id 316 | 317 | @classmethod 318 | def from_data(cls, data, many=False): 319 | """ 320 | Construct and return one or many :class:`.Artist` instances 321 | from Google Play Music API response. 322 | """ 323 | if many: 324 | return [cls.from_data(one) for one in data] 325 | 326 | return Artist( 327 | artist_id=data['artistId'], 328 | name=data['name'] 329 | ) 330 | 331 | 332 | class Station(object): 333 | """ 334 | Model that represents specific station on Google Play Music. 335 | """ 336 | def __init__(self, station_id, name): 337 | self.name = name 338 | self._id = station_id 339 | self._tracks = [] 340 | self._tracks_loaded = False 341 | 342 | @property 343 | def id(self): # pylint: disable=invalid-name 344 | """ 345 | Station ID. 346 | """ 347 | return self._id 348 | 349 | def load_tracks(self): 350 | """ 351 | Fetch tracks related to this station and 352 | populate it with :class:`Track` instances. 353 | """ 354 | data = gp.mobile_client.get_station_tracks(self.id, STATION_FETCH_LEN) 355 | self._tracks = Track.from_data(data, Track.SOURCE_STATION, many=True) 356 | self._tracks_loaded = True 357 | return self 358 | 359 | load_tracks_async = asynchronous(load_tracks) 360 | 361 | def get_tracks(self): 362 | """ 363 | Return a list of tracks in this station. 364 | """ 365 | assert self._tracks_loaded, 'Must call ".load_tracks()" before ".get_tracks()"' 366 | return self._tracks 367 | 368 | @classmethod 369 | def from_data(cls, data, many=False): 370 | """ 371 | Construct and return one or many :class:`.Station` instances 372 | from Google Play Music API response. 373 | """ 374 | if many: 375 | return [cls.from_data(one) for one in data if one['inLibrary']] 376 | 377 | return Station( 378 | station_id=data['id'], 379 | name=data['name'] 380 | ) 381 | 382 | 383 | class SearchResults(object): 384 | """ 385 | Model that represents search results including artists & tracks. 386 | """ 387 | def __init__(self, tracks, artists): 388 | self.artists = artists 389 | self.tracks = tracks 390 | 391 | @classmethod 392 | def from_data(cls, data): 393 | """ 394 | Construct and return :class:`.SearchResults` instance from raw data. 395 | """ 396 | return SearchResults( 397 | tracks=Track.from_data(data['song_hits'], Track.SOURCE_SEARCH, many=True), 398 | artists=Artist.from_data([ 399 | item['artist'] 400 | for item 401 | in data['artist_hits'] 402 | ], many=True) 403 | ) 404 | 405 | def get_artists(self): 406 | """ 407 | Return found artists. 408 | """ 409 | return self.artists 410 | 411 | def get_tracks(self): 412 | """ 413 | Return found tracks. 414 | """ 415 | return self.tracks 416 | 417 | 418 | class Playlist(object): 419 | """ 420 | Model that represents remotely stored (Google Play Music) playlist. 421 | """ 422 | def __init__(self, playlist_id, name, tracks): 423 | self._id = playlist_id 424 | self.name = name 425 | self.tracks = tracks 426 | 427 | @property 428 | def id(self): # pylint: disable=invalid-name 429 | """ 430 | Playlist ID. 431 | """ 432 | return self._id 433 | 434 | @classmethod 435 | def from_data(cls, data, many=False): 436 | """ 437 | Construct and return one or many :class:`.Playlist` instances 438 | from Google Play Music API response. 439 | """ 440 | if many: 441 | return [cls.from_data(one) for one in data] 442 | 443 | return Playlist( 444 | playlist_id=data['id'], 445 | name=data['name'], 446 | tracks=Track.from_data(data['tracks'], Track.SOURCE_PLAYLIST, many=True) 447 | ) 448 | 449 | 450 | class LikedSongs(object): 451 | """ 452 | A local model that represents the songs that a user liked and displays them as a faux playlist. 453 | 454 | This mirrors the "liked songs" generated playlist feature of the Google Play Music apps. 455 | """ 456 | def __init__(self): 457 | self._id = None # pylint: disable=invalid-name 458 | self.name = "Liked Songs" 459 | self._tracks = [] 460 | self._sorted = False 461 | 462 | @property 463 | def tracks(self): 464 | """ 465 | Get a sorted list of liked tracks. 466 | """ 467 | if self._sorted: 468 | tracks = self._tracks 469 | else: 470 | self._tracks.sort(key=lambda k: k.original_data.get('lastRatingChangeTimestamp', '0'), 471 | reverse=True) 472 | self._sorted = True 473 | tracks = self._tracks 474 | 475 | return tracks 476 | 477 | def add_liked_song(self, song): 478 | """ 479 | Add a liked song to the list. 480 | """ 481 | self._tracks.insert(0, song) 482 | 483 | def remove_liked_song(self, song): 484 | """ 485 | Remove a liked song from the list 486 | """ 487 | self._tracks.remove(song) 488 | 489 | 490 | class _GP(object): 491 | """ 492 | Interface to :class:`gmusicapi.Mobileclient`. Implements 493 | asynchronous API calls, caching and some other perks. 494 | 495 | Singleton. 496 | """ 497 | # TODO: Switch to urwid signals for more explicitness? 498 | caches_invalidated = EventHook() 499 | 500 | def __init__(self): 501 | # self.is_debug = os.getenv('CLAY_DEBUG') 502 | self.mobile_client = Mobileclient() 503 | self.mobile_client._make_call = self._make_call_proxy( 504 | self.mobile_client._make_call 505 | ) 506 | # if self.is_debug: 507 | # self.debug_file = open('/tmp/clay-api-log.json', 'w') 508 | # self._last_call_index = 0 509 | self.cached_tracks = None 510 | self.cached_liked_songs = LikedSongs() 511 | self.cached_playlists = None 512 | self.cached_stations = None 513 | 514 | self.invalidate_caches() 515 | 516 | self.auth_state_changed = EventHook() 517 | 518 | def _make_call_proxy(self, func): 519 | """ 520 | Return a function that wraps *fn* and logs args & return values. 521 | """ 522 | def _make_call(protocol, *args, **kwargs): 523 | """ 524 | Wrapper function. 525 | """ 526 | logger.debug('GP::{}(*{}, **{})'.format( 527 | protocol.__name__, 528 | args, 529 | kwargs 530 | )) 531 | result = func(protocol, *args, **kwargs) 532 | # self._last_call_index += 1 533 | # call_index = self._last_call_index 534 | # self.debug_file.write(json.dumps([ 535 | # call_index, 536 | # protocol.__name__, args, kwargs, 537 | # result 538 | # ]) + '\n') 539 | # self.debug_file.flush() 540 | return result 541 | return _make_call 542 | 543 | def invalidate_caches(self): 544 | """ 545 | Clear cached tracks & playlists & stations. 546 | """ 547 | self.cached_tracks = None 548 | self.cached_playlists = None 549 | self.cached_stations = None 550 | self.caches_invalidated.fire() 551 | 552 | @synchronized 553 | def login(self, email, password, device_id, **_): 554 | """ 555 | Log in into Google Play Music. 556 | """ 557 | self.mobile_client.logout() 558 | self.invalidate_caches() 559 | # prev_auth_state = self.is_authenticated 560 | result = self.mobile_client.login(email, password, device_id) 561 | # if prev_auth_state != self.is_authenticated: 562 | self.auth_state_changed.fire(self.is_authenticated) 563 | return result 564 | 565 | login_async = asynchronous(login) 566 | 567 | @synchronized 568 | def use_authtoken(self, authtoken, device_id): 569 | """ 570 | Try to use cached token to log into Google Play Music. 571 | """ 572 | # pylint: disable=protected-access 573 | self.mobile_client.session._authtoken = authtoken 574 | self.mobile_client.session.is_authenticated = True 575 | self.mobile_client.android_id = device_id 576 | del self.mobile_client.is_subscribed 577 | if self.mobile_client.is_subscribed: 578 | self.auth_state_changed.fire(True) 579 | return True 580 | del self.mobile_client.is_subscribed 581 | self.mobile_client.android_id = None 582 | self.mobile_client.session.is_authenticated = False 583 | self.auth_state_changed.fire(False) 584 | return False 585 | 586 | use_authtoken_async = asynchronous(use_authtoken) 587 | 588 | def get_authtoken(self): 589 | """ 590 | Return currently active auth token. 591 | """ 592 | # pylint: disable=protected-access 593 | return self.mobile_client.session._authtoken 594 | 595 | @synchronized 596 | def get_all_tracks(self): 597 | """ 598 | Cache and return all tracks from "My library". 599 | 600 | Each track will have "id" and "storeId" keys. 601 | """ 602 | if self.cached_tracks: 603 | return self.cached_tracks 604 | data = self.mobile_client.get_all_songs() 605 | self.cached_tracks = Track.from_data(data, Track.SOURCE_LIBRARY, True) 606 | 607 | return self.cached_tracks 608 | 609 | get_all_tracks_async = asynchronous(get_all_tracks) 610 | 611 | def get_stream_url(self, stream_id): 612 | """ 613 | Returns playable stream URL of track by id. 614 | """ 615 | return self.mobile_client.get_stream_url(stream_id) 616 | 617 | get_stream_url_async = asynchronous(get_stream_url) 618 | 619 | @synchronized 620 | def get_all_user_station_contents(self, **_): 621 | """ 622 | Return list of :class:`.Station` instances. 623 | """ 624 | if self.cached_stations: 625 | return self.cached_stations 626 | self.get_all_tracks() 627 | 628 | self.cached_stations = Station.from_data( 629 | self.mobile_client.get_all_stations(), 630 | True 631 | ) 632 | return self.cached_stations 633 | 634 | get_all_user_station_contents_async = ( # pylint: disable=invalid-name 635 | asynchronous(get_all_user_station_contents) 636 | ) 637 | 638 | @synchronized 639 | def get_all_user_playlist_contents(self, **_): 640 | """ 641 | Return list of :class:`.Playlist` instances. 642 | """ 643 | if self.cached_playlists: 644 | return [self.cached_liked_songs] + self.cached_playlists 645 | 646 | self.get_all_tracks() 647 | 648 | self.cached_playlists = Playlist.from_data( 649 | self.mobile_client.get_all_user_playlist_contents(), 650 | True 651 | ) 652 | return [self.cached_liked_songs] + self.cached_playlists 653 | 654 | get_all_user_playlist_contents_async = ( # pylint: disable=invalid-name 655 | asynchronous(get_all_user_playlist_contents) 656 | ) 657 | 658 | def get_cached_tracks_map(self): 659 | """ 660 | Return a dictionary of tracks where keys are strings with track IDs 661 | and values are :class:`.Track` instances. 662 | """ 663 | return {track.id: track for track in self.cached_tracks} 664 | 665 | def get_track_by_id(self, any_id): 666 | """ 667 | Return track by id or store_id. 668 | """ 669 | for track in self.cached_tracks: 670 | if any_id in (track.library_id, track.store_id, track.playlist_item_id): 671 | return track 672 | return None 673 | 674 | def search(self, query): 675 | """ 676 | Find tracks and return an instance of :class:`.SearchResults`. 677 | """ 678 | results = self.mobile_client.search(query) 679 | return SearchResults.from_data(results) 680 | 681 | search_async = asynchronous(search) 682 | 683 | def add_to_my_library(self, track): 684 | """ 685 | Add a track to my library. 686 | """ 687 | result = self.mobile_client.add_store_tracks(track.id) 688 | if result: 689 | self.invalidate_caches() 690 | return result 691 | 692 | def remove_from_my_library(self, track): 693 | """ 694 | Remove a track from my library. 695 | """ 696 | result = self.mobile_client.delete_songs(track.id) 697 | if result: 698 | self.invalidate_caches() 699 | return result 700 | 701 | @property 702 | def is_authenticated(self): 703 | """ 704 | Return True if user is authenticated on Google Play Music, false otherwise. 705 | """ 706 | return self.mobile_client.is_authenticated() 707 | 708 | @property 709 | def is_subscribed(self): 710 | """ 711 | Return True if user is subscribed on Google Play Music, false otherwise. 712 | """ 713 | return self.mobile_client.is_subscribed 714 | 715 | 716 | gp = _GP() # pylint: disable=invalid-name 717 | -------------------------------------------------------------------------------- /clay/songlist.py: -------------------------------------------------------------------------------- 1 | """ 2 | Components for song listing. 3 | """ 4 | # pylint: disable=too-many-arguments 5 | # pylint: disable=too-many-instance-attributes 6 | # pylint: disable=too-many-public-methods 7 | from operator import lt, gt 8 | from string import digits 9 | 10 | try: 11 | # Python 3.x 12 | from string import ascii_letters 13 | except ImportError: 14 | # Python 2.x 15 | from string import letters as ascii_letters 16 | import urwid 17 | from clay.notifications import notification_area 18 | from clay.player import player 19 | from clay.gp import gp 20 | from clay.clipboard import copy 21 | from clay.settings import settings 22 | from clay.hotkeys import hotkey_manager 23 | 24 | 25 | class SongListItem(urwid.Pile): 26 | """ 27 | Widget that represents single song item. 28 | """ 29 | _unicode = settings.get('unicode', 'clay_settings') 30 | signals = [ 31 | 'activate', 32 | 'play', 33 | 'append-requested', 34 | 'unappend-requested', 35 | 'station-requested', 36 | 'context-menu-requested' 37 | ] 38 | 39 | STATE_IDLE = 0 40 | STATE_LOADING = 1 41 | STATE_PLAYING = 2 42 | STATE_PAUSED = 3 43 | 44 | LINE1_ATTRS = { 45 | STATE_IDLE: ('line1', 'line1_focus'), 46 | STATE_LOADING: ('line1_active', 'line1_active_focus'), 47 | STATE_PLAYING: ('line1_active', 'line1_active_focus'), 48 | STATE_PAUSED: ('line1_active', 'line1_active_focus') 49 | } 50 | LINE2_ATTRS = { 51 | STATE_IDLE: ('line2', 'line2_focus'), 52 | STATE_LOADING: ('line2', 'line2_focus'), 53 | STATE_PLAYING: ('line2', 'line2_focus'), 54 | STATE_PAUSED: ('line2', 'line2_focus') 55 | } 56 | 57 | STATE_ICONS = { 58 | 0: ' ', 59 | 1: u'\u2505', 60 | 2: u'\u25B6', 61 | 3: u'\u25A0' 62 | } 63 | 64 | RATING_ICONS = { 65 | 0: ' ', 66 | 1: u'\U0001F593' if _unicode else '-', 67 | 2: u'\U0001F593' if _unicode else '2', 68 | 3: u'\U0001F593' if _unicode else '3', 69 | 4: u'\U0001F593' if _unicode else '4', 70 | 5: u'\U0001F592' if _unicode else '+' 71 | } 72 | 73 | EXPLICIT_ICONS = { 74 | 0: ' ', # not actually used? 75 | 1: u'\U0001F174' if _unicode else '[E]', 76 | 2: ' ', 77 | 3: ' ' 78 | } 79 | 80 | def __init__(self, track): 81 | self.track = track 82 | self.rating = self.RATING_ICONS[track.rating] 83 | self.explicit = self.EXPLICIT_ICONS[track.explicit_rating] 84 | self.index = 0 85 | self.state = SongListItem.STATE_IDLE 86 | self.line1_left = urwid.SelectableIcon('', cursor_position=1000) 87 | self.line1_left.set_layout('left', 'clip', None) 88 | self.line1_right = urwid.Text('x') 89 | self.line1 = urwid.Columns([ 90 | self.line1_left, 91 | ('pack', self.line1_right), 92 | ('pack', urwid.Text(' ')) 93 | ]) 94 | self.line2 = urwid.Text('', wrap='clip') 95 | 96 | self.line1_wrap = urwid.AttrWrap(self.line1, 'line1') 97 | self.line2_wrap = urwid.AttrWrap(self.line2, 'line2') 98 | 99 | self.content = urwid.Pile([ 100 | self.line1_wrap, 101 | self.line2_wrap, 102 | urwid.Text('') 103 | ]) 104 | 105 | self.is_focused = False 106 | 107 | super(SongListItem, self).__init__([ 108 | self.content 109 | ]) 110 | self.update_text() 111 | 112 | def set_state(self, state): 113 | """ 114 | Set state for this song. 115 | Possible choices are: 116 | 117 | - :attr:`.SongListItem.STATE_IDLE` 118 | - :attr:`.SongListItem.STATE_LOADING` 119 | - :attr:`.SongListItem.STATE_PLAYING` 120 | - :attr:`.SongListItem.STATE_PAUSED` 121 | """ 122 | self.state = state 123 | self.update_text() 124 | 125 | @staticmethod 126 | def get_state_icon(state): 127 | """ 128 | Get icon char for specific state. 129 | """ 130 | return SongListItem.STATE_ICONS[state] 131 | 132 | def update_text(self): 133 | """ 134 | Update text of this item from the attached track. 135 | """ 136 | self.line1_left.set_text( 137 | u'{index:3d} {icon} {title} [{minutes:02d}:{seconds:02d}]'.format( 138 | index=self.index + 1, 139 | icon=self.get_state_icon(self.state), 140 | title=self.track.title, 141 | minutes=self.track.duration // (1000 * 60), 142 | seconds=(self.track.duration // 1000) % 60, 143 | ) 144 | ) 145 | 146 | if settings.get_is_file_cached(self.track.filename): 147 | self.line1_right.set_text(u' \u25bc Cached') 148 | else: 149 | self.line1_right.set_text(u'') 150 | 151 | self.line1_right.set_text(u'{explicit} {rating}'.format(explicit=self.explicit, 152 | rating=self.rating)) 153 | 154 | self.line2.set_text( 155 | u' {} \u2015 {}'.format(self.track.artist, self.track.album_name) 156 | ) 157 | self.line1_wrap.set_attr(SongListItem.LINE1_ATTRS[self.state][self.is_focused]) 158 | self.line2_wrap.set_attr(SongListItem.LINE2_ATTRS[self.state][self.is_focused]) 159 | 160 | @property 161 | def full_title(self): 162 | """ 163 | Return song artist and title. 164 | """ 165 | return u'{} - {} {}'.format( 166 | self.track.artist, 167 | self.track.title, 168 | self.rating 169 | ) 170 | 171 | def keypress(self, size, key): 172 | """ 173 | Handle keypress. 174 | """ 175 | return hotkey_manager.keypress("library_item", self, super(SongListItem, self), size, key) 176 | 177 | def mouse_event(self, size, event, button, col, row, focus): 178 | """ 179 | Handle mouse event. 180 | """ 181 | if button == 1 and focus: 182 | urwid.emit_signal(self, 'activate', self) 183 | return None 184 | return super(SongListItem, self).mouse_event(size, event, button, col, row, focus) 185 | 186 | def thumbs_up(self): 187 | """ 188 | Thumb the currently selected song up. 189 | """ 190 | self.track.rate_song((0 if self.track.rating == 5 else 5)) 191 | 192 | def thumbs_down(self): 193 | """ 194 | Thumb the currently selected song down. 195 | """ 196 | self.track.rate_song((0 if self.track.rating == 1 else 1)) 197 | 198 | def _send_signal(self, signal): 199 | urwid.emit_signal(self, signal, self) 200 | 201 | def activate(self): 202 | """ 203 | Add the entire list to queue and begin playing 204 | """ 205 | self._send_signal("activate") 206 | 207 | def play(self): 208 | """ 209 | Play this song. 210 | """ 211 | self._send_signal("play") 212 | 213 | def append(self): 214 | """ 215 | Add this song to the queue. 216 | """ 217 | self._send_signal("append-requested") 218 | self.play() 219 | 220 | def unappend(self): 221 | """ 222 | Remove this song from the queue. 223 | """ 224 | if not self.is_currently_played: 225 | self._send_signal("unappend-requested") 226 | 227 | def request_station(self): 228 | """ 229 | Create a Google Play Music radio for this song. 230 | """ 231 | self._send_signal("station-requested") 232 | 233 | def show_context_menu(self): 234 | """ 235 | Display the context menu for this song. 236 | """ 237 | self._send_signal("context-menu-requested") 238 | 239 | @property 240 | def is_currently_played(self): 241 | """ 242 | Return ``True`` if song is in state :attr:`.SongListItem.STATE_PLAYING` 243 | or :attr:`.SongListItem.STATE_PAUSED`. 244 | """ 245 | return self.state in ( 246 | SongListItem.STATE_LOADING, 247 | SongListItem.STATE_PLAYING, 248 | SongListItem.STATE_PAUSED 249 | ) 250 | 251 | def set_index(self, index): 252 | """ 253 | Set numeric index for this item. 254 | """ 255 | self.index = index 256 | self.update_text() 257 | 258 | def render(self, size, focus=False): 259 | """ 260 | Render widget & set focused state. 261 | """ 262 | self.is_focused = focus 263 | self.update_text() 264 | return super(SongListItem, self).render(size, focus) 265 | 266 | 267 | class SongListBoxPopup(urwid.LineBox): 268 | """ 269 | Widget that represents context popup for a song item. 270 | """ 271 | signals = ['close'] 272 | 273 | def __init__(self, songitem): 274 | self.songitem = songitem 275 | self.options = [ 276 | urwid.AttrWrap( 277 | urwid.Text(' ' + songitem.full_title), 278 | 'panel' 279 | ), 280 | urwid.AttrWrap( 281 | urwid.Text(' Source: {}'.format(songitem.track.source)), 282 | 'panel_divider' 283 | ), 284 | urwid.AttrWrap( 285 | urwid.Text(' StoreID: {}'.format(songitem.track.store_id)), 286 | 'panel_divider' 287 | ) 288 | ] 289 | 290 | if not gp.get_track_by_id(songitem.track.id): 291 | self._add_item('Add to library', self.add_to_my_library) 292 | else: 293 | self._add_item('Remove from library', self.remove_from_my_library) 294 | 295 | self._add_item('Create station', self.create_station) 296 | 297 | if self.songitem.track in player.get_queue_tracks(): 298 | self._add_item('Remove from queue', self.remove_from_queue) 299 | else: 300 | self._add_item('Append to queue', self.append_to_queue) 301 | 302 | if self.songitem.track.cached_url is not None: 303 | self._add_item('Copy URL to clipboard', self.copy_url) 304 | 305 | self.options.append( 306 | urwid.AttrWrap( 307 | urwid.Button('Close', on_press=self.close), 308 | 'panel', 309 | 'panel_focus')) 310 | 311 | super(SongListBoxPopup, self).__init__( 312 | urwid.Pile(self.options) 313 | ) 314 | 315 | def _add_item(self, name, func): 316 | """ 317 | Add an item to the list with a divider. 318 | 319 | Args: 320 | name (str): The name of the option 321 | func: The function to call afterwards 322 | """ 323 | self.options.append( 324 | urwid.AttrWrap( 325 | urwid.Divider(u'\u2500'), 326 | 'panel_divider', 327 | 'panel_divider_focus')) 328 | 329 | self.options.append( 330 | urwid.AttrWrap( 331 | urwid.Button(name, on_press=func), 332 | 'panel', 333 | 'panel_focus')) 334 | 335 | def add_to_my_library(self, _): 336 | """ 337 | Add related track to my library. 338 | """ 339 | def on_add_to_my_library(result, error): 340 | """ 341 | Show notification with song addition result. 342 | """ 343 | if error or not result: 344 | notification_area.notify('Error while adding track to my library: {}'.format( 345 | str(error) if error else 'reason is unknown :(' 346 | )) 347 | else: 348 | notification_area.notify('Track added to library!') 349 | self.songitem.track.add_to_my_library_async(callback=on_add_to_my_library) 350 | self.close() 351 | 352 | def remove_from_my_library(self, _): 353 | """ 354 | Removes related track to my library. 355 | """ 356 | def on_remove_from_my_library(result, error): 357 | """ 358 | Show notification with song removal result. 359 | """ 360 | if error or not result: 361 | notification_area.notify('Error while removing track from my library: {}'.format( 362 | str(error) if error else 'reason is unknown :(' 363 | )) 364 | else: 365 | notification_area.notify('Track removed from library!') 366 | self.songitem.track.remove_from_my_library_async(callback=on_remove_from_my_library) 367 | self.close() 368 | 369 | def append_to_queue(self, _): 370 | """ 371 | Appends related track to queue. 372 | """ 373 | player.append_to_queue(self.songitem.track) 374 | self.close() 375 | 376 | def remove_from_queue(self, _): 377 | """ 378 | Removes related track from queue. 379 | """ 380 | player.remove_from_queue(self.songitem.track) 381 | self.close() 382 | 383 | def create_station(self, _): 384 | """ 385 | Create a station from this track. 386 | """ 387 | player.create_station_from_track(self.songitem.track) 388 | self.close() 389 | 390 | def copy_url(self, _): 391 | """ 392 | Copy URL to clipboard. 393 | """ 394 | copy(self.songitem.track.cached_url) 395 | self.close() 396 | 397 | def close(self, *_): 398 | """ 399 | Close this menu. 400 | """ 401 | urwid.emit_signal(self, 'close') 402 | 403 | 404 | class SongListBox(urwid.Frame): 405 | """ 406 | Displays :class:`.SongListItem` instances. 407 | """ 408 | signals = ['activate'] 409 | 410 | def __init__(self, app): 411 | self.app = app 412 | 413 | self.current_item = None 414 | self.tracks = [] 415 | self.walker = urwid.SimpleFocusListWalker([]) 416 | 417 | player.track_changed += self.track_changed 418 | player.media_state_changed += self.media_state_changed 419 | 420 | self.list_box = urwid.ListBox(self.walker) 421 | self.filter_prefix = '> ' 422 | self.filter_query = '' 423 | self.filter_box = urwid.Text(self.filter_prefix) 424 | self.filter_info = urwid.Text('') 425 | self.filter_panel = urwid.Columns([ 426 | self.filter_box, 427 | ('pack', self.filter_info) 428 | ]) 429 | self.content = urwid.Pile([ 430 | self.list_box, 431 | ]) 432 | 433 | self.overlay = urwid.Overlay( 434 | top_w=None, 435 | bottom_w=self.content, 436 | align='center', 437 | valign='middle', 438 | width=50, 439 | height='pack' 440 | ) 441 | 442 | self._is_filtering = False 443 | self.popup = None 444 | 445 | super(SongListBox, self).__init__( 446 | body=self.content 447 | ) 448 | 449 | def perform_filtering(self, char): 450 | """ 451 | Enter filtering mode (if not entered yet) and filter stuff. 452 | """ 453 | if not self._is_filtering: 454 | self.content.contents = [ 455 | (self.list_box, ('weight', 1)), 456 | (self.filter_panel, ('pack', None)) 457 | ] 458 | self.app.append_cancel_action(self.end_filtering) 459 | self.filter_query = '' 460 | self._is_filtering = True 461 | 462 | if char == 'backspace': 463 | self.filter_query = self.filter_query[:-1] 464 | else: 465 | self.filter_query += char 466 | self.filter_box.set_text(self.filter_prefix + self.filter_query) 467 | 468 | matches = self.get_filtered_items() 469 | self.filter_info.set_text('{} matches'.format(len(matches))) 470 | if matches: 471 | self.walker.set_focus(matches[0].index) 472 | 473 | def get_filtered_items(self): 474 | """ 475 | Get song items that match the search query. 476 | """ 477 | matches = [] 478 | for songitem in self.walker: 479 | if not isinstance(songitem, SongListItem): 480 | continue 481 | if self.filter_query.lower() in songitem.full_title.lower(): 482 | matches.append(songitem) 483 | return matches 484 | 485 | def end_filtering(self): 486 | """ 487 | Exit filtering mode. 488 | """ 489 | self.content.contents = [ 490 | (self.list_box, ('weight', 1)) 491 | ] 492 | self._is_filtering = False 493 | 494 | def set_placeholder(self, text): 495 | """ 496 | Clear list and add one placeholder item. 497 | """ 498 | self.walker[:] = [urwid.Text(text, align='center')] 499 | 500 | def tracks_to_songlist(self, tracks): 501 | """ 502 | Convert list of track data items into list of :class:`.SongListItem` instances. 503 | """ 504 | current_track = player.get_current_track() 505 | items = [] 506 | current_index = None 507 | for index, track in enumerate(tracks): 508 | songitem = SongListItem(track) 509 | if current_track is not None and current_track == track: 510 | songitem.set_state(SongListItem.STATE_LOADING) 511 | if current_index is None: 512 | current_index = index 513 | urwid.connect_signal( 514 | songitem, 'activate', self.item_activated 515 | ) 516 | 517 | urwid.connect_signal( 518 | songitem, 'play', self.item_play_pause 519 | ) 520 | urwid.connect_signal( 521 | songitem, 'append-requested', self.item_append_requested 522 | ) 523 | urwid.connect_signal( 524 | songitem, 'unappend-requested', self.item_unappend_requested 525 | ) 526 | urwid.connect_signal( 527 | songitem, 'station-requested', self.item_station_requested 528 | ) 529 | urwid.connect_signal( 530 | songitem, 'context-menu-requested', self.context_menu_requested 531 | ) 532 | items.append(songitem) 533 | return (items, current_index) 534 | 535 | def item_play_pause(self, songitem): 536 | """ 537 | Called when you want to start playing a song. 538 | """ 539 | if songitem.is_currently_played: 540 | player.play_pause() 541 | 542 | def item_activated(self, songitem): 543 | """ 544 | Called when specific song item is activated. 545 | Toggles track playback state or loads entire playlist 546 | that contains current track into player queue. 547 | """ 548 | if songitem.is_currently_played: 549 | player.play_pause() 550 | else: 551 | player.load_queue(self.tracks, songitem.index) 552 | 553 | @staticmethod 554 | def item_append_requested(songitem): 555 | """ 556 | Called when specific item emits *append-requested* item. 557 | Appends track to player queue. 558 | """ 559 | player.append_to_queue(songitem.track) 560 | 561 | @staticmethod 562 | def item_unappend_requested(songitem): 563 | """ 564 | Called when specific item emits *remove-requested* item. 565 | Removes track from player queue. 566 | """ 567 | player.remove_from_queue(songitem.track) 568 | 569 | @staticmethod 570 | def item_station_requested(songitem): 571 | """ 572 | Called when specific item emits *station-requested* item. 573 | Requests new station creation. 574 | """ 575 | player.create_station_from_track(songitem.track) 576 | 577 | def context_menu_requested(self, songitem): 578 | """ 579 | Show context menu. 580 | """ 581 | self.popup = SongListBoxPopup(songitem) 582 | self.app.append_cancel_action(self.popup.close) 583 | self.overlay.top_w = self.popup 584 | urwid.connect_signal(self.popup, 'close', self.hide_context_menu) 585 | self.contents['body'] = (self.overlay, None) 586 | 587 | @property 588 | def is_context_menu_visible(self): 589 | """ 590 | Return ``True`` if context menu is currently being shown. 591 | """ 592 | return self.contents['body'][0] is self.overlay 593 | 594 | def hide_context_menu(self): 595 | """ 596 | Hide context menu. 597 | """ 598 | if self.popup is not None and self.is_context_menu_visible: 599 | self.contents['body'] = (self.content, None) 600 | self.app.unregister_cancel_action(self.popup.close) 601 | self.popup = None 602 | 603 | def track_changed(self, track): 604 | """ 605 | Called when new track playback is started. 606 | Marks corresponding song item (if found in this song list) as currently played. 607 | """ 608 | for i, songitem in enumerate(self.walker): 609 | if isinstance(songitem, urwid.Text): 610 | continue 611 | if songitem.track == track: 612 | songitem.set_state(SongListItem.STATE_LOADING) 613 | self.walker.set_focus(i) 614 | elif songitem.state != SongListItem.STATE_IDLE: 615 | songitem.set_state(SongListItem.STATE_IDLE) 616 | 617 | def media_state_changed(self, is_loading, is_playing): 618 | """ 619 | Called when player media state changes. 620 | Updates corresponding song item state (if found in this song list). 621 | """ 622 | current_track = player.get_current_track() 623 | if current_track is None: 624 | return 625 | 626 | for songitem in self.walker: 627 | if isinstance(songitem, urwid.Text): 628 | continue 629 | if songitem.track == current_track: 630 | songitem.set_state( 631 | SongListItem.STATE_LOADING 632 | if is_loading 633 | else SongListItem.STATE_PLAYING 634 | if is_playing 635 | else SongListItem.STATE_PAUSED 636 | ) 637 | self.app.redraw() 638 | 639 | def populate(self, tracks): 640 | """ 641 | Display a list of :class:`clay.player.Track` instances in this song list. 642 | """ 643 | self.tracks = tracks 644 | self.walker[:], current_index = self.tracks_to_songlist(self.tracks) 645 | self.update_indexes() 646 | if current_index is not None: 647 | self.walker.set_focus(current_index) 648 | elif len(self.walker) >= 1: 649 | self.walker.set_focus(0) 650 | 651 | def append_track(self, track): 652 | """ 653 | Convert a track into :class:`.SongListItem` instance and appends it into this song list. 654 | """ 655 | tracks, _ = self.tracks_to_songlist([track]) 656 | self.walker.append(tracks[0]) 657 | self.update_indexes() 658 | 659 | def remove_track(self, track): 660 | """ 661 | Remove a song item that matches *track* from this song list (if found). 662 | """ 663 | for songlistitem in self.walker: 664 | if songlistitem.track == track: 665 | self.walker.remove(songlistitem) 666 | self.update_indexes() 667 | 668 | def update_indexes(self): 669 | """ 670 | Update indexes of all song items in this song list. 671 | """ 672 | for i, songlistitem in enumerate(self.walker): 673 | songlistitem.set_index(i) 674 | 675 | def keypress(self, size, key): 676 | if key in ascii_letters + digits + ' _-.,?!()[]/': 677 | self.perform_filtering(key) 678 | elif key == 'backspace': 679 | self.perform_filtering(key) 680 | elif self._is_filtering: 681 | try: 682 | return hotkey_manager.keypress("library_view", self, super(SongListBox, self), 683 | size, key) 684 | except IndexError: 685 | pass 686 | else: 687 | return super(SongListBox, self).keypress(size, key) 688 | 689 | return None 690 | 691 | def _get_filtered(self): 692 | """Get filtered list of items""" 693 | matches = self.get_filtered_items() 694 | _, index = self.walker.get_focus() 695 | return (matches, index) 696 | 697 | def move_to_beginning(self): 698 | """Move to the focus to beginning of the songlist""" 699 | matches, _ = self._get_filtered() 700 | self.list_box.set_focus(matches[0].index, 'below') 701 | return False 702 | 703 | def move_to_end(self): 704 | """Move to the focus to end of the songlist""" 705 | matches, _ = self._get_filtered() 706 | self.list_box.set_focus(matches[-1].index, 'above') 707 | return False 708 | 709 | def move_up(self): 710 | """Move the focus an item up in the playlist""" 711 | matches, index = self._get_filtered() 712 | self.list_box.set_focus(*self.get_item(matches, index, lt)) 713 | return False 714 | 715 | def move_down(self): 716 | """Move the focus an item down in the playlist """ 717 | matches, index = self._get_filtered() 718 | self.list_box.set_focus(*self.get_item(matches, index, gt)) 719 | return False 720 | 721 | @staticmethod 722 | def get_item(matches, current_index, callback): 723 | """ 724 | Get an item index from the matches list 725 | """ 726 | # Some not so very nice code to get to be nice and generic 727 | order = ['above', 'below'] 728 | if callback is lt: 729 | order.reverse() 730 | 731 | items = [item for item in matches if callback(item.index, current_index)] 732 | 733 | # Please witness some terrible code below. 734 | 735 | index = -1 if callback is lt else 0 736 | 737 | if items: 738 | return items[index].index, order[0] 739 | return matches[index].index, order[1] 740 | 741 | def mouse_event(self, size, event, button, col, row, focus): 742 | """ 743 | Handle mouse event. 744 | """ 745 | if button == 4: 746 | self.keypress(size, 'up') 747 | elif button == 5: 748 | self.keypress(size, 'down') 749 | else: 750 | super(SongListBox, self).mouse_event(size, event, button, col, row, focus) 751 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------