-
Notifications
You must be signed in to change notification settings - Fork 26
/
connection.py
2453 lines (2044 loc) · 90.9 KB
/
connection.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
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 base64 import b64encode
from urllib import urlencode
from .errors import *
from pprint import pprint
from cStringIO import StringIO
import json , urllib2, httplib, logging, socket, ssl
API_VERSION = '1.11.0'
logger = logging.getLogger(__name__)
class HTTPSConnectionChain(httplib.HTTPSConnection):
_preferred_ssl_protos = (
('TLSv1' , ssl.PROTOCOL_TLSv1) ,
('SSLv3' , ssl.PROTOCOL_SSLv3) ,
('SSLv23' , ssl.PROTOCOL_SSLv23) ,
)
_ssl_working_proto = None
def connect(self):
sock = socket.create_connection((self.host, self.port), self.timeout)
if self._tunnel_host:
self.sock = sock
self._tunnel()
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)
self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file,
ssl_version=self._ssl_working_proto)
return
# Try connecting via the different SSL protos in preference order
for proto_name , proto in self._preferred_ssl_protos:
try:
self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file,
ssl_version=proto)
except:
pass
else:
# Cache the working ssl version
HTTPSConnectionChain._ssl_working_proto = proto
break
class HTTPSHandlerChain(urllib2.HTTPSHandler):
def https_open(self , req):
return self.do_open(HTTPSConnectionChain, req)
# install opener
urllib2.install_opener(urllib2.build_opener(HTTPSHandlerChain()))
class PysHTTPRedirectHandler(urllib2.HTTPRedirectHandler):
"""
This class is used to override the default behavior of the
HTTPRedirectHandler, which does *not* redirect POST data
"""
def redirect_request(self, req, fp, code, msg, headers, newurl):
m = req.get_method()
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()
if k.lower() not in ("content-length", "content-type")
)
data = None
if req.has_data():
data = req.get_data()
return urllib2.Request(newurl,
data=data,
headers=newheaders,
origin_req_host=req.get_origin_req_host(),
unverifiable=True)
else:
raise urllib2.HTTPError(req.get_full_url(), code, msg, headers, fp)
class Connection(object):
def __init__(self , baseUrl , username , password , port=4040 ,
serverPath='/rest' , appName='py-sonic' , apiVersion=API_VERSION,
insecure=False):
"""
This will create a connection to your subsonic server
baseUrl:str The base url for your server. Be sure to use
"https" for SSL connections. If you are using
a port other than the default 4040, be sure to
specify that with the port argument. Do *not*
append it here.
ex: http://subsonic.example.com
If you are running subsonic under a different
path, specify that with the "serverPath" arg,
*not* here. For example, if your subsonic
lives at:
https://mydomain.com:8080/path/to/subsonic/rest
You would set the following:
baseUrl = "https://mydomain.com"
port = 8080
serverPath = "/path/to/subsonic/rest"
username:str The username to use for the connection
password:str The password to use for the connection
port:int The port number to connect on. The default for
unencrypted subsonic connections is 4040
serverPath:str The base resource path for the subsonic views.
This is useful if you have your subsonic server
behind a proxy and the path that you are proxying
is different from the default of '/rest'.
Ex:
serverPath='/path/to/subs'
The full url that would be built then would be
(assuming defaults and using "example.com" and
you are using the "ping" view):
http://example.com:4040/path/to/subs/ping.view
appName:str The name of your application.
apiVersion:str The API version you wish to use for your
application. Subsonic will throw an error if you
try to use/send an api version higher than what
the server supports. See the Subsonic API docs
to find the Subsonic version -> API version table.
This is useful if you are connecting to an older
version of Subsonic.
insecure:bool This will allow you to use self signed
certificates when connecting if set to True.
"""
self._baseUrl = baseUrl
self._username = username
self._rawPass = password
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)
# Properties
def setBaseUrl(self , url):
self._baseUrl = url
self._opener = self._getOpener(self._username , self._rawPass)
baseUrl = property(lambda s: s._baseUrl , setBaseUrl)
def setPort(self , port):
self._port = int(port)
port = property(lambda s: s._port , setPort)
def setUsername(self , username):
self._username = username
self._opener = self._getOpener(self._username , self._rawPass)
username = property(lambda s: s._username , setUsername)
def setPassword(self , password):
self._rawPass = password
# Redo the opener with the new creds
self._opener = self._getOpener(self._username , self._rawPass)
password = property(lambda s: s._rawPass , setPassword)
apiVersion = property(lambda s: s._apiVersion)
def setAppName(self , appName):
self._appName = appName
appName = property(lambda s: s._appName , setAppName)
def setServerPath(self , path):
self._serverPath = path.strip('/')
serverPath = property(lambda s: s._serverPath , setServerPath)
def setInsecure(self, insecure):
self._insecure = insecure
insecure = property(lambda s: s._insecure, setInsecure)
# API methods
def ping(self):
"""
since: 1.0.0
Returns a boolean True if the server is alive, False otherwise
"""
methodName = 'ping'
viewName = '%s.view' % methodName
req = self._getRequest(viewName)
try:
res = self._doInfoReq(req)
except:
return False
if res['status'] == 'ok':
return True
elif res['status'] == 'failed':
raise getExcByCode(res['error']['code'])
return False
def getLicense(self):
"""
since: 1.0.0
Gets details related to the software license
Returns a dict like the following:
{u'license': {u'date': u'2010-05-21T11:14:39',
u'email': u'email@example.com',
u'key': u'12345678901234567890123456789012',
u'valid': True},
u'status': u'ok',
u'version': u'1.5.0',
u'xmlns': u'http://subsonic.org/restapi'}
"""
methodName = 'getLicense'
viewName = '%s.view' % methodName
req = self._getRequest(viewName)
res = self._doInfoReq(req)
self._checkStatus(res)
return res
def getMusicFolders(self):
"""
since: 1.0.0
Returns all configured music folders
Returns a dict like the following:
{u'musicFolders': {u'musicFolder': [{u'id': 0, u'name': u'folder1'},
{u'id': 1, u'name': u'folder2'},
{u'id': 2, u'name': u'folder3'}]},
u'status': u'ok',
u'version': u'1.5.0',
u'xmlns': u'http://subsonic.org/restapi'}
"""
methodName = 'getMusicFolders'
viewName = '%s.view' % methodName
req = self._getRequest(viewName)
res = self._doInfoReq(req)
self._checkStatus(res)
return res
def getNowPlaying(self):
"""
since: 1.0.0
Returns what is currently being played by all users
Returns a dict like the following:
{u'nowPlaying': {u'entry': {u'album': u"Jazz 'Round Midnight 12",
u'artist': u'Astrud Gilberto',
u'bitRate': 172,
u'contentType': u'audio/mpeg',
u'coverArt': u'98349284',
u'duration': 325,
u'genre': u'Jazz',
u'id': u'2424324',
u'isDir': False,
u'isVideo': False,
u'minutesAgo': 0,
u'parent': u'542352',
u'path': u"Astrud Gilberto/Jazz 'Round Midnight 12/01 - The Girl From Ipanema.mp3",
u'playerId': 1,
u'size': 7004089,
u'suffix': u'mp3',
u'title': u'The Girl From Ipanema',
u'track': 1,
u'username': u'user1',
u'year': 1996}},
u'status': u'ok',
u'version': u'1.5.0',
u'xmlns': u'http://subsonic.org/restapi'}
"""
methodName = 'getNowPlaying'
viewName = '%s.view' % methodName
req = self._getRequest(viewName)
res = self._doInfoReq(req)
self._checkStatus(res)
return res
def getIndexes(self , musicFolderId=None , ifModifiedSince=0):
"""
since: 1.0.0
Returns an indexed structure of all artists
musicFolderId:int If this is specified, it will only return
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 time
Returns a dict like the following:
{u'indexes': {u'index': [{u'artist': [{u'id': u'29834728934',
u'name': u'A Perfect Circle'},
{u'id': u'238472893',
u'name': u'A Small Good Thing'},
{u'id': u'9327842983',
u'name': u'A Tribe Called Quest'},
{u'id': u'29348729874',
u'name': u'A-Teens, The'},
{u'id': u'298472938',
u'name': u'ABA STRUCTURE'}] ,
u'lastModified': 1303318347000L},
u'status': u'ok',
u'version': u'1.5.0',
u'xmlns': u'http://subsonic.org/restapi'}
"""
methodName = 'getIndexes'
viewName = '%s.view' % methodName
q = self._getQueryDict({'musicFolderId': musicFolderId ,
'ifModifiedSince': self._ts2milli(ifModifiedSince)})
req = self._getRequest(viewName , q)
res = self._doInfoReq(req)
self._checkStatus(res)
return res
def getMusicDirectory(self , mid):
"""
since: 1.0.0
Returns a listing of all files in a music directory. Typically used
to get a list of albums for an artist or list of songs for an album.
mid:str The string ID value which uniquely identifies the
folder. Obtained via calls to getIndexes or
getMusicDirectory. REQUIRED
Returns a dict like the following:
{u'directory': {u'child': [{u'artist': u'A Tribe Called Quest',
u'coverArt': u'223484',
u'id': u'329084',
u'isDir': True,
u'parent': u'234823940',
u'title': u'Beats, Rhymes And Life'},
{u'artist': u'A Tribe Called Quest',
u'coverArt': u'234823794',
u'id': u'238472893',
u'isDir': True,
u'parent': u'2308472938',
u'title': u'Midnight Marauders'},
{u'artist': u'A Tribe Called Quest',
u'coverArt': u'39284792374',
u'id': u'983274892',
u'isDir': True,
u'parent': u'9823749',
u'title': u"People's Instinctive Travels And The Paths Of Rhythm"},
{u'artist': u'A Tribe Called Quest',
u'coverArt': u'289347293',
u'id': u'3894723934',
u'isDir': True,
u'parent': u'9832942',
u'title': u'The Anthology'},
{u'artist': u'A Tribe Called Quest',
u'coverArt': u'923847923',
u'id': u'29834729',
u'isDir': True,
u'parent': u'2934872893',
u'title': u'The Love Movement'},
{u'artist': u'A Tribe Called Quest',
u'coverArt': u'9238742893',
u'id': u'238947293',
u'isDir': True,
u'parent': u'9432878492',
u'title': u'The Low End Theory'}],
u'id': u'329847293',
u'name': u'A Tribe Called Quest'},
u'status': u'ok',
u'version': u'1.5.0',
u'xmlns': u'http://subsonic.org/restapi'}
"""
methodName = 'getMusicDirectory'
viewName = '%s.view' % methodName
req = self._getRequest(viewName , {'id': mid})
res = self._doInfoReq(req)
self._checkStatus(res)
return res
def search(self , artist=None , album=None , title=None , any=None ,
count=20 , offset=0 , newerThan=None):
"""
since: 1.0.0
DEPRECATED SINCE API 1.4.0! USE search2() INSTEAD!
Returns a listing of files matching the given search criteria.
Supports paging with offset
artist:str Search for artist
album:str Search for album
title:str Search for title of song
any:str Search all fields
count:int Max number of results to return [default: 20]
offset:int Search result offset. For paging [default: 0]
newerThan:int Return matches newer than this timestamp
"""
if artist == album == title == any == None:
raise ArgumentError('Invalid search. You must supply search '
'criteria')
methodName = 'search'
viewName = '%s.view' % methodName
q = self._getQueryDict({'artist': artist , 'album': album ,
'title': title , 'any': any , 'count': count , 'offset': offset ,
'newerThan': self._ts2milli(newerThan)})
req = self._getRequest(viewName , q)
res = self._doInfoReq(req)
self._checkStatus(res)
return res
def search2(self , query , artistCount=20 , artistOffset=0 , albumCount=20 ,
albumOffset=0 , songCount=20 , songOffset=0):
"""
since: 1.4.0
Returns albums, artists and songs matching the given search criteria.
Supports paging through the result.
query:str The search query
artistCount:int Max number of artists to return [default: 20]
artistOffset:int Search offset for artists (for paging) [default: 0]
albumCount:int Max number of albums to return [default: 20]
albumOffset:int Search offset for albums (for paging) [default: 0]
songCount:int Max number of songs to return [default: 20]
songOffset:int Search offset for songs (for paging) [default: 0]
Returns a dict like the following:
{u'searchResult2': {u'album': [{u'artist': u'A Tribe Called Quest',
u'coverArt': u'289347',
u'id': u'32487298',
u'isDir': True,
u'parent': u'98374289',
u'title': u'The Love Movement'}],
u'artist': [{u'id': u'2947839',
u'name': u'A Tribe Called Quest'},
{u'id': u'239847239',
u'name': u'Tribe'}],
u'song': [{u'album': u'Beats, Rhymes And Life',
u'artist': u'A Tribe Called Quest',
u'bitRate': 224,
u'contentType': u'audio/mpeg',
u'coverArt': u'329847',
u'duration': 148,
u'genre': u'default',
u'id': u'3928472893',
u'isDir': False,
u'isVideo': False,
u'parent': u'23984728394',
u'path': u'A Tribe Called Quest/Beats, Rhymes And Life/A Tribe Called Quest - Beats, Rhymes And Life - 03 - Motivators.mp3',
u'size': 4171913,
u'suffix': u'mp3',
u'title': u'Motivators',
u'track': 3}]},
u'status': u'ok',
u'version': u'1.5.0',
u'xmlns': u'http://subsonic.org/restapi'}
"""
methodName = 'search2'
viewName = '%s.view' % methodName
q = {'query': query , 'artistCount': artistCount ,
'artistOffset': artistOffset , 'albumCount': albumCount ,
'albumOffset': albumOffset , 'songCount': songCount ,
'songOffset': songOffset}
req = self._getRequest(viewName , q)
res = self._doInfoReq(req)
self._checkStatus(res)
return res
def search3(self , query , artistCount=20 , artistOffset=0 , albumCount=20 ,
albumOffset=0 , songCount=20 , songOffset=0):
"""
since: 1.8.0
Works the same way as search2, but uses ID3 tags for
organization
query:str The search query
artistCount:int Max number of artists to return [default: 20]
artistOffset:int Search offset for artists (for paging) [default: 0]
albumCount:int Max number of albums to return [default: 20]
albumOffset:int Search offset for albums (for paging) [default: 0]
songCount:int Max number of songs to return [default: 20]
songOffset:int Search offset for songs (for paging) [default: 0]
Returns a dict like the following (search for "Tune Yards":
{u'searchResult3': {u'album': [{u'artist': u'Tune-Yards',
u'artistId': 1,
u'coverArt': u'al-7',
u'created': u'2012-01-30T12:35:33',
u'duration': 3229,
u'id': 7,
u'name': u'Bird-Brains',
u'songCount': 13},
{u'artist': u'Tune-Yards',
u'artistId': 1,
u'coverArt': u'al-8',
u'created': u'2011-03-22T15:08:00',
u'duration': 2531,
u'id': 8,
u'name': u'W H O K I L L',
u'songCount': 10}],
u'artist': {u'albumCount': 2,
u'coverArt': u'ar-1',
u'id': 1,
u'name': u'Tune-Yards'},
u'song': [{u'album': u'Bird-Brains',
u'albumId': 7,
u'artist': u'Tune-Yards',
u'artistId': 1,
u'bitRate': 160,
u'contentType': u'audio/mpeg',
u'coverArt': 105,
u'created': u'2012-01-30T12:35:33',
u'duration': 328,
u'genre': u'Lo-Fi',
u'id': 107,
u'isDir': False,
u'isVideo': False,
u'parent': 105,
u'path': u'Tune Yards/Bird-Brains/10-tune-yards-fiya.mp3',
u'size': 6588498,
u'suffix': u'mp3',
u'title': u'Fiya',
u'track': 10,
u'type': u'music',
u'year': 2009}]},
u'status': u'ok',
u'version': u'1.5.0',
u'xmlns': u'http://subsonic.org/restapi'}
"""
methodName = 'search3'
viewName = '%s.view' % methodName
q = {'query': query , 'artistCount': artistCount ,
'artistOffset': artistOffset , 'albumCount': albumCount ,
'albumOffset': albumOffset , 'songCount': songCount ,
'songOffset': songOffset}
req = self._getRequest(viewName , q)
res = self._doInfoReq(req)
self._checkStatus(res)
return res
def getPlaylists(self , username=None):
"""
since: 1.0.0
Returns the ID and name of all saved playlists
The "username" option was added in 1.8.0.
username:str If specified, return playlists for this user
rather than for the authenticated user. The
authenticated user must have admin role
if this parameter is used
Returns a dict like the following:
{u'playlists': {u'playlist': [{u'id': u'62656174732e6d3375',
u'name': u'beats'},
{u'id': u'766172696574792e6d3375',
u'name': u'variety'}]},
u'status': u'ok',
u'version': u'1.5.0',
u'xmlns': u'http://subsonic.org/restapi'}
"""
methodName = 'getPlaylists'
viewName = '%s.view' % methodName
q = self._getQueryDict({'username': username})
req = self._getRequest(viewName , q)
res = self._doInfoReq(req)
self._checkStatus(res)
return res
def getPlaylist(self , pid):
"""
since: 1.0.0
Returns a listing of files in a saved playlist
id:str The ID of the playlist as returned in getPlaylists()
Returns a dict like the following:
{u'playlist': {u'entry': {u'album': u'The Essential Bob Dylan',
u'artist': u'Bob Dylan',
u'bitRate': 32,
u'contentType': u'audio/mpeg',
u'coverArt': u'2983478293',
u'duration': 984,
u'genre': u'Classic Rock',
u'id': u'982739428',
u'isDir': False,
u'isVideo': False,
u'parent': u'98327428974',
u'path': u"Bob Dylan/Essential Bob Dylan Disc 1/Bob Dylan - The Essential Bob Dylan - 03 - The Times They Are A-Changin'.mp3",
u'size': 3921899,
u'suffix': u'mp3',
u'title': u"The Times They Are A-Changin'",
u'track': 3},
u'id': u'44796c616e2e6d3375',
u'name': u'Dylan'},
u'status': u'ok',
u'version': u'1.5.0',
u'xmlns': u'http://subsonic.org/restapi'}
"""
methodName = 'getPlaylist'
viewName = '%s.view' % methodName
req = self._getRequest(viewName , {'id': pid})
res = self._doInfoReq(req)
self._checkStatus(res)
return res
def createPlaylist(self , playlistId=None , name=None , songIds=[]):
"""
since: 1.2.0
Creates OR updates a playlist. If updating the list, the
playlistId is required. If creating a list, the name is required.
playlistId:str The ID of the playlist to UPDATE
name:str The name of the playlist to CREATE
songIds:list The list of songIds to populate the list with in
either create or update mode. Note that this
list will replace the existing list if updating
Returns a dict like the following:
{u'status': u'ok',
u'version': u'1.5.0',
u'xmlns': u'http://subsonic.org/restapi'}
"""
methodName = 'createPlaylist'
viewName = '%s.view' % methodName
if playlistId == name == None:
raise ArgumentError('You must supply either a playlistId or a name')
if playlistId is not None and name is not None:
raise ArgumentError('You can only supply either a playlistId '
'OR a name, not both')
q = self._getQueryDict({'playlistId': playlistId , 'name': name})
req = self._getRequestWithList(viewName , 'songId' , songIds , q)
res = self._doInfoReq(req)
self._checkStatus(res)
return res
def deletePlaylist(self , pid):
"""
since: 1.2.0
Deletes a saved playlist
pid:str ID of the playlist to delete, as obtained by getPlaylists
Returns a dict like the following:
"""
methodName = 'deletePlaylist'
viewName = '%s.view' % methodName
req = self._getRequest(viewName , {'id': pid})
res = self._doInfoReq(req)
self._checkStatus(res)
return res
def download(self , sid):
"""
since: 1.0.0
Downloads a given music file.
sid:str The ID of the music file to download.
Returns the file-like object for reading or raises an exception
on error
"""
methodName = 'download'
viewName = '%s.view' % methodName
req = self._getRequest(viewName , {'id': sid})
res = self._doBinReq(req)
if isinstance(res , dict):
self._checkStatus(res)
return res
def stream(self , sid , maxBitRate=0 , tformat=None , timeOffset=None ,
size=None , estimateContentLength=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
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})
req = self._getRequest(viewName , q)
res = self._doBinReq(req)
if isinstance(res , dict):
self._checkStatus(res)
return res
def getCoverArt(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)
res = self._doBinReq(req)
if isinstance(res , dict):
self._checkStatus(res)
return res
def scrobble(self , sid , submission=True , listenTime=None):
"""
since: 1.5.0
"Scrobbles" a given music file on last.fm. Requires that the user
has set this up.
Since 1.8.0 you may specify multiple id (and optionally time)
parameters to scrobble multiple files.
Since 1.11.0 this method will also update the play count and
last played timestamp for the song and album. It will also make
the song appear in the "Now playing" page in the web app, and
appear in the list of songs returned by getNowPlaying
sid:str The ID of the file to scrobble
submission:bool Whether this is a "submission" or a "now playing"
notification
listenTime:int (Since 1.8.0) The time (unix timestamp) at
which the song was listened to.
Returns a dict like the following:
{u'status': u'ok',
u'version': u'1.5.0',
u'xmlns': u'http://subsonic.org/restapi'}
"""
methodName = 'scrobble'
viewName = '%s.view' % methodName
q = self._getQueryDict({'id': sid , 'submission': submission ,
'time': self._ts2milli(listenTime)})
req = self._getRequest(viewName , q)
res = self._doInfoReq(req)
self._checkStatus(res)
return res
def changePassword(self , username , password):
"""
since: 1.1.0
Changes the password of an existing Subsonic user. Note that the
user performing this must have admin privileges
username:str The username whose password is being changed
password:str The new password of the user
Returns a dict like the following:
{u'status': u'ok',
u'version': u'1.5.0',
u'xmlns': u'http://subsonic.org/restapi'}
"""
methodName = 'changePassword'
viewName = '%s.view' % methodName
hexPass = 'enc:%s' % self._hexEnc(password)
# There seems to be an issue with some subsonic implementations
# not recognizing the "enc:" precursor to the encoded password and
# encodes the whole "enc:<hex>" as the password. Weird.
#q = {'username': username , 'password': hexPass.lower()}
q = {'username': username , 'password': password}
req = self._getRequest(viewName , q)
res = self._doInfoReq(req)
self._checkStatus(res)
return res
def getUser(self , username):
"""
since: 1.3.0
Get details about a given user, including which auth roles it has.
Can be used to enable/disable certain features in the client, such
as jukebox control
username:str The username to retrieve. You can only retrieve
your own user unless you have admin privs.
Returns a dict like the following:
{u'status': u'ok',
u'user': {u'adminRole': False,
u'commentRole': False,
u'coverArtRole': False,
u'downloadRole': True,
u'jukeboxRole': False,
u'playlistRole': True,
u'podcastRole': False,
u'settingsRole': True,
u'streamRole': True,
u'uploadRole': True,
u'username': u'test'},
u'version': u'1.5.0',
u'xmlns': u'http://subsonic.org/restapi'}
"""
methodName = 'getUser'
viewName = '%s.view' % methodName
q = {'username': username}
req = self._getRequest(viewName , q)
res = self._doInfoReq(req)
self._checkStatus(res)
return res
def getUsers(self):
"""
since 1.8.0
Gets a list of users
returns a dict like the following
{u'status': u'ok',
u'users': {u'user': [{u'adminRole': True,
u'commentRole': True,
u'coverArtRole': True,
u'downloadRole': True,
u'jukeboxRole': True,
u'playlistRole': True,
u'podcastRole': True,
u'scrobblingEnabled': True,
u'settingsRole': True,
u'shareRole': True,
u'streamRole': True,
u'uploadRole': True,
u'username': u'user1'},
...
...
]} ,
u'version': u'1.10.2',
u'xmlns': u'http://subsonic.org/restapi'}
"""
methodName = 'getUsers'
viewName = '%s.view' % methodName
req = self._getRequest(viewName)
res = self._doInfoReq(req)
self._checkStatus(res)
return res
def createUser(self , username , password , email ,
ldapAuthenticated=False , adminRole=False , settingsRole=True ,
streamRole=True , jukeboxRole=False , downloadRole=False ,
uploadRole=False , playlistRole=False , coverArtRole=False ,
commentRole=False , podcastRole=False , shareRole=False):
"""
since: 1.1.0
Creates a new subsonic user, using the parameters defined. See the
documentation at http://subsonic.org for more info on all the roles.
username:str The username of the new user
password:str The password for the new user
email:str The email of the new user
<For info on the boolean roles, see http://subsonic.org for more info>
Returns a dict like the following:
{u'status': u'ok',
u'version': u'1.5.0',
u'xmlns': u'http://subsonic.org/restapi'}
"""
methodName = 'createUser'
viewName = '%s.view' % methodName
hexPass = 'enc:%s' % self._hexEnc(password)
q = {'username': username , 'password': hexPass , 'email': email ,
'ldapAuthenticated': ldapAuthenticated , 'adminRole': adminRole ,
'settingsRole': settingsRole , 'streamRole': streamRole ,
'jukeboxRole': jukeboxRole , 'downloadRole': downloadRole ,
'uploadRole': uploadRole , 'playlistRole': playlistRole ,
'coverArtRole': coverArtRole , 'commentRole': commentRole ,
'podcastRole': podcastRole , 'shareRole': shareRole}
req = self._getRequest(viewName , q)
res = self._doInfoReq(req)
self._checkStatus(res)
return res
def updateUser(self , username , password=None , email=None ,
ldapAuthenticated=False , adminRole=False , settingsRole=True ,
streamRole=True , jukeboxRole=False , downloadRole=False ,
uploadRole=False , playlistRole=False , coverArtRole=False ,
commentRole=False , podcastRole=False , shareRole=False):
"""
since 1.10.1
Modifies an existing Subsonic user.
username:str The username of the user to update.
All other args are the same as create user and you can update
whatever item you wish to update for the given username.
Returns a dict like the following:
{u'status': u'ok',
u'version': u'1.5.0',
u'xmlns': u'http://subsonic.org/restapi'}
"""
methodName = 'updateUser'
viewName = '%s.view' % methodName
if password is not None:
password = 'enc:%s' % self._hexEnc(password)
q = self._getQueryDict({'username': username , 'password': password ,
'email': email , 'ldapAuthenticated': ldapAuthenticated ,
'adminRole': adminRole ,
'settingsRole': settingsRole , 'streamRole': streamRole ,
'jukeboxRole': jukeboxRole , 'downloadRole': downloadRole ,
'uploadRole': uploadRole , 'playlistRole': playlistRole ,
'coverArtRole': coverArtRole , 'commentRole': commentRole ,
'podcastRole': podcastRole , 'shareRole': shareRole})