Compare commits

...

132 Commits

Author SHA1 Message Date
warwickh 4fffcd143e
Merge pull request #47 from GioF71/feature/search-album
[Feature] Search Album
2023-02-03 08:25:49 +11:00
Giovanni Fulco e59b65d5e0
[Feature] Search Album 2023-02-02 19:43:09 +01:00
warwickh fa0c4ec165 Update repo link 2022-09-18 18:39:33 +10:00
warwickh 2c785729ee
Merge pull request #43 from BlackIkeEagle/collections-abc-import
also use collections.abc in simpleplugin to import MutableMapping
2022-03-05 16:12:22 +11:00
BlackEagle d11505bd04 also use collections.abc in simpleplugin to import MutableMapping
Signed-off-by: BlackEagle <ike.devolder@gmail.com>
2022-03-03 22:40:02 +01:00
warwickh d221fa4f39
Resolved incorrect repo link 2022-01-30 16:25:47 +11:00
warwickh ec86d2abdd Modify separator for verifypeer 2022-01-28 11:09:11 +11:00
warwickh b9a556eded Handle subfolder in server setting 2021-10-11 12:50:10 +11:00
warwickh 4e15a1d0d3
Update addon.xml for v3.0.2 2021-09-28 16:06:38 +10:00
warwickh 1295d078e5
Update readme for v3.0.2 2021-09-28 09:16:33 +10:00
warwickh 4b1e0ad104
Update changelog for v3.0.2 2021-09-28 09:13:44 +10:00
warwickh 7baa12f06f remove future and dateutil dependency 2021-09-28 09:05:01 +10:00
warwickh f97b9e1de9 Don't start service if scrobbling switched off 2021-09-10 09:24:48 +10:00
warwickh 8ca52e6cc8
Resolve merge conflict 2021-09-09 18:04:37 +10:00
Warwick Harris c4c0aa00c6 Merge scrobble to master 2021-09-09 18:01:32 +10:00
Warwick Harris 67bd25496e Testing when setting doesn't exist 2021-09-09 12:10:43 +10:00
warwickh 0932e650f8 Notify service start 2021-09-09 11:48:06 +10:00
Warwick Harris 57141eed02 Merge branch 'scrobble' of github.com:warwickh/plugin.audio.subsonic into scrobble 2021-09-09 09:40:37 +10:00
Warwick Harris 2335973433 Some error fixes 2021-09-09 09:40:18 +10:00
warwickh 150b5012da
Update readme to include scrobbling 2021-09-08 17:00:23 +10:00
warwickh 8c4f31db05 More efficient settings and return value 2021-09-08 16:47:08 +10:00
warwickh 596ddaacdb First working scrobble service 2021-09-08 16:25:36 +10:00
warwickh c25e5848cf
Update settings for merge default 2021-09-07 17:01:24 +10:00
warwickh 469681bf5e Add insecure fix - still needs correct hostname 2021-09-07 15:29:59 +10:00
warwickh ced597b6d2
Update changelog for v3.0.1 2021-09-06 10:55:20 +10:00
warwickh 03da132550 Added option for merging albums in browse mode 2021-09-05 15:13:23 +10:00
warwickh 742c5b66fc Working with random update, need to format info better 2021-09-05 14:34:41 +10:00
warwickh 640157dad0 Added artist info - first working 2021-09-04 16:40:44 +10:00
warwickh 56dffe70bc Added artist info - some errors remaining 2021-09-04 16:00:49 +10:00
warwickh 34a7c249be
Update settings string 2021-09-04 14:13:08 +10:00
warwickh 67d2302bc4 Update installation details in readme 2021-09-04 10:23:26 +10:00
warwickh 9fbb67cc3c
Update readme with repo details 2021-09-03 18:35:39 +10:00
warwickh 0ac9d36187
Update readme to include repository zip 2021-09-03 18:34:06 +10:00
warwickh 49754bccaa
Update version number 2021-09-03 13:05:07 +10:00
warwickh 358df44fb1 Cleanup and prepare for merge 2021-09-02 16:54:48 +10:00
Warwick Harris a551df5c8c Clean up deprecation warnings and add some logging to resolve http client timeout 2021-09-02 12:56:34 +10:00
warwickh e640d0f81d
Update Readme to include Navidrome compatibility 2021-08-31 09:22:18 +10:00
warwickh 3aac9d1c54
Change to use GET as default 2021-08-31 09:16:03 +10:00
Warwick Harris 7564e75f63 Catch empty star response 2021-08-31 08:52:05 +10:00
Warwick Harris ed3f7da8b5 Remove dependency for integer ids to suit Navidrome requirement 2021-08-30 16:42:28 +10:00
warwickh 194844571c Fix ndent 2021-07-02 18:12:01 +10:00
warwickh 6035ff49b8 Avoid errors in walk functions 2021-07-02 17:37:44 +10:00
warwickh bc30d36466 Correct fanart path in addon.xml 2021-07-02 08:57:04 +10:00
gordielachance 445303a2fc
Merge pull request #30 from warwickh/master
Merge Matrix compatible to master
2021-06-30 11:13:38 +02:00
warwickh 2d76c74f42 All logging to LOGDEBUG 2021-06-29 20:28:48 +10:00
warwickh a7f74582de Add fanart 2021-06-29 20:05:09 +10:00
warwickh 41a747a2b7 Add fanart 2021-06-29 20:02:35 +10:00
warwickh 2e5d012cae Add fanart 2021-06-29 20:01:30 +10:00
warwickh 53ecd6e5d1 Add fanart 2021-06-29 19:56:16 +10:00
warwickh 2efa209227
Clean up main.py 2021-06-29 15:47:38 +10:00
warwickh 1703d433a3 Move Matrix compatible version to 3.0.0 2021-06-29 14:47:07 +10:00
warwickh 17f77aca93
Change layout 2021-06-29 14:42:03 +10:00
warwickh a136a7b47e
Change layout 2021-06-29 14:40:26 +10:00
warwickh b461af0269
Change layout 2021-06-29 14:39:39 +10:00
warwickh bf1ee6bd1b
Update installation instructions 2021-06-29 14:39:16 +10:00
warwickh 79a9b1ebc3
Updated simpleplugin link 2021-06-29 14:32:53 +10:00
warwickh 46da611895
Update contact information 2021-06-29 14:14:58 +10:00
warwickh d524b8cc8e
set version for script.module.future 2021-06-29 14:14:07 +10:00
warwickh 0ddda4676c
Added requirement for script.module.future 2021-06-29 07:38:03 +10:00
warwickh 1d22cd75c1
Update settings.xml 2021-06-28 19:26:44 +10:00
warwickh 1fc06bd790 Add api version 1.16.0 2021-06-28 19:21:36 +10:00
warwickh e958c5bb2a Stream and coverart requests assume url request and add useget by default in connection 2021-06-28 19:07:56 +10:00
warwickh 9d86ff2051 Readd some logging for stream auth 2021-06-28 17:59:22 +10:00
warwickh 71e208b662
Need to check why useget required for streaming 2021-06-28 17:51:27 +10:00
warwickh 6910755b36
Update settings.xml
Ensure default bitrate
2021-06-28 17:41:01 +10:00
warwickh aca6ad6e83
Change port storage to text 2021-06-28 16:50:21 +10:00
warwickh adc78f9783 Clean up some logging 2021-06-28 15:47:08 +10:00
warwickh 0c32547c0d Update readme 2021-06-28 15:40:33 +10:00
warwickh 67b5e4ab8c Update readme 2021-06-28 15:13:17 +10:00
warwickh 861e7534c6 Fix connection port issue 2021-06-28 14:55:56 +10:00
warwickh c65548a73b Fix empty folder crash 2021-06-28 14:06:59 +10:00
warwickh f5202f2229 Restore notes against TO FIX items 2021-06-23 09:56:28 +10:00
warwickh 2b3789fe5c Fix browse function 2021-06-22 18:25:52 +10:00
warwickh 92356ab533 2.0.9 2021-06-22 16:47:09 +10:00
warwickh 1d3181fe4e Initial Matrix Compatible commit 2021-06-22 16:35:39 +10:00
gordielachance 577181bb73
Merge pull request #20 from gordielachance/2.0.8
2 0 8
2017-12-04 11:35:04 +01:00
gordielachance f0649bf2b5
Fix missing DE translation for "Search" 2017-12-03 18:32:32 +01:00
gordielachance b630801150
Merge pull request #19 from comxd/patch-1
Fix missing FR translation for "Search"
2017-12-03 18:30:06 +01:00
David 99d57fa1f9
Fix missing FR translation for "Search"
@see commit #9e7e542585eb67392fad3191f44a973c0e59839f
2017-12-03 18:16:21 +01:00
gordielachance f7ccef89ef 2.0.8 2017-11-29 11:30:58 +01:00
gordielachance d90af02d8b
Merge pull request #18 from Heruwar/feature/path-support_and_pw-improvements
Path support and security improvements
2017-11-29 11:09:56 +01:00
heru 4429451454 Dont sent plaintext password in requests and use subsonic hex-encoding with legacy auth 2017-11-25 18:15:12 +01:00
heru 313b413fc5 Add support for path in server URL 2017-11-25 18:13:44 +01:00
heru 30d0e8641e Make sure password and username are always strings 2017-11-25 18:12:53 +01:00
gordielachance b18b8e0094 Update addon.xml 2017-04-18 15:26:34 +02:00
gordielachance 66ae5ee093 Update CHANGELOG.md 2017-04-18 15:25:20 +02:00
gordielachance 426dcf964f Merge pull request #16 from silascutler/master
Added Search
2017-04-18 15:19:10 +02:00
Silas Cutler ce58b6993f Updates 2017-04-02 12:12:49 -04:00
Silas Cutler f51e5c3c28 Removed pop-up option 2017-04-02 11:44:22 -04:00
Silas Cutler e966b5bfa2 Removed pop-up option 2017-04-02 11:44:14 -04:00
Silas Cutler 9e7e542585 Added Search 2017-04-02 09:06:49 -04:00
gordielachance 10bb432a14 Merge pull request #12 from gordielachance/media-folders
Media folders
2017-01-14 12:47:36 +01:00
rickybiscus e6b00afc27 version update 2017-01-14 12:38:50 +01:00
rickybiscus 60ebe928b0 minor 2017-01-10 18:36:34 +01:00
rickybiscus 2482e56fdc minor 2017-01-09 11:36:23 +01:00
rickybiscus 290fa837b3 simpleplugin 2.1.0 2017-01-09 11:01:41 +01:00
rickybiscus 0344163cd5 typo 2017-01-09 10:50:00 +01:00
rickybiscus 3a0efadebb use Addon().get_localized_string (simpleplugin) 2017-01-09 10:48:30 +01:00
rickybiscus 8c2ffe006c localized strings : settings typo 2017-01-09 10:46:24 +01:00
rickybiscus ebf82b8218 fixes for localized strings 2017-01-09 10:46:11 +01:00
rickybiscus d9a18d41e3 reorganize code 2017-01-09 10:45:12 +01:00
rickybiscus c6e9cc92e8 Browse/Library menus (file structure vs ID3 tags) 2017-01-09 01:02:37 +01:00
rickybiscus 3ed7b231cc if there is only one media folder, return list_indexes() directly 2017-01-08 11:35:53 +01:00
rickybiscus 7d26333ce0 WIP : list_indexes function (not working yet) 2017-01-08 11:11:05 +01:00
rickybiscus d9210dcaef new 'Browse' top menu to list media folders 2017-01-08 11:09:54 +01:00
gordielachance 0cda25e07a Merge pull request #9 from Moshkopp/patch-2
german description.
2017-01-03 23:19:38 +01:00
Moshkopp be07844e38 german description. 2017-01-03 22:56:07 +01:00
rickybiscus 5484614cc1 typo 2017-01-03 22:07:47 +01:00
rickybiscus 7e67edd64a removed some strings
+ typos
+ changelog
2017-01-03 21:14:00 +01:00
rickybiscus 8ce871a9f7 typo 2017-01-03 20:54:51 +01:00
rickybiscus 3acb61d605 french translation 2017-01-03 20:40:08 +01:00
gordielachance c621458704 Merge pull request #7 from Moshkopp/master
Added multilanguage support
2017-01-03 20:14:41 +01:00
Moshkopp aaac00f69a Update strings.po 2016-12-28 18:13:22 +01:00
Moshkopp afea46a9e1 Add files via upload
typo
2016-12-28 18:12:29 +01:00
Moshkopp fb64a2e6fe Delete strings.po 2016-12-28 18:12:03 +01:00
Moshkopp a029490fe8 Add files via upload
typo
2016-12-28 18:10:05 +01:00
Moshkopp 4a057ba83c Add files via upload
Added multilanguage support
2016-12-28 14:33:26 +01:00
rickybiscus ef6ba710e2 doc 2016-10-15 01:33:55 +02:00
rickybiscus 4179ca8ada Fixed images when listing entries 2016-10-15 01:33:43 +02:00
rickybiscus fcbcccaeb9 doc 2016-10-15 01:27:12 +02:00
gordielachance fcfee371f8 doc 2016-10-04 17:13:00 +02:00
gordielachance 68a8fec4f8 try to fix https://github.com/gordielachance/plugin.audio.subsonic/issues/2 2016-10-04 17:08:05 +02:00
gordielachance 2285d5ca0b minor 2016-10-04 16:56:36 +02:00
gordielachance 537524d7fe fix simpleplugin dependency (finally!) 2016-10-04 16:56:29 +02:00
gordielachance 3cb2bc702b doc 2016-10-04 15:16:46 +02:00
gordielachance b66129b448 temporary disable sorting stuff 2016-10-04 15:13:57 +02:00
gordielachance 8bbeabc0dc removed list_artist_albums() + colorize starred items labels 2016-10-04 15:12:06 +02:00
gordielachance 5117218f86 hide artist in lists if it is unique 2016-10-04 14:57:24 +02:00
gordielachance f80b6458a1 improved Sort by 2016-10-04 14:47:01 +02:00
gordielachance 8bae5abd88 new function get_track_entry_label() 2016-10-04 12:53:53 +02:00
gordielachance c026d31836 better stars/unstar code
now update/get a stars (persistent) cache to handle the starred items
2016-10-04 12:45:01 +02:00
gordielachance f905da4f43 better import modules 2016-10-04 11:15:12 +02:00
24 changed files with 3448 additions and 4802 deletions

