2 # Copyright (C) 2004, 2005, 2007 Richard Kettlewell
4 # This program is free software; you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation; either version 2 of the License, or
7 # (at your option) any later version.
9 # This program is distributed in the hope that it will be useful, but
10 # WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 # General Public License for more details.
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
20 """Python support for DisOrder
22 Provides disorder.client, a class for accessing a DisOrder server.
26 #! /usr/bin/env python
35 #! /usr/bin/env python
39 for path in sys.argv[1:]:
42 See disorder_protocol(5) for details of the communication protocol.
44 NB that this code only supports servers configured to use SHA1-based
45 authentication. If the server demands another hash then it will not be
46 possible to use this module.
59 _configfile = "pkgconfdir/config"
60 _dbhome = "pkgstatedir"
63 # various regexps we'll use
64 _ws = re.compile(r"^[ \t\n\r]+")
65 _squote = re.compile("'(([^\\\\']|\\\\[\\\\\"'n])+)'")
66 _dquote = re.compile("\"(([^\\\\\"]|\\\\[\\\\\"'n])+)\"")
67 _unquoted = re.compile("[^\"' \\t\\n\\r][^ \t\n\r]*")
69 _response = re.compile("([0-9]{3}) ?(.*)")
73 ########################################################################
76 class Error(Exception):
77 """Base class for DisOrder exceptions."""
79 class _splitError(Error):
81 def __init__(self, value):
84 return str(self.value)
86 class parseError(Error):
87 """Error parsing the configuration file."""
88 def __init__(self, path, line, details):
91 self.details = details
93 return "%s:%d: %s" % (self.path, self.line, self.details)
95 class protocolError(Error):
96 """DisOrder control protocol error.
98 Indicates a mismatch between the client and server's understanding of
101 def __init__(self, who, error):
105 return "%s: %s" % (self.who, str(self.error))
107 class operationError(Error):
108 """DisOrder control protocol error response.
110 Indicates that an operation failed (e.g. an attempt to play a
111 nonexistent track). The connection should still be usable.
113 def __init__(self, res, details, cmd=None):
116 self.details_ = details
118 """Return the complete response string from the server, with the command
121 Excludes the final newline.
123 if self.cmd_ is None:
124 return "%d %s" % (self.res_, self.details_)
126 return "%d %s [%s]" % (self.res_, self.details_, self.cmd_)
128 """Return the response code from the server."""
131 """Returns the detail string from the server."""
134 class communicationError(Error):
135 """DisOrder control protocol communication error.
137 Indicates that communication with the server went wrong, perhaps
138 because the server was restarted. The caller could report an error to
139 the user and wait for further user instructions, or even automatically
142 def __init__(self, who, error):
146 return "%s: %s" % (self.who, str(self.error))
148 ########################################################################
149 # DisOrder-specific text processing
152 # Unescape the contents of a string
156 # s -- string to unescape
158 s = re.sub("\\\\n", "\n", s)
159 s = re.sub("\\\\(.)", "\\1", s)
162 def _split(s, *comments):
163 # Split a string into fields according to the usual Disorder string splitting
168 # s -- string to parse
169 # comments -- if present, parse comments
173 # On success, a list of fields is returned.
175 # On error, disorder.parseError is thrown.
180 if comments and s[0] == '#':
187 # pick of quoted fields of both kinds
192 fields.append(_unescape(m.group(1)))
195 # and unquoted fields
196 m = _unquoted.match(s)
198 fields.append(m.group(0))
201 # anything left must be in error
202 if s[0] == '"' or s[0] == '\'':
203 raise _splitError("invalid quoted string")
205 raise _splitError("syntax error")
209 # Escape the contents of a string
213 # s -- string to escape
215 if re.search("[\\\\\"'\n \t\r]", s) or s == '':
216 s = re.sub(r'[\\"]', r'\\\g<0>', s)
217 s = re.sub("\n", r"\\n", s)
223 # Quote a list of values
224 return ' '.join(map(_escape, list))
227 # Return the value of s in a form suitable for writing to stderr
228 return s.encode(locale.nl_langinfo(locale.CODESET), 'replace')
231 # Convert a list of the form [k1, v1, k2, v2, ..., kN, vN]
232 # to a dictionary {k1:v1, k2:v2, ..., kN:vN}
240 except StopIteration:
245 # parse a queue entry
246 return _list2dict(_split(s))
248 ########################################################################
252 """DisOrder client class.
254 This class provides access to the DisOrder server either on this
255 machine or across the internet.
257 The server to connect to, and the username and password to use, are
258 determined from the configuration files as described in 'man
261 All methods will connect if necessary, as soon as you have a
262 disorder.client object you can start calling operational methods on
265 However if the server is restarted then the next method called on a
266 connection will throw an exception. This may be considered a bug.
268 All methods block until they complete.
270 Operation methods raise communicationError if the connection breaks,
271 protocolError if the response from the server is malformed, or
272 operationError if the response is valid but indicates that the
280 """Constructor for DisOrder client class.
282 The constructor reads the configuration file, but does not connect
285 If the environment variable DISORDER_PYTHON_DEBUG is set then the
286 debug flags are initialised to that value. This can be overridden
287 with the debug() method below.
289 The constructor Raises parseError() if the configuration file is not
292 pw = pwd.getpwuid(os.getuid())
293 self.debugging = int(os.getenv("DISORDER_PYTHON_DEBUG", 0))
294 self.config = { 'collections': [],
295 'username': pw.pw_name,
297 home = os.getenv("HOME")
300 privconf = _configfile + "." + pw.pw_name
301 passfile = home + os.sep + ".disorder" + os.sep + "passwd"
302 if os.path.exists(_configfile):
303 self._readfile(_configfile)
304 if os.path.exists(privconf):
305 self._readfile(privconf)
306 if os.path.exists(passfile) and _userconf:
307 self._readfile(passfile)
308 self.state = 'disconnected'
310 def debug(self, bits):
311 """Enable or disable protocol debugging. Debug messages are written
315 bits -- bitmap of operations that should generate debug information
318 debug_proto -- dump control protocol messages (excluding bodies)
319 debug_body -- dump control protocol message bodies
321 self.debugging = bits
323 def _debug(self, bit, s):
325 if self.debugging & bit:
326 sys.stderr.write(_sanitize(s))
327 sys.stderr.write("\n")
330 def connect(self, cookie=None):
331 """c.connect(cookie=None)
333 Connect to the DisOrder server and authenticate.
335 Raises communicationError if connection fails and operationError if
336 authentication fails (in which case disconnection is automatic).
338 May be called more than once to retry connections (e.g. when the
339 server is down). If we are already connected and authenticated,
342 Other operations automatically connect if we're not already
343 connected, so it is not strictly necessary to call this method.
345 If COOKIE is specified then that is used to log in instead of
346 the username/password.
348 if self.state == 'disconnected':
350 self.state = 'connecting'
351 if 'connect' in self.config and len(self.config['connect']) > 0:
352 c = self.config['connect']
353 self.who = repr(c) # temporarily
355 a = socket.getaddrinfo(None, c[0],
361 a = socket.getaddrinfo(c[0], c[1],
367 s = socket.socket(a[0], a[1], a[2]);
369 self.who = "%s" % a[3]
371 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM);
372 self.who = self.config['home'] + os.sep + "socket"
374 self.w = s.makefile("wb")
375 self.r = s.makefile("rb")
376 (res, challenge) = self._simple()
379 h.update(self.config['password'])
380 h.update(binascii.unhexlify(challenge))
381 self._simple("user", self.config['username'], h.hexdigest())
383 self._simple("cookie", cookie)
384 self.state = 'connected'
385 except socket.error, e:
387 raise communicationError(self.who, e)
392 def _disconnect(self):
393 # disconnect from the server, whatever state we are in
399 self.state = 'disconnected'
401 ########################################################################
404 def become(self, who):
405 """Become another user.
408 who -- the user to become.
410 Only trusted users can perform this operation.
412 self._simple("become", who)
414 def play(self, track):
418 track -- the path of the track to play.
420 Returns the ID of the new queue entry.
422 Note that queue IDs are unicode strings (because all track information
423 values are unicode strings).
425 res, details = self._simple("play", track)
426 return unicode(details) # because it's unicode in queue() output
428 def remove(self, track):
429 """Remove a track from the queue.
432 track -- the path or ID of the track to remove.
434 self._simple("remove", track)
437 """Enable playing."""
438 self._simple("enable")
440 def disable(self, *now):
444 now -- if present (with any value), the current track is stopped
448 self._simple("disable", "now")
450 self._simple("disable")
452 def scratch(self, *id):
453 """Scratch the currently playing track.
456 id -- if present, the ID of the track to scratch.
459 self._simple("scratch", id[0])
461 self._simple("scratch")
464 """Shut down the server.
466 Only trusted users can perform this operation.
468 self._simple("shutdown")
470 def reconfigure(self):
471 """Make the server reload its configuration.
473 Only trusted users can perform this operation.
475 self._simple("reconfigure")
477 def rescan(self, pattern):
478 """Rescan one or more collections.
481 pattern -- glob pattern matching collections to rescan.
483 Only trusted users can perform this operation.
485 self._simple("rescan", pattern)
488 """Return the server's version number."""
489 return self._simple("version")[1]
492 """Return the currently playing track.
494 If a track is playing then it is returned as a dictionary. See
495 disorder_protocol(5) for the meanings of the keys. All keys are
496 plain strings but the values will be unicode strings.
498 If no track is playing then None is returned."""
499 res, details = self._simple("playing")
502 return _queueEntry(details)
503 except _splitError, s:
504 raise protocolError(self.who, s.str())
508 def _somequeue(self, command):
509 self._simple(command)
511 return map(lambda s: _queueEntry(s), self._body())
512 except _splitError, s:
513 raise protocolError(self.who, s.str())
516 """Return a list of recently played tracks.
518 The return value is a list of dictionaries corresponding to
519 recently played tracks. The oldest track comes first.
521 See disorder_protocol(5) for the meanings of the keys. All keys are
522 plain strings but the values will be unicode strings."""
523 return self._somequeue("recent")
526 """Return the current queue.
528 The return value is a list of dictionaries corresponding to
529 recently played tracks. The next track to be played comes first.
531 See disorder_protocol(5) for the meanings of the keys. All keys are
532 plain strings but the values will be unicode strings."""
533 return self._somequeue("queue")
535 def _somedir(self, command, dir, re):
537 self._simple(command, dir, re[0])
539 self._simple(command, dir)
542 def directories(self, dir, *re):
543 """List subdirectories of a directory.
546 dir -- directory to list, or '' for the whole root.
547 re -- regexp that results must match. Optional.
549 The return value is a list of the (nonempty) subdirectories of dir.
550 If dir is '' then a list of top-level directories is returned.
552 If a regexp is specified then the basename of each result must
553 match. Matching is case-independent. See pcrepattern(3).
555 return self._somedir("dirs", dir, re)
557 def files(self, dir, *re):
558 """List files within a directory.
561 dir -- directory to list, or '' for the whole root.
562 re -- regexp that results must match. Optional.
564 The return value is a list of playable files in dir. If dir is ''
565 then a list of top-level files is returned.
567 If a regexp is specified then the basename of each result must
568 match. Matching is case-independent. See pcrepattern(3).
570 return self._somedir("files", dir, re)
572 def allfiles(self, dir, *re):
573 """List subdirectories and files within a directory.
576 dir -- directory to list, or '' for the whole root.
577 re -- regexp that results must match. Optional.
579 The return value is a list of all (nonempty) subdirectories and
580 files within dir. If dir is '' then a list of top-level files and
581 directories is returned.
583 If a regexp is specified then the basename of each result must
584 match. Matching is case-independent. See pcrepattern(3).
586 return self._somedir("allfiles", dir, re)
588 def set(self, track, key, value):
589 """Set a preference value.
592 track -- the track to modify
593 key -- the preference name
594 value -- the new preference value
596 self._simple("set", track, key, value)
598 def unset(self, track, key):
599 """Unset a preference value.
602 track -- the track to modify
603 key -- the preference to remove
605 self._simple("set", track, key, value)
607 def get(self, track, key):
608 """Get a preference value.
611 track -- the track to query
612 key -- the preference to remove
614 The return value is the preference.
616 ret, details = self._simple("get", track, key)
622 def prefs(self, track):
623 """Get all the preferences for a track.
626 track -- the track to query
628 The return value is a dictionary of all the track's preferences.
629 Note that even nominally numeric values remain encoded as strings.
631 self._simple("prefs", track)
633 for line in self._body():
636 except _splitError, s:
637 raise protocolError(self.who, s.str())
639 raise protocolError(self.who, "invalid prefs body line")
643 def _boolean(self, s):
646 def exists(self, track):
647 """Return true if a track exists
650 track -- the track to check for"""
651 return self._boolean(self._simple("exists", track))
654 """Return true if playing is enabled"""
655 return self._boolean(self._simple("enabled"))
657 def random_enabled(self):
658 """Return true if random play is enabled"""
659 return self._boolean(self._simple("random-enabled"))
661 def random_enable(self):
662 """Enable random play."""
663 self._simple("random-enable")
665 def random_disable(self):
666 """Disable random play."""
667 self._simple("random-disable")
669 def length(self, track):
670 """Return the length of a track in seconds.
673 track -- the track to query.
675 ret, details = self._simple("length", track)
678 def search(self, words):
679 """Search for tracks.
682 words -- the set of words to search for.
684 The return value is a list of track path names, all of which contain
685 all of the required words (in their path name, trackname
688 self._simple("search", _quote(words))
694 The return value is a list of all tags which apply to at least one
700 """Get server statistics.
702 The return value is list of statistics.
704 self._simple("stats")
708 """Get all preferences.
710 The return value is an encoded dump of the preferences database.
715 def set_volume(self, left, right):
719 left -- volume for the left speaker.
720 right -- volume for the right speaker.
722 self._simple("volume", left, right)
724 def get_volume(self):
727 The return value a tuple consisting of the left and right volumes.
729 ret, details = self._simple("volume")
730 return map(int,string.split(details))
732 def move(self, track, delta):
733 """Move a track in the queue.
736 track -- the name or ID of the track to move
737 delta -- the number of steps towards the head of the queue to move
739 ret, details = self._simple("move", track, str(delta))
742 def moveafter(self, target, tracks):
743 """Move a track in the queue
746 target -- target ID or None
747 tracks -- a list of IDs to move
749 If target is '' or is not in the queue then the tracks are moved to
750 the head of the queue.
752 Otherwise the tracks are moved to just after the target."""
755 self._simple("moveafter", target, *tracks)
757 def log(self, callback):
758 """Read event log entries as they happen.
760 Each event log entry is handled by passing it to callback.
762 The callback takes two arguments, the first is the client and the
763 second the line from the event log.
765 The callback should return True to continue or False to stop (don't
766 forget this, or your program will mysteriously misbehave).
768 It is suggested that you use the disorder.monitor class instead of
769 calling this method directly, but this is not mandatory.
771 See disorder_protocol(5) for the event log syntax.
774 callback -- function to call with log entry
776 ret, details = self._simple("log")
779 self._debug(client.debug_body, "<<< %s" % l)
780 if l != '' and l[0] == '.':
784 if not callback(self, l):
786 # tell the server to stop sending, eat the remains of the body,
788 self._send("version")
793 """Pause the current track."""
794 self._simple("pause")
797 """Resume after a pause."""
798 self._simple("resume")
800 def part(self, track, context, part):
801 """Get a track name part
804 track -- the track to query
805 context -- the context ('sort' or 'display')
806 part -- the desired part (usually 'artist', 'album' or 'title')
808 The return value is the preference
810 ret, details = self._simple("part", track, context, part)
813 def setglobal(self, key, value):
814 """Set a global preference value.
817 key -- the preference name
818 value -- the new preference value
820 self._simple("set-global", key, value)
822 def unsetglobal(self, key):
823 """Unset a global preference value.
826 key -- the preference to remove
828 self._simple("set-global", key, value)
830 def getglobal(self, key):
831 """Get a global preference value.
834 key -- the preference to look up
836 The return value is the preference
838 ret, details = self._simple("get-global", key)
844 def make_cookie(self):
845 """Create a login cookie"""
846 ret, details = self._simple("make-cookie")
850 """Revoke a login cookie"""
851 self._simple("revoke")
853 ########################################################################
857 # read one response line and return as some suitable string object
859 # If an I/O error occurs, disconnect from the server.
861 # XXX does readline() DTRT regarding character encodings?
863 l = self.r.readline()
864 if not re.search("\n", l):
865 raise communicationError(self.who, "peer disconnected")
870 return unicode(l, "UTF-8")
873 # read a response as a (code, details) tuple
875 self._debug(client.debug_proto, "<== %s" % l)
876 m = _response.match(l)
878 return int(m.group(1)), m.group(2)
880 raise protocolError(self.who, "invalid response %s")
882 def _send(self, *command):
883 # Quote and send a command
885 # Returns the encoded command.
886 quoted = _quote(command)
887 self._debug(client.debug_proto, "==> %s" % quoted)
888 encoded = quoted.encode("UTF-8")
890 self.w.write(encoded)
897 raise communicationError(self.who, e)
902 def _simple(self, *command):
903 # Issue a simple command, throw an exception on error
905 # If an I/O error occurs, disconnect from the server.
907 # On success or 'normal' errors returns response as a (code, details) tuple
909 # On error raise operationError
910 if self.state == 'disconnected':
913 cmd = self._send(*command)
916 res, details = self._response()
917 if res / 100 == 2 or res == 555:
919 raise operationError(res, details, cmd)
922 # Fetch a dot-stuffed body
926 self._debug(client.debug_body, "<<< %s" % l)
927 if l != '' and l[0] == '.':
933 ########################################################################
934 # Configuration file parsing
936 def _readfile(self, path):
937 # Read a configuration file
941 # path -- path of file to read
943 # handlers for various commands
944 def _collection(self, command, args):
946 return "'%s' takes three args" % command
947 self.config["collections"].append(args)
949 def _unary(self, command, args):
951 return "'%s' takes only one arg" % command
952 self.config[command] = args[0]
954 def _include(self, command, args):
956 return "'%s' takes only one arg" % command
957 self._readfile(args[0])
959 def _any(self, command, args):
960 self.config[command] = args
962 # mapping of options to handlers
963 _options = { "collection": _collection,
968 "include": _include }
971 for lno, line in enumerate(file(path, "r")):
973 fields = _split(line, 'comments')
974 except _splitError, s:
975 raise parseError(path, lno + 1, str(s))
978 # we just ignore options we don't know about, so as to cope gracefully
979 # with version skew (and nothing to do with implementor laziness)
980 if command in _options:
981 e = _options[command](self, command, fields[1:])
983 self._parseError(path, lno + 1, e)
985 def _parseError(self, path, lno, s):
986 raise parseError(path, lno, s)
988 ########################################################################
992 """DisOrder event log monitor class
994 Intended to be subclassed with methods corresponding to event log messages
995 the implementor cares about over-ridden."""
997 def __init__(self, c=None):
998 """Constructor for the monitor class
1000 Can be passed a client to use. If none is specified then one
1001 will be created specially for the purpose.
1010 """Start monitoring logs. Continues monitoring until one of the
1011 message-specific methods returns False. Can be called more than once
1012 (but not recursively!)"""
1013 self.c.log(self._callback)
1016 """Return the timestamp of the current (or most recent) event log entry"""
1017 return self.timestamp
1019 def _callback(self, c, line):
1023 return self.invalid(line)
1025 return self.invalid(line)
1026 self.timestamp = int(bits[0], 16)
1029 if keyword == 'completed':
1031 return self.completed(bits[0])
1032 elif keyword == 'failed':
1034 return self.failed(bits[0], bits[1])
1035 elif keyword == 'moved':
1040 return self.invalid(line)
1041 return self.moved(bits[0], n, bits[2])
1042 elif keyword == 'playing':
1044 return self.playing(bits[0], None)
1045 elif len(bits) == 2:
1046 return self.playing(bits[0], bits[1])
1047 elif keyword == 'queue' or keyword == 'recent-added':
1049 q = _list2dict(bits)
1051 return self.invalid(line)
1052 if keyword == 'queue':
1053 return self.queue(q)
1054 if keyword == 'recent-added':
1055 return self.recent_added(q)
1056 elif keyword == 'recent-removed':
1058 return self.recent_removed(bits[0])
1059 elif keyword == 'removed':
1061 return self.removed(bits[0], None)
1062 elif len(bits) == 2:
1063 return self.removed(bits[0], bits[1])
1064 elif keyword == 'scratched':
1066 return self.scratched(bits[0], bits[1])
1067 return self.invalid(line)
1069 def completed(self, track):
1070 """Called when a track completes.
1073 track -- track that completed"""
1076 def failed(self, track, error):
1077 """Called when a player suffers an error.
1080 track -- track that failed
1081 error -- error indicator"""
1084 def moved(self, id, offset, user):
1085 """Called when a track is moved in the queue.
1088 id -- queue entry ID
1089 offset -- distance moved
1090 user -- user responsible"""
1093 def playing(self, track, user):
1094 """Called when a track starts playing.
1097 track -- track that has started
1098 user -- user that submitted track, or None"""
1102 """Called when a track is added to the queue.
1105 q -- dictionary of new queue entry"""
1108 def recent_added(self, q):
1109 """Called when a track is added to the recently played list
1112 q -- dictionary of new queue entry"""
1115 def recent_removed(self, id):
1116 """Called when a track is removed from the recently played list
1119 id -- ID of removed entry (always the oldest)"""
1122 def removed(self, id, user):
1123 """Called when a track is removed from the queue, either manually
1124 or in order to play it.
1127 id -- ID of removed entry
1128 user -- user responsible (or None if we're playing this track)"""
1131 def scratched(self, track, user):
1132 """Called when a track is scratched
1135 track -- track that was scratched
1136 user -- user responsible"""
1139 def invalid(self, line):
1140 """Called when an event log line cannot be interpreted
1143 line -- line that could not be understood"""
1148 # py-indent-offset:2