2 # Copyright (C) 2004, 2005 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:]:
54 _configfile = "pkgconfdir/config"
55 _dbhome = "pkgstatedir"
58 # various regexps we'll use
59 _ws = re.compile(r"^[ \t\n\r]+")
60 _squote = re.compile("'(([^\\\\']|\\\\[\\\\\"'n])+)'")
61 _dquote = re.compile("\"(([^\\\\\"]|\\\\[\\\\\"'n])+)\"")
62 _unquoted = re.compile("[^\"' \\t\\n\\r][^ \t\n\r]*")
64 _response = re.compile("([0-9]{3}) ?(.*)")
68 ########################################################################
71 class Error(Exception):
72 """Base class for DisOrder exceptions."""
74 class _splitError(Error):
76 def __init__(self, value):
79 return str(self.value)
81 class parseError(Error):
82 """Error parsing the configuration file."""
83 def __init__(self, path, line, details):
86 self.details = details
88 return "%s:%d: %s" % (self.path, self.line, self.details)
90 class protocolError(Error):
91 """DisOrder control protocol error.
93 Indicates a mismatch between the client and server's understanding of
96 def __init__(self, who, error):
100 return "%s: %s" % (self.who, str(self.error))
102 class operationError(Error):
103 """DisOrder control protocol error response.
105 Indicates that an operation failed (e.g. an attempt to play a
106 nonexistent track). The connection should still be usable.
108 def __init__(self, res, details, cmd=None):
111 self.details_ = details
113 """Return the complete response string from the server, with the command
116 Excludes the final newline.
118 if self.cmd_ is None:
119 return "%d %s" % (self.res_, self.details_)
121 return "%d %s [%s]" % (self.res_, self.details_, self.cmd_)
123 """Return the response code from the server."""
126 """Returns the detail string from the server."""
129 class communicationError(Error):
130 """DisOrder control protocol communication error.
132 Indicates that communication with the server went wrong, perhaps
133 because the server was restarted. The caller could report an error to
134 the user and wait for further user instructions, or even automatically
137 def __init__(self, who, error):
141 return "%s: %s" % (self.who, str(self.error))
143 ########################################################################
144 # DisOrder-specific text processing
147 # Unescape the contents of a string
151 # s -- string to unescape
153 s = re.sub("\\\\n", "\n", s)
154 s = re.sub("\\\\(.)", "\\1", s)
157 def _split(s, *comments):
158 # Split a string into fields according to the usual Disorder string splitting
163 # s -- string to parse
164 # comments -- if present, parse comments
168 # On success, a list of fields is returned.
170 # On error, disorder.parseError is thrown.
175 if comments and s[0] == '#':
182 # pick of quoted fields of both kinds
187 fields.append(_unescape(m.group(1)))
190 # and unquoted fields
191 m = _unquoted.match(s)
193 fields.append(m.group(0))
196 # anything left must be in error
197 if s[0] == '"' or s[0] == '\'':
198 raise _splitError("invalid quoted string")
200 raise _splitError("syntax error")
204 # Escape the contents of a string
208 # s -- string to escape
210 if re.search("[\\\\\"'\n \t\r]", s) or s == '':
211 s = re.sub(r'[\\"]', r'\\\g<0>', s)
212 s = re.sub("\n", r"\\n", s)
218 # Quote a list of values
219 return ' '.join(map(_escape, list))
222 # Return the value of s in a form suitable for writing to stderr
223 return s.encode(locale.nl_langinfo(locale.CODESET), 'replace')
226 # Convert a list of the form [k1, v1, k2, v2, ..., kN, vN]
227 # to a dictionary {k1:v1, k2:v2, ..., kN:vN}
235 except StopIteration:
240 # parse a queue entry
241 return _list2dict(_split(s))
243 ########################################################################
247 """DisOrder client class.
249 This class provides access to the DisOrder server either on this
250 machine or across the internet.
252 The server to connect to, and the username and password to use, are
253 determined from the configuration files as described in 'man
256 All methods will connect if necessary, as soon as you have a
257 disorder.client object you can start calling operational methods on
260 However if the server is restarted then the next method called on a
261 connection will throw an exception. This may be considered a bug.
263 All methods block until they complete.
265 Operation methods raise communicationError if the connection breaks,
266 protocolError if the response from the server is malformed, or
267 operationError if the response is valid but indicates that the
275 """Constructor for DisOrder client class.
277 The constructor reads the configuration file, but does not connect
280 If the environment variable DISORDER_PYTHON_DEBUG is set then the
281 debug flags are initialised to that value. This can be overridden
282 with the debug() method below.
284 The constructor Raises parseError() if the configuration file is not
287 pw = pwd.getpwuid(os.getuid())
288 self.debugging = int(os.getenv("DISORDER_PYTHON_DEBUG", 0))
289 self.config = { 'collections': [],
290 'username': pw.pw_name,
292 home = os.getenv("HOME")
295 privconf = _configfile + "." + pw.pw_name
296 passfile = home + os.sep + ".disorder" + os.sep + "passwd"
297 if os.path.exists(_configfile):
298 self._readfile(_configfile)
299 if os.path.exists(privconf):
300 self._readfile(privconf)
301 if os.path.exists(passfile) and _userconf:
302 self._readfile(passfile)
303 self.state = 'disconnected'
305 def debug(self, bits):
306 """Enable or disable protocol debugging. Debug messages are written
310 bits -- bitmap of operations that should generate debug information
313 debug_proto -- dump control protocol messages (excluding bodies)
314 debug_body -- dump control protocol message bodies
316 self.debugging = bits
318 def _debug(self, bit, s):
320 if self.debugging & bit:
321 sys.stderr.write(_sanitize(s))
322 sys.stderr.write("\n")
326 """Connect to the DisOrder server and authenticate.
328 Raises communicationError if connection fails and operationError if
329 authentication fails (in which case disconnection is automatic).
331 May be called more than once to retry connections (e.g. when the
332 server is down). If we are already connected and authenticated,
335 Other operations automatically connect if we're not already
336 connected, so it is not strictly necessary to call this method.
338 if self.state == 'disconnected':
340 self.state = 'connecting'
341 if 'connect' in self.config and len(self.config['connect']) > 0:
342 c = self.config['connect']
343 self.who = repr(c) # temporarily
345 a = socket.getaddrinfo(None, c[0],
351 a = socket.getaddrinfo(c[0], c[1],
357 s = socket.socket(a[0], a[1], a[2]);
359 self.who = "%s" % a[3]
361 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM);
362 self.who = self.config['home'] + os.sep + "socket"
364 self.w = s.makefile("wb")
365 self.r = s.makefile("rb")
366 (res, challenge) = self._simple()
368 h.update(self.config['password'])
369 h.update(binascii.unhexlify(challenge))
370 self._simple("user", self.config['username'], h.hexdigest())
371 self.state = 'connected'
372 except socket.error, e:
374 raise communicationError(self.who, e)
379 def _disconnect(self):
380 # disconnect from the server, whatever state we are in
386 self.state = 'disconnected'
388 ########################################################################
391 def become(self, who):
392 """Become another user.
395 who -- the user to become.
397 Only trusted users can perform this operation.
399 self._simple("become", who)
401 def play(self, track):
405 track -- the path of the track to play.
407 self._simple("play", track)
409 def remove(self, track):
410 """Remove a track from the queue.
413 track -- the path or ID of the track to remove.
415 self._simple("remove", track)
418 """Enable playing."""
419 self._simple("enable")
421 def disable(self, *now):
425 now -- if present (with any value), the current track is stopped
429 self._simple("disable", "now")
431 self._simple("disable")
433 def scratch(self, *id):
434 """Scratch the currently playing track.
437 id -- if present, the ID of the track to scratch.
440 self._simple("scratch", id[0])
442 self._simple("scratch")
445 """Shut down the server.
447 Only trusted users can perform this operation.
449 self._simple("shutdown")
451 def reconfigure(self):
452 """Make the server reload its configuration.
454 Only trusted users can perform this operation.
456 self._simple("reconfigure")
458 def rescan(self, pattern):
459 """Rescan one or more collections.
462 pattern -- glob pattern matching collections to rescan.
464 Only trusted users can perform this operation.
466 self._simple("rescan", pattern)
469 """Return the server's version number."""
470 return self._simple("version")[1]
473 """Return the currently playing track.
475 If a track is playing then it is returned as a dictionary.
476 If no track is playing then None is returned."""
477 res, details = self._simple("playing")
480 return _queueEntry(details)
481 except _splitError, s:
482 raise protocolError(self.who, s.str())
486 def _somequeue(self, command):
487 self._simple(command)
489 return map(lambda s: _queueEntry(s), self._body())
490 except _splitError, s:
491 raise protocolError(self.who, s.str())
494 """Return a list of recently played tracks.
496 The return value is a list of dictionaries corresponding to
497 recently played tracks. The oldest track comes first."""
498 return self._somequeue("recent")
501 """Return the current queue.
503 The return value is a list of dictionaries corresponding to
504 recently played tracks. The next track to be played comes first."""
505 return self._somequeue("queue")
507 def _somedir(self, command, dir, re):
509 self._simple(command, dir, re[0])
511 self._simple(command, dir)
514 def directories(self, dir, *re):
515 """List subdirectories of a directory.
518 dir -- directory to list, or '' for the whole root.
519 re -- regexp that results must match. Optional.
521 The return value is a list of the (nonempty) subdirectories of dir.
522 If dir is '' then a list of top-level directories is returned.
524 If a regexp is specified then the basename of each result must
525 match. Matching is case-independent. See pcrepattern(3).
527 return self._somedir("dirs", dir, re)
529 def files(self, dir, *re):
530 """List files within a directory.
533 dir -- directory to list, or '' for the whole root.
534 re -- regexp that results must match. Optional.
536 The return value is a list of playable files in dir. If dir is ''
537 then a list of top-level files is returned.
539 If a regexp is specified then the basename of each result must
540 match. Matching is case-independent. See pcrepattern(3).
542 return self._somedir("files", dir, re)
544 def allfiles(self, dir, *re):
545 """List subdirectories and files within a directory.
548 dir -- directory to list, or '' for the whole root.
549 re -- regexp that results must match. Optional.
551 The return value is a list of all (nonempty) subdirectories and
552 files within dir. If dir is '' then a list of top-level files and
553 directories is returned.
555 If a regexp is specified then the basename of each result must
556 match. Matching is case-independent. See pcrepattern(3).
558 return self._somedir("allfiles", dir, re)
560 def set(self, track, key, value):
561 """Set a preference value.
564 track -- the track to modify
565 key -- the preference name
566 value -- the new preference value
568 self._simple("set", track, key, value)
570 def unset(self, track, key):
571 """Unset a preference value.
574 track -- the track to modify
575 key -- the preference to remove
577 self._simple("set", track, key, value)
579 def get(self, track, key):
580 """Get a preference value.
583 track -- the track to query
584 key -- the preference to remove
586 The return value is the preference
588 ret, details = self._simple("get", track, key)
594 def prefs(self, track):
595 """Get all the preferences for a track.
598 track -- the track to query
600 The return value is a dictionary of all the track's preferences.
601 Note that even nominally numeric values remain encoded as strings.
603 self._simple("prefs", track)
605 for line in self._body():
608 except _splitError, s:
609 raise protocolError(self.who, s.str())
611 raise protocolError(self.who, "invalid prefs body line")
615 def _boolean(self, s):
618 def exists(self, track):
619 """Return true if a track exists
622 track -- the track to check for"""
623 return self._boolean(self._simple("exists", track))
626 """Return true if playing is enabled"""
627 return self._boolean(self._simple("enabled"))
629 def random_enabled(self):
630 """Return true if random play is enabled"""
631 return self._boolean(self._simple("random-enabled"))
633 def random_enable(self):
634 """Enable random play."""
635 self._simple("random-enable")
637 def random_disable(self):
638 """Disable random play."""
639 self._simple("random-disable")
641 def length(self, track):
642 """Return the length of a track in seconds.
645 track -- the track to query.
647 ret, details = self._simple("length", track)
650 def search(self, words):
651 """Search for tracks.
654 words -- the set of words to search for.
656 The return value is a list of track path names, all of which contain
657 all of the required words (in their path name, trackname
660 self._simple("search", _quote(words))
666 The return value is a list of all tags which apply to at least one
672 """Get server statistics.
674 The return value is list of statistics.
676 self._simple("stats")
680 """Get all preferences.
682 The return value is an encoded dump of the preferences database.
687 def set_volume(self, left, right):
691 left -- volume for the left speaker.
692 right -- volume for the right speaker.
694 self._simple("volume", left, right)
696 def get_volume(self):
699 The return value a tuple consisting of the left and right volumes.
701 ret, details = self._simple("volume")
702 return map(int,string.split(details))
704 def move(self, track, delta):
705 """Move a track in the queue.
708 track -- the name or ID of the track to move
709 delta -- the number of steps towards the head of the queue to move
711 ret, details = self._simple("move", track, str(delta))
714 def log(self, callback):
715 """Read event log entries as they happen.
717 Each event log entry is handled by passing it to callback.
719 The callback takes two arguments, the first is the client and the
720 second the line from the event log.
722 The callback should return True to continue or False to stop (don't
723 forget this, or your program will mysteriously misbehave).
725 It is suggested that you use the disorder.monitor class instead of
726 calling this method directly, but this is not mandatory.
728 See disorder_protocol(5) for the event log syntax.
731 callback -- function to call with log entry
733 ret, details = self._simple("log")
736 self._debug(client.debug_body, "<<< %s" % l)
737 if l != '' and l[0] == '.':
741 if not callback(self, l):
743 # tell the server to stop sending, eat the remains of the body,
745 self._send("version")
750 """Pause the current track."""
751 self._simple("pause")
754 """Resume after a pause."""
755 self._simple("resume")
757 def part(self, track, context, part):
758 """Get a track name part
761 track -- the track to query
762 context -- the context ('sort' or 'display')
763 part -- the desired part (usually 'artist', 'album' or 'title')
765 The return value is the preference
767 ret, details = self._simple("part", track, context, part)
770 def setglobal(self, key, value):
771 """Set a global preference value.
774 key -- the preference name
775 value -- the new preference value
777 self._simple("set-global", key, value)
779 def unsetglobal(self, key):
780 """Unset a global preference value.
783 key -- the preference to remove
785 self._simple("set-global", key, value)
787 def getglobal(self, key):
788 """Get a global preference value.
791 key -- the preference to look up
793 The return value is the preference
795 ret, details = self._simple("get-global", key)
801 ########################################################################
805 # read one response line and return as some suitable string object
807 # If an I/O error occurs, disconnect from the server.
809 # XXX does readline() DTRT regarding character encodings?
811 l = self.r.readline()
812 if not re.search("\n", l):
813 raise communicationError(self.who, "peer disconnected")
818 return unicode(l, "UTF-8")
821 # read a response as a (code, details) tuple
823 self._debug(client.debug_proto, "<== %s" % l)
824 m = _response.match(l)
826 return int(m.group(1)), m.group(2)
828 raise protocolError(self.who, "invalid response %s")
830 def _send(self, *command):
831 # Quote and send a command
833 # Returns the encoded command.
834 quoted = _quote(command)
835 self._debug(client.debug_proto, "==> %s" % quoted)
836 encoded = quoted.encode("UTF-8")
838 self.w.write(encoded)
845 raise communicationError(self.who, e)
850 def _simple(self, *command):
851 # Issue a simple command, throw an exception on error
853 # If an I/O error occurs, disconnect from the server.
855 # On success or 'normal' errors returns response as a (code, details) tuple
857 # On error raise operationError
858 if self.state == 'disconnected':
861 cmd = self._send(*command)
864 res, details = self._response()
865 if res / 100 == 2 or res == 555:
867 raise operationError(res, details, cmd)
870 # Fetch a dot-stuffed body
874 self._debug(client.debug_body, "<<< %s" % l)
875 if l != '' and l[0] == '.':
881 ########################################################################
882 # Configuration file parsing
884 def _readfile(self, path):
885 # Read a configuration file
889 # path -- path of file to read
891 # handlers for various commands
892 def _collection(self, command, args):
894 return "'%s' takes three args" % command
895 self.config["collections"].append(args)
897 def _unary(self, command, args):
899 return "'%s' takes only one arg" % command
900 self.config[command] = args[0]
902 def _include(self, command, args):
904 return "'%s' takes only one arg" % command
905 self._readfile(args[0])
907 def _any(self, command, args):
908 self.config[command] = args
910 # mapping of options to handlers
911 _options = { "collection": _collection,
916 "include": _include }
919 for lno, line in enumerate(file(path, "r")):
921 fields = _split(line, 'comments')
922 except _splitError, s:
923 raise parseError(path, lno + 1, str(s))
926 # we just ignore options we don't know about, so as to cope gracefully
927 # with version skew (and nothing to do with implementor laziness)
928 if command in _options:
929 e = _options[command](self, command, fields[1:])
931 self._parseError(path, lno + 1, e)
933 def _parseError(self, path, lno, s):
934 raise parseError(path, lno, s)
936 ########################################################################
940 """DisOrder event log monitor class
942 Intended to be subclassed with methods corresponding to event log messages
943 the implementor cares about over-ridden."""
945 def __init__(self, c=None):
946 """Constructor for the monitor class
948 Can be passed a client to use. If none is specified then one
949 will be created specially for the purpose.
958 """Start monitoring logs. Continues monitoring until one of the
959 message-specific methods returns False. Can be called more than once
960 (but not recursively!)"""
961 self.c.log(self._callback)
964 """Return the timestamp of the current (or most recent) event log entry"""
965 return self.timestamp
967 def _callback(self, c, line):
971 return self.invalid(line)
973 return self.invalid(line)
974 self.timestamp = int(bits[0], 16)
977 if keyword == 'completed':
979 return self.completed(bits[0])
980 elif keyword == 'failed':
982 return self.failed(bits[0], bits[1])
983 elif keyword == 'moved':
988 return self.invalid(line)
989 return self.moved(bits[0], n, bits[2])
990 elif keyword == 'playing':
992 return self.playing(bits[0], None)
994 return self.playing(bits[0], bits[1])
995 elif keyword == 'queue' or keyword == 'recent-added':
999 return self.invalid(line)
1000 if keyword == 'queue':
1001 return self.queue(q)
1002 if keyword == 'recent-added':
1003 return self.recent_added(q)
1004 elif keyword == 'recent-removed':
1006 return self.recent_removed(bits[0])
1007 elif keyword == 'removed':
1009 return self.removed(bits[0], None)
1010 elif len(bits) == 2:
1011 return self.removed(bits[0], bits[1])
1012 elif keyword == 'scratched':
1014 return self.scratched(bits[0], bits[1])
1015 return self.invalid(line)
1017 def completed(self, track):
1018 """Called when a track completes.
1021 track -- track that completed"""
1024 def failed(self, track, error):
1025 """Called when a player suffers an error.
1028 track -- track that failed
1029 error -- error indicator"""
1032 def moved(self, id, offset, user):
1033 """Called when a track is moved in the queue.
1036 id -- queue entry ID
1037 offset -- distance moved
1038 user -- user responsible"""
1041 def playing(self, track, user):
1042 """Called when a track starts playing.
1045 track -- track that has started
1046 user -- user that submitted track, or None"""
1050 """Called when a track is added to the queue.
1053 q -- dictionary of new queue entry"""
1056 def recent_added(self, q):
1057 """Called when a track is added to the recently played list
1060 q -- dictionary of new queue entry"""
1063 def recent_removed(self, id):
1064 """Called when a track is removed from the recently played list
1067 id -- ID of removed entry (always the oldest)"""
1070 def removed(self, id, user):
1071 """Called when a track is removed from the queue, either manually
1072 or in order to play it.
1075 id -- ID of removed entry
1076 user -- user responsible (or None if we're playing this track)"""
1079 def scratched(self, track, user):
1080 """Called when a track is scratched
1083 track -- track that was scratched
1084 user -- user responsible"""
1087 def invalid(self, line):
1088 """Called when an event log line cannot be interpreted
1091 line -- line that could not be understood"""
1096 # py-indent-offset:2