View File

@ -1,5 +1,52 @@
# Changelog
## v3.0.2
Released 29th September 2021 (by warwickh)
* Removed dependency on future and dateutil
* Simpleplugin modified - no longer py2 compatible
## v3.0.1
Released 2nd September 2021 (by warwickh)
* Added Navidrome compatibility (remove dependency on integer ids)
## v3.0.0
Released 29th June 2021 (by warwickh)
* Basic update to provide Matrix compatility. Not tested on Kodi below v19
* Updates simpleplugin to latest version (3.0.0) https://github.com/vlmaksime/script.module.simpleplugin
* Moves some legacy simpleplugin static routines into main.py
* Removes dependancy on libsonic_extra by moving some walk functions into main.py
* Updates libsonic to latest version and adds functions for returning raw url for populating menus
* Move to version 3+ for diffferentiation from Leia compatible version
## v2.0.8
Released 29th November 2017 (by Heruwar)
* Fixes a security issue where the password is sent as plaintext in the URL query parameters when methods from libsonic_extas are used.
Also adds Subsonic hex encoding when using legacy auth.
* Adds support for URL paths like https://hostname.com/subsonic as requested in Github issue #17 and also encountered in some of the reports (#14 and #5)
* Fixes an error when the password only contains digits, which simpleplugin converts to a Long, which later fails when libsonic tries to salt the password expecting a string.
## v2.0.7
Released 18 April 2017
* Added Search (by silascutler)
## v2.0.6
Released 14 January 2017
* Upgrade to simpleplugin 2.1.0
* Browse/Library menus (file structure vs ID3 tags)
* Added multilanguage support
## v2.0.5
Released 15 October 2016
* Fixed images when listing entries
## v2.0.4
Released 5 October 2016
* Cache (permanently) starred items so we can know everywhere if an item is starred or not without querying it
* Colorize starred items
* Hide artist in lists if it is unique
* Removed list_artist_albums()
* Include simpleplugin v2.0.1 as library and remove KODI dependency
## v2.0.3
Released 4 October 2016
* Random tracks submenu

View File

@ -1,23 +1,39 @@
# Subsonic
Kodi plugin to stream, star and download music from Subsonic.
Kodi plugin to stream, star and download music from Subsonic/Airsonic/Navidrome (requires Subsonic API compatibility)
For feature requests / issues:
https://github.com/gordielachance/plugin.audio.subsonic/issues
https://github.com/warwickh/plugin.audio.subsonic/issues
Contributions are welcome:
https://github.com/gordielachance/plugin.audio.subsonic
https://github.com/warwickh/plugin.audio.subsonic
Master branch updated to support Kodi 19 Matrix
Leia compatible version available in alternate branch
## Features
* Browse by artist, albums (newest/most played/recently played/random), tracks (starred/random), and playlists
* Download songs
* Star songs
* Navidrome compatibility added (please report any issues)
* Scrobble to Last.FM
## Installation
From repository
[repository.warwickh](https://github.com/warwickh/repository.warwickh/raw/master/matrix/zips/repository.warwickh) (Please report any issues)
From GitHub
* Click the code button and download
* Enable unknown sources and install from zip in Kodi
or
* Navigate to your `.kodi/addons/` folder
* Clone this repository: `git clone https://github.com/gordielachance/plugin.audio.subsonic.git`
* Install the SimplePlugin dependency by cloning its repository: `git clone https://github.com/romanvm/script.module.simpleplugin.git`
* Clone this repository: `git clone https://github.com/warwickh/plugin.audio.subsonic.git`
* (Re)start Kodi.
Note: You will need to enter your server settings into the plugin configuration before use
## TODO
* Scrobble to Last.FM (http://forum.kodi.tv/showthread.php?tid=195597&pid=2429362#pid2429362)
* Improve the caching system
* Search filter GUI for tracks and albums
@ -25,7 +41,8 @@ https://github.com/gordielachance/plugin.audio.subsonic
See the `LICENSE` file.
Additional copyright notices:
* [Previous version of this plugin](https://github.com/gordielachance/plugin.audio.subsonic) by gordielachance
* [Previous version of this plugin](https://github.com/basilfx/plugin.audio.subsonic) by basilfx
* [SimplePlugin](https://github.com/romanvm/script.module.simpleplugin/stargazers) by romanvm
* [SimplePlugin](https://github.com/romanvm/script.module.simpleplugin/stargazers) by romanvm now at [SimplePlugin3](https://github.com/vlmaksime/script.module.simpleplugin)
* The original [SubKodi](https://github.com/DarkAllMan/SubKodi) plugin
* [`py-sonic`](https://github.com/crustymonkey/py-sonic) Python module

View File

@ -1,29 +1,48 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<addon id="plugin.audio.subsonic" name="Subsonic" version="2.0.3" provider-name="BasilFX,grosbouff,lrusak">
<requires>
<import addon="xbmc.python" version="2.14.0"/>
<import addon="script.module.dateutil" version="2.4.2"/>
<import addon="script.module.simpleplugin" version="2.0.1"/>
</requires>
<extension point="xbmc.python.pluginsource" library="main.py">
<provides>audio</provides>
</extension>
<addon id="plugin.audio.subsonic" name="Subsonic" version="3.0.2" provider-name="BasilFX,warwickh">
<requires>
<import addon="xbmc.python" version="3.0.0"/>
</requires>
<extension point="xbmc.python.pluginsource" library="main.py">
<provides>audio</provides>
</extension>
<extension point="xbmc.service" library="service.py" />
<extension point="xbmc.addon.metadata">
<summary lang="en">Subsonic music addon for Kodi.</summary>
<summary lang="fr">Extension Subsonic pour Kodi.</summary>
<summary lang="de">Subsonic Musik Addon für Kodi.</summary>
<description lang="en">
Stream, star and download your tunes, directly to Kodi !
For feature requests / issues:
https://github.com/gordielachance/plugin.audio.subsonic/issues
https://github.com/warwickh/plugin.audio.subsonic/issues
Contributions are welcome:
https://github.com/gordielachance/plugin.audio.subsonic
https://github.com/warwickh/plugin.audio.subsonic
</description>
<description lang="fr">
Jouez, marquez vos favoris et téléchargez votre musique, directement dans Kodi !
Pour les demandes et problèmes :
https://github.com/warwickh/plugin.audio.subsonic/issues
Les contributions sont les bienvenues :
https://github.com/warwickh/plugin.audio.subsonic
</description>
<description lang="de">
Streame, bewerte und downloade deine Medien direkt in Kodi !
Für neue Eigentschaften oder Fehler:
https://github.com/warwickh/plugin.audio.subsonic/issues
Beihilfe ist Willkommen:
https://github.com/warwickh/plugin.audio.subsonic
</description>
<assets>
<icon>icon.png</icon>
<fanart>fanart.jpg</fanart>
</assets>
<disclaimer lang="en"></disclaimer>
<language>en</language>
<language>multi</language>
<platform>all</platform>
<license>MIT</license>
<forum></forum>
<website>http://www.subsonic.org</website>
<source>https://github.com/gordielachance/plugin.audio.subsonic</source>
<source>https://github.com/warwickh/plugin.audio.subsonic</source>
<email></email>
</extension>
</addon>

BIN
fanart.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 124 KiB

View File

@ -1,32 +1,24 @@
"""
This file is part of py-sonic.
py-sonic is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
py-sonic is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with py-sonic. If not, see <http://www.gnu.org/licenses/>
For information on method calls, see 'pydoc libsonic.connection'
----------
Basic example:
----------
import libsonic
conn = libsonic.Connection('http://localhost' , 'admin' , 'password')
print conn.ping()
"""
from connection import *
from .connection import *
__version__ = '0.6.2'
__version__ = '0.7.9'

View File

@ -15,23 +15,29 @@ You should have received a copy of the GNU General Public License
along with py-sonic. If not, see <http://www.gnu.org/licenses/>
"""
from urllib import urlencode
from .errors import *
from pprint import pprint
from cStringIO import StringIO
from libsonic.errors import *
from netrc import netrc
from hashlib import md5
import json, urllib2, httplib, logging, socket, ssl, sys, os
import urllib.request
import urllib.error
import urllib.parse
from http import client as http_client
from urllib.parse import urlencode
from io import StringIO
API_VERSION = '1.14.0'
import json
import logging
import socket
import ssl
import sys
import os
import xbmc
API_VERSION = '1.16.1'
logger = logging.getLogger(__name__)
class HTTPSConnectionChain(httplib.HTTPSConnection):
_preferred_ssl_protos = sorted([ p for p in dir(ssl)
if p.startswith('PROTOCOL_') ], reverse=True)
_ssl_working_proto = None
class HTTPSConnectionChain(http_client.HTTPSConnection):
def _create_sock(self):
sock = socket.create_connection((self.host, self.port), self.timeout)
if self._tunnel_host:
@ -40,38 +46,21 @@ class HTTPSConnectionChain(httplib.HTTPSConnection):
return sock
def connect(self):
if self._ssl_working_proto is not None:
# If we have a working proto, let's use that straight away
logger.debug("Using known working proto: '%s'",
self._ssl_working_proto)
sock = self._create_sock()
self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file,
ssl_version=self._ssl_working_proto)
return
sock = self._create_sock()
try:
self.sock = self._context.wrap_socket(sock,
server_hostname=self.host)
except:
sock.close()
# Try connecting via the different SSL protos in preference order
for proto_name in self._preferred_ssl_protos:
sock = self._create_sock()
proto = getattr(ssl, proto_name, None)
try:
self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file,
ssl_version=proto)
except:
sock.close()
else:
# Cache the working ssl version
HTTPSConnectionChain._ssl_working_proto = proto
break
class HTTPSHandlerChain(urllib2.HTTPSHandler):
class HTTPSHandlerChain(urllib.request.HTTPSHandler):
def https_open(self, req):
return self.do_open(HTTPSConnectionChain, req)
return self.do_open(HTTPSConnectionChain, req, context=self._context)
# install opener
urllib2.install_opener(urllib2.build_opener(HTTPSHandlerChain()))
urllib.request.install_opener(urllib.request.build_opener(HTTPSHandlerChain()))
class PysHTTPRedirectHandler(urllib2.HTTPRedirectHandler):
class PysHTTPRedirectHandler(urllib.request.HTTPRedirectHandler):
"""
This class is used to override the default behavior of the
HTTPRedirectHandler, which does *not* redirect POST data
@ -81,24 +70,30 @@ class PysHTTPRedirectHandler(urllib2.HTTPRedirectHandler):
if (code in (301, 302, 303, 307) and m in ("GET", "HEAD")
or code in (301, 302, 303) and m == "POST"):
newurl = newurl.replace(' ', '%20')
newheaders = dict((k, v) for k, v in req.headers.items()
newheaders = dict((k, v) for k, v in list(req.headers.items())
if k.lower() not in ("content-length", "content-type")
)
data = None
if req.has_data():
data = req.get_data()
return urllib2.Request(newurl,
if req.data:
data = req.data
return urllib.request.Request(newurl,
data=data,
headers=newheaders,
origin_req_host=req.get_origin_req_host(),
origin_req_host=req.origin_req_host,
unverifiable=True)
else:
raise urllib2.HTTPError(req.get_full_url(), code, msg, headers, fp)
raise urllib.error.HTTPError(
req.get_full_url(),
code,
msg,
headers,
fp,
)
class Connection(object):
def __init__(self, baseUrl, username=None, password=None, port=4040,
serverPath='/rest', appName='py-sonic', apiVersion=API_VERSION,
insecure=False, useNetrc=None, legacyAuth=False, useGET=False):
insecure=False, useNetrc=None, legacyAuth=False, useGET=True):
"""
This will create a connection to your subsonic server
@ -160,8 +155,18 @@ class Connection(object):
request. This is not recommended as request
URLs can get very long with some API calls
"""
self._baseUrl = baseUrl
self._hostname = baseUrl.split('://')[1].strip()
self._baseUrl = baseUrl.rstrip('/')
self._hostname = self._baseUrl.split('://')[1]
if len(self._hostname.split('/'))>1:
print(len(self._hostname.split('/')))
xbmc.log("Got a folder %s"%(self._hostname.split('/')[1]),xbmc.LOGDEBUG)
parts = urllib.parse.urlparse(self._baseUrl)
self._baseUrl = "%s://%s" % (parts.scheme, parts.hostname)
self._hostname = parts.hostname
self._serverPath = parts.path.strip('/') + '/rest'
else:
self._serverPath = serverPath.strip('/')
self._username = username
self._rawPass = password
self._legacyAuth = legacyAuth
@ -178,7 +183,6 @@ class Connection(object):
self._port = int(port)
self._apiVersion = apiVersion
self._appName = appName
self._serverPath = serverPath.strip('/')
self._insecure = insecure
self._opener = self._getOpener(self._username, self._rawPass)
@ -236,9 +240,11 @@ class Connection(object):
viewName = '%s.view' % methodName
req = self._getRequest(viewName)
xbmc.log("Pinging %s"%str(req.full_url),xbmc.LOGDEBUG)
try:
res = self._doInfoReq(req)
except:
except Exception as e:
print("Ping failed %s"%e)
return False
if res['status'] == 'ok':
return True
@ -271,6 +277,52 @@ class Connection(object):
self._checkStatus(res)
return res
def getScanStatus(self):
"""
since: 1.15.0
returns the current status for media library scanning.
takes no extra parameters.
returns a dict like the following:
{'status': 'ok', 'version': '1.15.0',
'scanstatus': {'scanning': true, 'count': 4680}}
'count' is the total number of items to be scanned
"""
methodName = 'getScanStatus'
viewName = '%s.view' % methodName
req = self._getRequest(viewName)
res = self._doInfoReq(req)
self._checkStatus(res)
return res
def startScan(self):
"""
since: 1.15.0
Initiates a rescan of the media libraries.
Takes no extra parameters.
returns a dict like the following:
{'status': 'ok', 'version': '1.15.0',
'scanstatus': {'scanning': true, 'count': 0}}
'scanning' changes to false when a scan is complete
'count' starts a 0 and ends at the total number of items scanned
"""
methodName = 'startScan'
viewName = '%s.view' % methodName
req = self._getRequest(viewName)
res = self._doInfoReq(req)
self._checkStatus(res)
return res
def getMusicFolders(self):
"""
since: 1.0.0
@ -344,7 +396,7 @@ class Connection(object):
artists for the given folder ID from
the getMusicFolders call
ifModifiedSince:int If specified, return a result if the artist
collection has changed since the given
collection has changed since the given
unix timestamp
Returns a dict like the following:
@ -809,6 +861,59 @@ class Connection(object):
self._checkStatus(res)
return res
def streamUrl(self, sid, maxBitRate=0, tformat=None, timeOffset=None,
size=None, estimateContentLength=False, converted=False):
"""
since: 1.0.0
Downloads a given music file.
sid:str The ID of the music file to download.
maxBitRate:int (since: 1.2.0) If specified, the server will
attempt to limit the bitrate to this value, in
kilobits per second. If set to zero (default), no limit
is imposed. Legal values are: 0, 32, 40, 48, 56, 64,
80, 96, 112, 128, 160, 192, 224, 256 and 320.
tformat:str (since: 1.6.0) Specifies the target format
(e.g. "mp3" or "flv") in case there are multiple
applicable transcodings (since: 1.9.0) You can use
the special value "raw" to disable transcoding
timeOffset:int (since: 1.6.0) Only applicable to video
streaming. Start the stream at the given
offset (in seconds) into the video
size:str (since: 1.6.0) The requested video size in
WxH, for instance 640x480
estimateContentLength:bool (since: 1.8.0) If set to True,
the HTTP Content-Length header
will be set to an estimated
value for trancoded media
converted:bool (since: 1.14.0) Only applicable to video streaming.
Subsonic can optimize videos for streaming by
converting them to MP4. If a conversion exists for
the video in question, then setting this parameter
to "true" will cause the converted video to be
returned instead of the original.
Returns the file-like object for reading or raises an exception
on error
"""
methodName = 'stream'
viewName = '%s.view' % methodName
q = self._getQueryDict({'id': sid, 'maxBitRate': maxBitRate,
'format': tformat, 'timeOffset': timeOffset, 'size': size,
'estimateContentLength': estimateContentLength,
'converted': converted})
req = self._getRequest(viewName, q)
#xbmc.log("Requesting %s"%str(req.full_url),xbmc.LOGDEBUG)
return_url = req.full_url
if self._insecure:
return_url += '&verifypeer=false'
xbmc.log("Request is insecure %s"%return_url,level=xbmc.LOGDEBUG)
return return_url
def getCoverArt(self, aid, size=None):
"""
since: 1.0.0
@ -832,6 +937,32 @@ class Connection(object):
self._checkStatus(res)
return res
def getCoverArtUrl(self, aid, size=None):
"""
since: 1.0.0
Returns a cover art image
aid:str ID string for the cover art image to download
size:int If specified, scale image to this size
Returns the file-like object for reading or raises an exception
on error
"""
methodName = 'getCoverArt'
viewName = '%s.view' % methodName
q = self._getQueryDict({'id': aid, 'size': size})
req = self._getRequest(viewName, q)
#xbmc.log("Requesting %s"%str(req.full_url),xbmc.LOGDEBUG)
return_url = req.full_url
if self._insecure:
return_url += '&verifypeer=false'
xbmc.log("Request is insecure %s"%return_url,level=xbmc.LOGDEBUG)
return return_url
def scrobble(self, sid, submission=True, listenTime=None):
"""
since: 1.5.0
@ -980,7 +1111,7 @@ class Connection(object):
streamRole=True, jukeboxRole=False, downloadRole=False,
uploadRole=False, playlistRole=False, coverArtRole=False,
commentRole=False, podcastRole=False, shareRole=False,
musicFolderId=None):
videoConversionRole=False, musicFolderId=None):
"""
since: 1.1.0
@ -1011,6 +1142,7 @@ class Connection(object):
'uploadRole': uploadRole, 'playlistRole': playlistRole,
'coverArtRole': coverArtRole, 'commentRole': commentRole,
'podcastRole': podcastRole, 'shareRole': shareRole,
'videoConversionRole': videoConversionRole,
'musicFolderId': musicFolderId
})
@ -1024,7 +1156,7 @@ class Connection(object):
streamRole=True, jukeboxRole=False, downloadRole=False,
uploadRole=False, playlistRole=False, coverArtRole=False,
commentRole=False, podcastRole=False, shareRole=False,
musicFolderId=None, maxBitRate=0):
videoConversionRole=False, musicFolderId=None, maxBitRate=0):
"""
since 1.10.1
@ -1056,6 +1188,7 @@ class Connection(object):
'uploadRole': uploadRole, 'playlistRole': playlistRole,
'coverArtRole': coverArtRole, 'commentRole': commentRole,
'podcastRole': podcastRole, 'shareRole': shareRole,
'videoConversionRole': videoConversionRole,
'musicFolderId': musicFolderId, 'maxBitRate': maxBitRate
})
req = self._getRequest(viewName, q)
@ -1874,6 +2007,7 @@ class Connection(object):
q['musicFolderId'] = musicFolderId
req = self._getRequest(viewName, q)
xbmc.log("Requesting %s"%str(req.full_url),xbmc.LOGDEBUG)
res = self._doInfoReq(req)
self._checkStatus(res)
return res
@ -1960,7 +2094,7 @@ class Connection(object):
req = self._getRequest(viewName, q)
try:
res = self._doBinReq(req)
except urllib2.HTTPError:
except urllib.error.HTTPError:
# Avatar is not set/does not exist, return None
return None
if isinstance(res, dict):
@ -2065,7 +2199,7 @@ class Connection(object):
musicFolderId:int Only return results from the music folder
with the given ID. See getMusicFolders
"""
methodName = 'getGenres'
methodName = 'getSongsByGenre'
viewName = '%s.view' % methodName
q = self._getQueryDict({'genre': genre,
@ -2112,7 +2246,7 @@ class Connection(object):
req = self._getRequest(viewName, q)
try:
res = self._doBinReq(req)
except urllib2.HTTPError:
except urllib.error.HTTPError:
# Avatar is not set/does not exist, return None
return None
if isinstance(res, dict):
@ -2224,6 +2358,70 @@ class Connection(object):
self._checkStatus(res)
return res
def createInternetRadioStation(self, streamUrl, name, homepageUrl=None):
"""
since 1.16.0
Create an internet radio station
streamUrl:str The stream URL for the station
name:str The user-defined name for the station
homepageUrl:str The homepage URL for the station
"""
methodName = 'createInternetRadioStation'
viewName = '{}.view'.format(methodName)
q = self._getQueryDict({
'streamUrl': streamUrl, 'name': name, 'homepageUrl': homepageUrl})
req = self._getRequest(viewName, q)
res = self._doInfoReq(req)
self._checkStatus(res)
return res
def updateInternetRadioStation(self, iid, streamUrl, name,
homepageUrl=None):
"""
since 1.16.0
Create an internet radio station
iid:str The ID for the station
streamUrl:str The stream URL for the station
name:str The user-defined name for the station
homepageUrl:str The homepage URL for the station
"""
methodName = 'updateInternetRadioStation'
viewName = '{}.view'.format(methodName)
q = self._getQueryDict({
'id': iid, 'streamUrl': streamUrl, 'name': name,
'homepageUrl': homepageUrl,
})
req = self._getRequest(viewName, q)
res = self._doInfoReq(req)
self._checkStatus(res)
return res
def deleteInternetRadioStation(self, iid):
"""
since 1.16.0
Create an internet radio station
iid:str The ID for the station
"""
methodName = 'deleteInternetRadioStation'
viewName = '{}.view'.format(methodName)
q = {'id': iid}
req = self._getRequest(viewName, q)
res = self._doInfoReq(req)
self._checkStatus(res)
return res
def getBookmarks(self):
"""
since: 1.9.0
@ -2301,6 +2499,8 @@ class Connection(object):
req = self._getRequest(viewName, q)
res = self._doInfoReq(req)
print(req.get_full_url())
print(res)
self._checkStatus(res)
return res
@ -2376,10 +2576,10 @@ class Connection(object):
position:int The position, in milliseconds, within the current
playing song
Saves the state of the play queue for this user. This includes
the tracks in the play queue, the currently playing track, and
the position within this track. Typically used to allow a user to
move between different clients/apps while retaining the same play
Saves the state of the play queue for this user. This includes
the tracks in the play queue, the currently playing track, and
the position within this track. Typically used to allow a user to
move between different clients/apps while retaining the same play
queue (for instance when listening to an audio book).
"""
methodName = 'savePlayQueue'
@ -2388,7 +2588,7 @@ class Connection(object):
qids = [qids]
q = self._getQueryDict({'current': current, 'position': position})
req = self._getRequestWithLists(viewName, {'id': qids}, q)
res = self._doInfoReq(req)
self._checkStatus(res)
@ -2398,16 +2598,16 @@ class Connection(object):
"""
since 1.12.0
Returns the state of the play queue for this user (as set by
savePlayQueue). This includes the tracks in the play queue,
the currently playing track, and the position within this track.
Typically used to allow a user to move between different
clients/apps while retaining the same play queue (for instance
Returns the state of the play queue for this user (as set by
savePlayQueue). This includes the tracks in the play queue,
the currently playing track, and the position within this track.
Typically used to allow a user to move between different
clients/apps while retaining the same play queue (for instance
when listening to an audio book).
"""
methodName = 'getPlayQueue'
viewName = '%s.view' % methodName
req = self._getRequest(viewName)
res = self._doInfoReq(req)
self._checkStatus(res)
@ -2424,9 +2624,9 @@ class Connection(object):
"""
methodName = 'getTopSongs'
viewName = '%s.view' % methodName
q = {'artist': artist, 'count': count}
req = self._getRequest(viewName, q)
res = self._doInfoReq(req)
self._checkStatus(res)
@ -2442,9 +2642,9 @@ class Connection(object):
"""
methodName = 'getNewestPodcasts'
viewName = '%s.view' % methodName
q = {'count': count}
req = self._getRequest(viewName, q)
res = self._doInfoReq(req)
self._checkStatus(res)
@ -2490,7 +2690,8 @@ class Connection(object):
methodName = 'getVideoInfo'
viewName = '%s.view' % methodName
q = {'id': int(vid)}
#q = {'id': int(vid)}
q = {'id': vid}
req = self._getRequest(viewName, q)
res = self._doInfoReq(req)
self._checkStatus(res)
@ -2507,7 +2708,8 @@ class Connection(object):
methodName = 'getAlbumInfo'
viewName = '%s.view' % methodName
q = {'id': int(aid)}
#q = {'id': int(aid)}
q = {'id': aid}
req = self._getRequest(viewName, q)
res = self._doInfoReq(req)
self._checkStatus(res)
@ -2524,7 +2726,8 @@ class Connection(object):
methodName = 'getAlbumInfo2'
viewName = '%s.view' % methodName
q = {'id': int(aid)}
#q = {'id': int(aid)}
q = {'id': aid}
req = self._getRequest(viewName, q)
res = self._doInfoReq(req)
self._checkStatus(res)
@ -2543,7 +2746,8 @@ class Connection(object):
methodName = 'getCaptions'
viewName = '%s.view' % methodName
q = self._getQueryDict({'id': int(vid), 'format': fmt})
#q = self._getQueryDict({'id': int(vid), 'format': fmt})
q = self._getQueryDict({'id': vid, 'format': fmt})
req = self._getRequest(viewName, q)
res = self._doInfoReq(req)
self._checkStatus(res)
@ -2561,7 +2765,7 @@ class Connection(object):
url = '%s:%d/%s/%s?%s' % (self._baseUrl, self._port,
self._separateServerPath(), viewName, methodName)
req = urllib2.Request(url)
req = urllib.request.Request(url)
res = self._opener.open(req)
res_msg = res.msg.lower()
return res_msg == 'ok'
@ -2575,14 +2779,17 @@ class Connection(object):
if sys.version_info[:3] >= (2, 7, 9) and self._insecure:
https_chain = HTTPSHandlerChain(
context=ssl._create_unverified_context())
opener = urllib2.build_opener(PysHTTPRedirectHandler, https_chain)
opener = urllib.request.build_opener(
PysHTTPRedirectHandler,
https_chain,
)
return opener
def _getQueryDict(self, d):
"""
Given a dictionary, it cleans out all the values set to None
"""
for k, v in d.items():
for k, v in list(d.items()):
if v is None:
del d[k]
return d
@ -2599,7 +2806,7 @@ class Connection(object):
qdict['p'] = 'enc:%s' % self._hexEnc(self._rawPass)
else:
salt = self._getSalt()
token = md5(self._rawPass + salt).hexdigest()
token = md5((self._rawPass + salt).encode('utf-8')).hexdigest()
qdict.update({
's': salt,
't': token,
@ -2612,12 +2819,13 @@ class Connection(object):
qdict.update(query)
url = '%s:%d/%s/%s' % (self._baseUrl, self._port, self._serverPath,
viewName)
req = urllib2.Request(url, urlencode(qdict))
if self._useGET:
#xbmc.log("Standard URL %s"%url,level=xbmc.LOGDEBUG)
#xbmc.log("Qdict %s"%str(qdict),level=xbmc.LOGDEBUG)
req = urllib.request.Request(url, urlencode(qdict).encode('utf-8'))
if(self._useGET or ('getCoverArt' in viewName) or ('stream' in viewName)):
url += '?%s' % urlencode(qdict)
req = urllib2.Request(url)
#xbmc.log("UseGET URL %s"%(url),xbmc.LOGDEBUG)
req = urllib.request.Request(url)
return req
def _getRequestWithList(self, viewName, listName, alist, query={}):
@ -2633,7 +2841,7 @@ class Connection(object):
data.write(urlencode(qdict))
for i in alist:
data.write('&%s' % urlencode({listName: i}))
req = urllib2.Request(url, data.getvalue())
req = urllib.request.Request(url, data.getvalue().encode('utf-8'))
if self._useGET:
url += '?%s' % data.getvalue()
@ -2657,10 +2865,10 @@ class Connection(object):
viewName)
data = StringIO()
data.write(urlencode(qdict))
for k, l in listMap.iteritems():
for k, l in listMap.items():
for i in l:
data.write('&%s' % urlencode({k: i}))
req = urllib2.Request(url, data.getvalue())
req = urllib.request.Request(url, data.getvalue().encode('utf-8'))
if self._useGET:
url += '?%s' % data.getvalue()
@ -2671,12 +2879,17 @@ class Connection(object):
def _doInfoReq(self, req):
# Returns a parsed dictionary version of the result
res = self._opener.open(req)
dres = json.loads(res.read())
dres = json.loads(res.read().decode('utf-8'))
return dres['subsonic-response']
def _doBinReq(self, req):
res = self._opener.open(req)
contType = res.info().getheader('Content-Type')
info = res.info()
if hasattr(info, 'getheader'):
contType = info.getheader('Content-Type')
else:
contType = info.get('Content-Type')
if contType:
if contType.startswith('text/html') or \
contType.startswith('application/json'):
@ -2716,7 +2929,7 @@ class Connection(object):
"""
separate REST portion of URL from base server path.
"""
return urllib2.splithost(self._serverPath)[1].split('/')[0]
return urllib.parse.splithost(self._serverPath)[1].split('/')[0]
def _fixLastModified(self, data):
"""
@ -2726,9 +2939,9 @@ class Connection(object):
of SECONDS since the unix epoch. JAVA SUCKS!
"""
if isinstance(data, dict):
for k, v in data.items():
for k, v in list(data.items()):
if k == 'lastModified':
data[k] = long(v) / 1000.0
data[k] = int(v) / 1000.0
return
elif isinstance(v, (tuple, list, dict)):
return self._fixLastModified(v)

View File

@ -1,434 +0,0 @@
import urllib
import urlparse
import libsonic
def force_list(value):
"""
Coerce the input value to a list.
If `value` is `None`, return an empty list. If it is a single value, create
a new list with that element on index 0.
:param value: Input value to coerce.
:return: Value as list.
:rtype: list
"""
if value is None:
return []
elif type(value) == list:
return value
else:
return [value]
class SubsonicClient(libsonic.Connection):
"""
Extend `libsonic.Connection` with new features and fix a few issues.
- Parse URL for host and port for constructor.
- Make sure API results are of of uniform type.
- Provide methods to intercept URL of binary requests.
- Add order property to playlist items.
- Add conventient `walk_*' methods to iterate over the API responses.
"""
def __init__(self, url, username, password, apiversion, insecure, legacyauth):
"""
Construct a new SubsonicClient.
:param str url: Full URL (including scheme) of the Subsonic server.
:param str username: Username of the server.
:param str password: Password of the server.
"""
self.intercept_url = False
# Parse Subsonic URL
parts = urlparse.urlparse(url)
scheme = parts.scheme or "http"
# Make sure there is hostname
if not parts.hostname:
raise ValueError("Expected hostname for URL: %s" % url)
# Validate scheme
if scheme not in ("http", "https"):
raise ValueError("Unexpected scheme '%s' for URL: %s" % (
scheme, url))
# Pick a default port
host = "%s://%s" % (scheme, parts.hostname)
port = parts.port or {"http": 80, "https": 443}[scheme]
# Invoke original constructor
super(SubsonicClient, self).__init__(
host, username, password, port=port, appName='Kodi', apiVersion=apiversion, insecure=insecure, legacyAuth=legacyauth)
def getIndexes(self, *args, **kwargs):
"""
Improve the getIndexes method. Ensures IDs are integers.
"""
def _artists_iterator(artists):
for artist in force_list(artists):
artist["id"] = int(artist["id"])
yield artist
def _index_iterator(index):
for index in force_list(index):
index["artist"] = list(_artists_iterator(index.get("artist")))
yield index
def _children_iterator(children):
for child in force_list(children):
child["id"] = int(child["id"])
if "parent" in child:
child["parent"] = int(child["parent"])
if "coverArt" in child:
child["coverArt"] = int(child["coverArt"])
if "artistId" in child:
child["artistId"] = int(child["artistId"])
if "albumId" in child:
child["albumId"] = int(child["albumId"])
yield child
response = super(SubsonicClient, self).getIndexes(*args, **kwargs)
response["indexes"] = response.get("indexes", {})
response["indexes"]["index"] = list(
_index_iterator(response["indexes"].get("index")))
response["indexes"]["child"] = list(
_children_iterator(response["indexes"].get("child")))
return response
def getPlaylists(self, *args, **kwargs):
"""
Improve the getPlaylists method. Ensures IDs are integers.
"""
def _playlists_iterator(playlists):
for playlist in force_list(playlists):
playlist["id"] = int(playlist["id"])
yield playlist
response = super(SubsonicClient, self).getPlaylists(*args, **kwargs)
response["playlists"]["playlist"] = list(
_playlists_iterator(response["playlists"].get("playlist")))
return response
def getPlaylist(self, *args, **kwargs):
"""
Improve the getPlaylist method. Ensures IDs are integers and add an
order property to each entry.
"""
def _entries_iterator(entries):
for order, entry in enumerate(force_list(entries), start=1):
entry["id"] = int(entry["id"])
entry["order"] = order
yield entry
response = super(SubsonicClient, self).getPlaylist(*args, **kwargs)
response["playlist"]["entry"] = list(
_entries_iterator(response["playlist"].get("entry")))
return response
def getArtists(self, *args, **kwargs):
"""
Improve the getArtists method. Ensures IDs are integers.
"""
def _artists_iterator(artists):
for artist in force_list(artists):
artist["id"] = int(artist["id"])
yield artist
def _index_iterator(index):
for index in force_list(index):
index["artist"] = list(_artists_iterator(index.get("artist")))
yield index
response = super(SubsonicClient, self).getArtists(*args, **kwargs)
response["artists"] = response.get("artists", {})
response["artists"]["index"] = list(
_index_iterator(response["artists"].get("index")))
return response
def getArtist(self, *args, **kwargs):
"""
Improve the getArtist method. Ensures IDs are integers.
"""
def _albums_iterator(albums):
for album in force_list(albums):
album["id"] = int(album["id"])
if "artistId" in album:
album["artistId"] = int(album["artistId"])
yield album
response = super(SubsonicClient, self).getArtist(*args, **kwargs)
response["artist"]["album"] = list(
_albums_iterator(response["artist"].get("album")))
return response
def getMusicDirectory(self, *args, **kwargs):
"""
Improve the getMusicDirectory method. Ensures IDs are integers.
"""
def _children_iterator(children):
for child in force_list(children):
child["id"] = int(child["id"])
if "parent" in child:
child["parent"] = int(child["parent"])
if "coverArt" in child:
child["coverArt"] = int(child["coverArt"])
if "artistId" in child:
child["artistId"] = int(child["artistId"])
if "albumId" in child:
child["albumId"] = int(child["albumId"])
yield child
response = super(SubsonicClient, self).getMusicDirectory(
*args, **kwargs)
response["directory"]["child"] = list(
_children_iterator(response["directory"].get("child")))
return response
def getAlbum(self, *args, **kwargs):
"""
Improve the getAlbum method. Ensures the IDs are real integers.
"""
def _songs_iterator(songs):
for song in force_list(songs):
song["id"] = int(song["id"])
yield song
response = super(SubsonicClient, self).getAlbum(*args, **kwargs)
response["album"]["song"] = list(
_songs_iterator(response["album"].get("song")))
return response
def getAlbumList2(self, *args, **kwargs):
"""
Improve the getAlbumList2 method. Ensures the IDs are real integers.
"""
def _album_iterator(albums):
for album in force_list(albums):
album["id"] = int(album["id"])
yield album
response = super(SubsonicClient, self).getAlbumList2(*args, **kwargs)
response["albumList2"]["album"] = list(
_album_iterator(response["albumList2"].get("album")))
return response
def getStarred(self, *args, **kwargs):
"""
Improve the getStarred method. Ensures the IDs are real integers.
"""
def _song_iterator(songs):
for song in force_list(songs):
song["id"] = int(song["id"])
yield song
response = super(SubsonicClient, self).getStarred(*args, **kwargs)
response["starred"]["song"] = list(
_song_iterator(response["starred"].get("song")))
return response
def getCoverArtUrl(self, *args, **kwargs):
"""
Return an URL to the cover art.
"""
self.intercept_url = True
url = self.getCoverArt(*args, **kwargs)
self.intercept_url = False
return url
def streamUrl(self, *args, **kwargs):
"""
Return an URL to the file to stream.
"""
self.intercept_url = True
url = self.stream(*args, **kwargs)
self.intercept_url = False
return url
def _doBinReq(self, *args, **kwargs):
"""
Intercept request URL to provide the URL of the item that is requested.
If the URL is intercepted, the request is not executed. A username and
password is added to provide direct access to the stream.
"""
if self.intercept_url:
parts = list(urlparse.urlparse(
args[0].get_full_url() + "?" + args[0].data))
parts[4] = dict(urlparse.parse_qsl(parts[4]))
parts[4].update({"u": self.username, "p": self.password})
parts[4] = urllib.urlencode(parts[4])
return urlparse.urlunparse(parts)
else:
return super(SubsonicClient, self)._doBinReq(*args, **kwargs)
def walk_index(self):
"""
Request Subsonic's index and iterate each item.
"""
response = self.getIndexes()
for index in response["indexes"]["index"]:
for index in index["artist"]:
for item in self.walk_directory(index["id"]):
yield item
for child in response["indexes"]["child"]:
if child.get("isDir"):
for child in self.walk_directory(child["id"]):
yield child
else:
yield child
def walk_playlists(self):
"""
Request Subsonic's playlists and iterate over each item.
"""
response = self.getPlaylists()
for child in response["playlists"]["playlist"]:
yield child
def walk_playlist(self, playlist_id):
"""
Request Subsonic's playlist items and iterate over each item.
"""
response = self.getPlaylist(playlist_id)
for child in response["playlist"]["entry"]:
yield child
def walk_directory(self, directory_id):
"""
Request a Subsonic music directory and iterate over each item.
"""
response = self.getMusicDirectory(directory_id)
for child in response["directory"]["child"]:
if child.get("isDir"):
for child in self.walk_directory(child["id"]):
yield child
else:
yield child
def walk_artist(self, artist_id):
"""
Request a Subsonic artist and iterate over each album.
"""
response = self.getArtist(artist_id)
for child in response["artist"]["album"]:
yield child
def walk_artists(self):
"""
Request all artists and iterate over each item.
"""
response = self.getArtists()
for index in response["artists"]["index"]:
for artist in index["artist"]:
yield artist
def walk_genres(self):
"""
Request all genres and iterate over each item.
"""
response = self.getGenres()
for genre in response["genres"]["genre"]:
yield genre
def walk_albums(self, ltype, size=None, fromYear=None,toYear=None, genre=None, offset=None):
"""
Request all albums for a given genre and iterate over each album.
"""
if ltype == 'byGenre' and genre is None:
return
if ltype == 'byYear' and (fromYear is None or toYear is None):
return
response = self.getAlbumList2(
ltype=ltype, size=size, fromYear=fromYear, toYear=toYear,genre=genre, offset=offset)
if not response["albumList2"]["album"]:
return
for album in response["albumList2"]["album"]:
yield album
def walk_album(self, album_id):
"""
Request an alum and iterate over each item.
"""
response = self.getAlbum(album_id)
for song in response["album"]["song"]:
yield song
def walk_tracks_random(self, size=None, genre=None, fromYear=None,toYear=None):
"""
Request random songs by genre and/or year and iterate over each song.
"""
response = self.getRandomSongs(
size=size, genre=genre, fromYear=fromYear, toYear=toYear)
for song in response["randomSongs"]["song"]:
yield song
def walk_tracks_starred(self):
"""
Request Subsonic's starred songs and iterate over each item.
"""
response = self.getStarred()
for song in response["starred"]["song"]:
yield song

View File

@ -1,5 +0,0 @@
*.pyc
test.py
MANIFEST
dist
build

View File

@ -1,57 +0,0 @@
## 0.6.2
* Added an option to use GET requests, instead of the default POST requests
## 0.6.1
* Added `legacyAuth` option for pre-1.13.0 support
## 0.6.0
* Added API 1.14.0 support
## 0.5.1
* Added the ability to use a netrc file for credentials
## 0.5.0
* Added support for using credentials via a netrc file
## 0.4.1
* Fixed SSL handling issues
## 0.4.0
* Added missing 1.12.0 API items
* Added 1.13.0 API items
* All timestamps both passed in, and returned, should now be in **proper** unix time, which is seconds since the epoch, **not** milliseconds since the epoch
## 0.3.5
* allow for self-signed certs
## 0.3.4
* Add missing parameters to getAlbumList2 (thanks to basilfx)
* Remove trailing whitespace (thanks to basilfx)
## 0.3.3
* Added support for API version 1.11.0
* Added a couple of additions from API version 1.10.x that were previously
missed
## 0.3.1
* Incorporated unofficial API calls (beallio)
## 0.2.1
* Added a patch to force SSLv3 as some users were apparently having issues
with the 4.7 release of Subsonic and SSL. (thanks to orangepeelbeef)
## 0.2.0
* Added support for API version 1.8.0 (Subsonic verion 4.7)

View File

@ -1,674 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

View File

@ -1,3 +0,0 @@
include LICENSE
include CHANGELOG.md
include README.md

View File

@ -1,80 +0,0 @@
# py-sonic #
## INSTALL ##
Installation is fairly simple. Just do the standard install as root:
tar -xvzf py-sonic-*.tar.gz
cd py-sonic-*
python setup.py install
You can also install directly using *pip* or *easy_install*
pip install py-sonic
## PYTHON 3 ##
I've added experimental support for Python 3. This is not fully tested, but I
do encourage people to fork the repository and test off the "python3" branch
and issue pull requests. If you don't want to go through that trouble, bug
reports are always welcome too!
## USAGE ##
This library follows the REST API almost exactly (for now). If you follow the
documentation on http://www.subsonic.org/pages/api.jsp or you do a:
pydoc libsonic.connection
I have also added documentation at http://stuffivelearned.org/doku.php?id=programming:python:py-sonic
## BASIC TUTORIAL ##
This is about as basic as it gets. We are just going to set up the connection
and then get a couple of random songs.
```python
#!/usr/bin/env python
from pprint import pprint
import libsonic
# We pass in the base url, the username, password, and port number
# Be sure to use https:// if this is an ssl connection!
conn = libsonic.Connection('https://music.example.com' , 'myuser' ,
'secretpass' , port=443)
# Let's get 2 completely random songs
songs = conn.getRandomSongs(size=2)
# We'll just pretty print the results we got to the terminal
pprint(songs)
```
As you can see, it's really pretty simple. If you use the documentation
provided in the library:
pydoc libsonic.connection
or the api docs on subsonic.org (listed above), you should be able to make use
of your server without too much trouble.
Right now, only plain old dictionary structures are returned. The plan
for a later release includes the following:
* Proper object representations for Artist, Album, Song, etc.
* Lazy access of members (the song objects aren't created until you want to
do something with them)
## TODO ##
In the future, I would like to make this a little more "pythonic" and add
some classes to wrap up the data returned from the server. Right now, the data
is just returned in the form of a dict, but I would like to have actual
Song, Album, Folder, etc. classes instead, or at least an alternative. For
now, it works.
*NOTE:* I've noticed a wart with the upstream Subsonic API wherein any
of the Connection methods that would normally return a list of dictionary
elements (getPlaylists() for example), will only return a dictionary if there
is a single return element. I plan on changing this in py-sonic so that
any methods of that nature will *always* return a list, even if there is
only a single dict in the list.

View File

@ -1,32 +0,0 @@
"""
This file is part of py-sonic.
py-sonic is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
py-sonic is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with py-sonic. If not, see <http://www.gnu.org/licenses/>
For information on method calls, see 'pydoc libsonic.connection'
----------
Basic example:
----------
import libsonic
conn = libsonic.Connection('http://localhost' , 'admin' , 'password')
print conn.ping()
"""
from connection import *
__version__ = '0.6.2'

File diff suppressed because it is too large Load Diff

View File

@ -1,59 +0,0 @@
"""
This file is part of py-sonic.
py-sonic is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
py-sonic is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with py-sonic. If not, see <http://www.gnu.org/licenses/>
"""
class SonicError(Exception):
pass
class ParameterError(SonicError):
pass
class VersionError(SonicError):
pass
class CredentialError(SonicError):
pass
class AuthError(SonicError):
pass
class LicenseError(SonicError):
pass
class DataNotFoundError(SonicError):
pass
class ArgumentError(SonicError):
pass
# This maps the error code numbers from the Subsonic server to their
# appropriate Exceptions
ERR_CODE_MAP = {
0: SonicError ,
10: ParameterError ,
20: VersionError ,
30: VersionError ,
40: CredentialError ,
50: AuthError ,
60: LicenseError ,
70: DataNotFoundError ,
}
def getExcByCode(code):
code = int(code)
if code in ERR_CODE_MAP:
return ERR_CODE_MAP[code]
return SonicError

View File

@ -1,49 +0,0 @@
#!/usr/bin/env python
"""
This file is part of py-sonic.
py-sonic is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
py-sonic is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with py-sonic. If not, see <http://www.gnu.org/licenses/>
"""
from distutils.core import setup
from libsonic import __version__ as version
setup(name='py-sonic',
version=version,
author='Jay Deiman',
author_email='admin@splitstreams.com',
url='http://stuffivelearned.org',
description='A python wrapper library for the Subsonic REST API. '
'http://subsonic.org',
long_description='This is a basic wrapper library for the Subsonic '
'REST API. This will allow you to connect to your server and retrieve '
'information and have it returned in basic Python types.',
packages=['libsonic'],
package_dir={'libsonic': 'libsonic'},
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: System Administrators',
'Intended Audience :: Information Technology',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Natural Language :: English',
'Operating System :: POSIX',
'Programming Language :: Python',
'Topic :: System :: Systems Administration',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Software Development :: Libraries',
'Topic :: System',
]
)

View File

@ -0,0 +1,4 @@
#v2.1.0
#https://github.com/romanvm/script.module.simpleplugin/releases
from .simpleplugin import *

File diff suppressed because it is too large Load Diff

1504
main.py

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,182 @@
# XBMC Media Center language file
# Addon Name: Subsonic
# Addon id: plugin.audio.subsonic
# Addon Provider:
# Addon Translate: Moshkopp
msgid ""
msgstr ""
msgctxt "#30000"
msgid "General"
msgstr ""
msgctxt "#30001"
msgid "Server"
msgstr ""
msgctxt "#30002"
msgid "Server URL"
msgstr ""
msgctxt "#30003"
msgid "Username"
msgstr ""
msgctxt "#30004"
msgid "Password"
msgstr ""
msgctxt "#30005"
msgid "Display"
msgstr ""
msgctxt "#30006"
msgid "Albums per page"
msgstr ""
msgctxt "#30007"
msgid "Tracks per page (ignored in albums & playlists)"
msgstr ""
msgctxt "#30008"
msgid "Download"
msgstr ""
msgctxt "#30009"
msgid "Download folder"
msgstr ""
msgctxt "#30010"
msgid "Streaming"
msgstr ""
msgctxt "#30011"
msgid "Transcode format"
msgstr ""
msgctxt "#30012"
msgid "Bitrate"
msgstr ""
msgctxt "#30013"
msgid "Advanced Settings"
msgstr ""
msgctxt "#30014"
msgid "API version"
msgstr ""
msgctxt "#30016"
msgid "Allow self signed certificates"
msgstr ""
msgctxt "#30017"
msgid "Cache (in minutes)"
msgstr ""
msgctxt "#30018"
msgid "Cache data time"
msgstr ""
msgctxt "#30019"
msgid "Library"
msgstr ""
msgctxt "#30020"
msgid "Albums"
msgstr ""
msgctxt "#30021"
msgid "Tracks"
msgstr ""
msgctxt "#30022"
msgid "Playlists"
msgstr ""
msgctxt "#30023"
msgid "Newest albums"
msgstr ""
msgctxt "#30024"
msgid "Most played albums"
msgstr ""
msgctxt "#30025"
msgid "Recently played albums"
msgstr ""
msgctxt "#30026"
msgid "Random albums"
msgstr ""
msgctxt "#30029"
msgid "Next page"
msgstr ""
msgctxt "#30030"
msgid "Back to Menu"
msgstr ""
msgctxt "#30031"
msgid "Item has been unstarred."
msgstr ""
msgctxt "#30032"
msgid "Item has been starred!"
msgstr ""
msgctxt "#30033"
msgid "Star on Subsonic"
msgstr ""
msgctxt "#30034"
msgid "Unstar on Subsonic"
msgstr ""
msgctxt "#30035"
msgid "Download"
msgstr ""
msgctxt "#30036"
msgid "Starred tracks"
msgstr ""
msgctxt "#30037"
msgid "Random tracks"
msgstr ""
msgctxt "#30038"
msgid "Browse"
msgstr ""
msgctxt "#30039"
msgid "Search Songs"
msgstr ""
msgctxt "#30040"
msgid "useGET"
msgstr ""
msgctxt "#30041"
msgid "legacyauth"
msgstr ""
msgctxt "#30042"
msgid "port"
msgstr ""
msgctxt "#30043"
msgid "Merge album folders"
msgstr ""
msgctxt "#30044"
msgid "Scrobble to Last.FM"
msgstr ""
msgctxt "#30045"
msgid "Search Albums"
msgstr ""

View File

@ -0,0 +1,182 @@
# XBMC Media Center language file
# Addon Name: Subsonic
# Addon id: plugin.audio.subsonic
# Addon Provider:
# Addon Translate: Gordie
msgid ""
msgstr ""
msgctxt "#30000"
msgid "General"
msgstr "Général"
msgctxt "#30001"
msgid "Server"
msgstr "Serveur"
msgctxt "#30002"
msgid "Server URL"
msgstr "URL du serveur"
msgctxt "#30003"
msgid "Username"
msgstr "Nom d'utilisateur"
msgctxt "#30004"
msgid "Password"
msgstr "Mot de passe"
msgctxt "#30005"
msgid "Display"
msgstr "Affichage"
msgctxt "#30006"
msgid "Albums per page"
msgstr "Albums par page"
msgctxt "#30007"
msgid "Tracks per page (ignored in albums & playlists)"
msgstr "Pistes par page (ignoré dans les albums & listes de lecture)"
msgctxt "#30008"
msgid "Download"
msgstr "Télécharger"
msgctxt "#30009"
msgid "Download folder"
msgstr "Répertoire de téléchargement"
msgctxt "#30010"
msgid "Streaming"
msgstr "Diffusion"
msgctxt "#30011"
msgid "Transcode format"
msgstr "Format de transcodage"
msgctxt "#30012"
msgid "Bitrate"
msgstr "Bitrate"
msgctxt "#30013"
msgid "Advanced Settings"
msgstr "Paramètres avancés"
msgctxt "#30014"
msgid "API version"
msgstr "Version de l'API"
msgctxt "#30016"
msgid "Allow self signed certificates"
msgstr "Autoriser les certificats auto-signés"
msgctxt "#30017"
msgid "Cache (in minutes)"
msgstr "Cache (en minutes)"
msgctxt "#30018"
msgid "Cache datas time"
msgstr "Durée du cache pour les données"
msgctxt "#30019"
msgid "Library"
msgstr "Bibliothèque"
msgctxt "#30020"
msgid "Albums"
msgstr "Albums"
msgctxt "#30021"
msgid "Tracks"
msgstr "Pistes"
msgctxt "#30022"
msgid "Playlists"
msgstr "Playlists"
msgctxt "#30023"
msgid "Newest albums"
msgstr "Nouveaux albums"
msgctxt "#30024"
msgid "Most played albums"
msgstr "Albums les plus joués"
msgctxt "#30025"
msgid "Recently played albums"
msgstr "Albums joués récemment"
msgctxt "#30026"
msgid "Random albums"
msgstr "Albums au hasard"
msgctxt "#30029"
msgid "Next page"
msgstr "Page suivante"
msgctxt "#30030"
msgid "Back to Menu"
msgstr "Retour au menu"
msgctxt "#30031"
msgid "Item has been unstarred."
msgstr "Cet élément a été retiré des favoris"
msgctxt "#30032"
msgid "Item has been starred!"
msgstr "Cet élément a été ajouté aux favoris !"
msgctxt "#30033"
msgid "Star on Subsonic"
msgstr "Ajouter aux favoris Subsonic"
msgctxt "#30034"
msgid "Unstar on Subsonic"
msgstr "Retirer des favoris Subsonic"
msgctxt "#30035"
msgid "Download"
msgstr "Télécharger"
msgctxt "#30036"
msgid "Starred tracks"
msgstr "Pistes favorites"
msgctxt "#30037"
msgid "Random tracks"
msgstr "Pistes au hasard"
msgctxt "#30038"
msgid "Browse"
msgstr "Parcourir"
msgctxt "#30039"
msgid "Search Songs"
msgstr "Rechercher Chansons"
msgctxt "#30040"
msgid "useGET"
msgstr ""
msgctxt "#30041"
msgid "legacyauth"
msgstr ""
msgctxt "#30042"
msgid "port"
msgstr ""
msgctxt "#30043"
msgid "Merge album folders"
msgstr ""
msgctxt "#30044"
msgid "Scrobble to Last.FM"
msgstr ""
msgctxt "#30045"
msgid "Search Albums"
msgstr "Rechercher Albums"

View File

@ -0,0 +1,181 @@
# XBMC Media Center language file
# Addon Name: Subsonic
# Addon id: plugin.audio.subsonic
# Addon Provider:
# Addon Translate: Moshkopp
msgid ""
msgstr ""
msgctxt "#30000"
msgid "General"
msgstr "Allgemein"
msgctxt "#30001"
msgid "Server"
msgstr "Server"
msgctxt "#30002"
msgid "Server URL"
msgstr "Serveradresse"
msgctxt "#30003"
msgid "Username"
msgstr "Benutzername"
msgctxt "#30004"
msgid "Password"
msgstr "Passwort"
msgctxt "#30005"
msgid "Display"
msgstr "Anzeige"
msgctxt "#30006"
msgid "Albums per page"
msgstr "Alben pro Seite"
msgctxt "#30007"
msgid "Tracks per page (ignored in albums & playlists)"
msgstr "Lieder pro Seite (wird in Alben und Playlisten ignoriert)"
msgctxt "#30008"
msgid "Download"
msgstr "Download"
msgctxt "#30009"
msgid "Download folder"
msgstr "Download Verzeichnis"
msgctxt "#30010"
msgid "Streaming"
msgstr "Übertragung"
msgctxt "#30011"
msgid "Transcode format"
msgstr "Umwandlungs Format"
msgctxt "#30012"
msgid "Bitrate"
msgstr "Bitrate"
msgctxt "#30013"
msgid "Advanced Settings"
msgstr "Erweitert"
msgctxt "#30014"
msgid "API version"
msgstr "API Version"
msgctxt "#30016"
msgid "Allow self signed certificates"
msgstr "Erlaube eigensignierte Zertifikate"
msgctxt "#30017"
msgid "Cache (in minutes)"
msgstr "Speicher (in Minuten)"
msgctxt "#30018"
msgid "Cache datas time"
msgstr "Speicher Daten Zeit"
msgctxt "#30019"
msgid "Library"
msgstr "Bibliothek"
msgctxt "#30020"
msgid "Albums"
msgstr "Alben"
msgctxt "#30021"
msgid "Tracks"
msgstr "Lieder"
msgctxt "#30022"
msgid "Playlists"
msgstr "Playlisten"
msgctxt "#30023"
msgid "Newest albums"
msgstr "Neueste Alben"
msgctxt "#30024"
msgid "Most played albums"
msgstr "Häufig gehörte Alben"
msgctxt "#30025"
msgid "Recently played albums"
msgstr "Zuletzt gehörte Alben"
msgctxt "#30026"
msgid "Random albums"
msgstr "Zufällige Alben"
msgctxt "#30029"
msgid "Next page"
msgstr "Nächste Seite"
msgctxt "#30030"
msgid "Back to Menu"
msgstr "Hauptmenü"
msgctxt "#30031"
msgid "Item has been unstarred."
msgstr "Bewertung entfernt"
msgctxt "#30032"
msgid "Item has been starred!"
msgstr "Bewertung hinzugefügt"
msgctxt "#30033"
msgid "Star on Subsonic"
msgstr "Bewerten auf Subsonic"
msgctxt "#30034"
msgid "Unstar on Subsonic"
msgstr "Löschen auf Subsonic"
msgctxt "#30035"
msgid "Download"
msgstr "Herunterladen"
msgctxt "#30036"
msgid "Starred tracks"
msgstr "Lieblings lieder"
msgctxt "#30037"
msgid "Random tracks"
msgstr "Zufällig lieder"
msgctxt "#30038"
msgid "Browse"
msgstr "Durchsuchen"
msgctxt "#30039"
msgid "Search Songs"
msgstr "Suche Lieder"
msgctxt "#30040"
msgid "useGET"
msgstr ""
msgctxt "#30041"
msgid "legacyauth"
msgstr ""
msgctxt "#30042"
msgid "port"
msgstr ""
msgctxt "#30043"
msgid "Merge album folders"
msgstr ""
msgctxt "#30044"
msgid "Scrobble to Last.FM"
msgstr ""
msgctxt "#30045"
msgid "Search Albums"
msgstr "Suche Albums"

View File

@ -1,27 +1,33 @@
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<settings>
<!-- GENERAL -->
<category label="General">
<setting label="Server" type="lsep" />
<setting id="subsonic_url" type="text" label="Server URL" default="http://demo.subsonic.org"/>
<setting id="username" type="text" label="Username" default="guest3"/>
<setting id="password" type="text" option="hidden" label="Password" default="guest"/>
<setting label="Display" type="lsep" />
<setting id="albums_per_page" type="labelenum" label="Albums per page" default="50" values="10|25|50|100|250|500"/>
<setting id="tracks_per_page" type="labelenum" label="Tracks per page (ignored in albums & playlists)" default="100" values="10|25|50|100|250|500"/>
<setting label="Download" type="lsep" />
<setting id="download_folder" type="folder" label="Download folder" source="auto" option="writeable"/>
<setting label="Streaming" type="lsep" />
<setting id="transcode_format_streaming" type="labelenum" label="Transcode format" values="mp3|raw|flv|ogg"/>
<setting id="bitrate_streaming" type="labelenum" label="Bitrate" values="320|256|224|192|160|128|112|96|80|64|56|48|40|32"/>
<category label="30000">
<setting label="30001" type="lsep" />
<setting label="30002" id="subsonic_url" type="text" default="http://demo.subsonic.org"/>
<setting label="30042" id="port" type="text" default="80"/>
<setting label="30003" id="username" type="text" default="guest3"/>
<setting label="30004" id="password" type="text" option="hidden" default="guest"/>
<setting label="30005" type="lsep" />
<setting label="30006" id="albums_per_page" type="labelenum" default="50" values="10|25|50|100|250|500"/>
<setting label="30007" id="tracks_per_page" type="labelenum" default="100" values="10|25|50|100|250|500"/>
<setting label="30008" type="lsep" />
<setting label="30009" id="download_folder" type="folder" source="auto" option="writeable"/>
<setting label="30010" type="lsep" />
<setting label="30011" id="transcode_format_streaming" type="labelenum" values="mp3|raw|flv|ogg"/>
<setting label="30012" id="bitrate_streaming" type="labelenum" default="0" values="320|256|224|192|160|128|112|96|80|64|56|48|40|32|0"/>
</category>
<!-- ADVANCED -->
<category label="Advanced Settings">
<setting label="Server" type="lsep" />
<setting id="apiversion" type="labelenum" label="API version" values="1.11.0|1.12.0|1.13.0|1.14.0" default="1.13.0"/>
<setting id="insecure" type="bool" label="Allow self signed certificates" default="false" />
<setting label="Cache (in minutes) - not yet implemented" type="lsep" />
<setting id="cachetime" type="labelenum" label="Cache datas time" default="5" values="1|5|15|30|60|120|180|720|1440"/>
<category label="30013">
<setting label="30001" type="lsep" />
<setting label="30014" id="apiversion" type="labelenum" values="1.11.0|1.12.0|1.13.0|1.14.0|1.15.0|1.16.0" default="1.15.0"/>
<setting label="30016" id="insecure" type="bool" default="false" />
<setting label="30040" id="useget" type="bool" default="true" />
<setting label="30041" id="legacyauth" type="bool" default="false" />
<setting label="30017" type="lsep" />
<setting label="30018" id="cachetime" type="labelenum" default="3600" values="1|5|15|30|60|120|180|720|1440|3600"/>
<setting label="30043" id="merge" type="bool" default="false" />
<setting label="30044" id="scrobble" type="bool" default="false" />
</category>
</settings>

105
service.py Normal file
View File

@ -0,0 +1,105 @@
import re
import xbmc
import xbmcvfs
import os
import xbmcaddon
# Add the /lib folder to sys
sys.path.append(xbmcvfs.translatePath(os.path.join(xbmcaddon.Addon("plugin.audio.subsonic").getAddonInfo("path"), "lib")))
import libsonic
from simpleplugin import Plugin
from simpleplugin import Addon
# Create plugin instance
plugin = Plugin()
connection = None
try:
scrobbleEnabled = Addon().get_setting('scrobble')
except:
scrobbleEnabled = False
scrobbled = False
def popup(text, time=5000, image=None):
title = plugin.addon.getAddonInfo('name')
icon = plugin.addon.getAddonInfo('icon')
xbmc.executebuiltin('Notification(%s, %s, %d, %s)' % (title, text,
time, icon))
def get_connection():
global connection
if connection==None:
connected = False
# Create connection
try:
connection = libsonic.Connection(
baseUrl=Addon().get_setting('subsonic_url'),
username=Addon().get_setting('username', convert=False),
password=Addon().get_setting('password', convert=False),
port=Addon().get_setting('port'),
apiVersion=Addon().get_setting('apiversion'),
insecure=Addon().get_setting('insecure'),
legacyAuth=Addon().get_setting('legacyauth'),
useGET=Addon().get_setting('useget'),
)
connected = connection.ping()
except:
pass
if connected==False:
popup('Connection error')
return False
return connection
def scrobble_track(track_id):
connection = get_connection()
if connection==False:
return False
res = connection.scrobble(track_id)
#xbmc.log("response %s"%(res), xbmc.LOGINFO)
if res['status'] == 'ok':
popup("Scrobbled track")
return True
else:
popup("Scrobble failed")
return False
if __name__ == '__main__':
if(scrobbleEnabled):
monitor = xbmc.Monitor()
xbmc.log("Subsonic service started", xbmc.LOGINFO)
popup("Subsonic service started")
while not monitor.abortRequested():
if monitor.waitForAbort(10):
break
if (xbmc.getCondVisibility("Player.HasMedia")):
try:
currentFileName = xbmc.getInfoLabel("Player.Filenameandpath")
currentFileProgress = xbmc.getInfoLabel("Player.Progress")
pattern = re.compile(r'plugin:\/\/plugin\.audio\.subsonic\/\?action=play_track&id=(.*?)&')
currentTrackId = re.findall(pattern, currentFileName)[0]
#xbmc.log("Name %s Id %s Progress %s"%(currentFileName,currentTrackId,currentFileProgress), xbmc.LOGDEBUG)
if (int(currentFileProgress)<50):
scrobbled = False
elif (int(currentFileProgress)>=50 and scrobbled == False):
xbmc.log("Scrobbling Track Id %s"%(currentTrackId), xbmc.LOGDEBUG)
success = scrobble_track(currentTrackId)
if success:
scrobbled = True
else:
pass
except IndexError:
print ("Not a Subsonic track")
scrobbled = True
except Exception as e:
xbmc.log("Subsonic service failed %e"%e, xbmc.LOGINFO)
else:
pass
#xbmc.log("Playing stopped", xbmc.LOGINFO)
else:
xbmc.log("Subsonic service not started due to settings", xbmc.LOGINFO)