summaryrefslogtreecommitdiffstats
path: root/mpdspl.py
blob: b72399270f3ffc3b48d1ac01233e165e42b7e5a8 (plain)
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
#! /usr/bin/env python
#
# A script to create smart playlists, with a variety of criteria, out of an
# MPD database.
#
# Authors:
#   Sebastien Delafond <[email protected]>
#   original implementation by Michael Walker <[email protected]>
#
# This code is licensed under the GPL v3, or any later version at your choice.

import codecs, cPickle, datetime, operator, optparse
import os, os.path, sqlite3, sys, re, textwrap, time

DEFAULT_ENCODING = 'utf-8'

DEFAULT_MDP_CONFIG_FILE = "/etc/mpd.conf"

# There is an environmental variable XDG_CACHE_HOME which specifies where to
# save cache files. However, if not set, a default of ~/.cache should be used.
DEFAULT_CACHE_FILE = os.environ.get('XDG_CACHE_HOME',
                                    os.path.join(os.environ['HOME'], ".cache"))
DEFAULT_CACHE_FILE = os.path.expanduser(os.path.join(DEFAULT_CACHE_FILE,
                                                     "mpdspl/mpddb.cache"))

# $XDG_DATA_HOME specifies where to save data files, in our case a record of
# playlists which have been created. If unset a default of ~/.local/share
# should be used.
DEFAULT_DATA_DIR = os.environ.get('XDG_DATA_HOME',
                                  os.path.join(os.environ['HOME'], ".local/share/"))
DEFAULT_DATA_DIR = os.path.expanduser(os.path.join(DEFAULT_DATA_DIR,
                                                   "mpdspl"))

KEYWORDS = {"ar"   : ("Artist", "Artist"),
            "al"   : ("Album", "Album"),
            "ti"   : ("Title", "Title"),
            "tn"   : ("Track", "Track number"),
            "ge"   : ("Genre", "Genre"),
            "ye"   : ("Date", "Track year"),
            "le"   : ("Time", "Track duration (in seconds)"),
            "fp"   : ("file", "File full path"),
            "fn"   : ("key", "File name"),
            "mt"   : ("mtime", "File modification time"),
            "ra"   : ("Rating", "Track rating"),
            "raar" : ("RatingAr", "Artist rating"),
            "raal" : ("RatingAl", "Album rating"),
            "rag"  : ("RatingGe", "Genre rating"),
            "pc"   : ("PlayCount", "Play Count") }

class CustomException(Exception):
    pass

class AbstractRule:
    def __init__(self, key, operator, delimiter, value, flags):
        if key.lower() in KEYWORDS:
            self.key = KEYWORDS[key.lower()][0]
        elif key.lower() in [ v[0].lower() for v in KEYWORDS.values() ]:
            self.key = key.lower()
        else:
            raise CustomException("A track has no attribute '%s'" % (key,))
        
        self.operator = operator
        self.delimiter = delimiter
        self.value = value
        if flags:
            self.flags = tuple(flags)
        else:
            self.flags = ()
        self.negate = 'n' in self.flags

    def __repr__(self):
        return "%(key)s%(operator)s%(delimiter)s%(value)s%(delimiter)s flags=%(flags)s" % self.__dict__

    def getOperator(self):
        return self.OPERATORS[self.operator]
    
    def match(self, track):
        attr = getattr(track, self.key.lower())
        matched = self.__match__(attr)

        if self.negate:
            matched = not matched
        return matched
    
class RegexRule(AbstractRule):
    """ Search according to a regex, for instance:
               contains foo                     -->   =/foo/
               contains bar, case-insensitive   -->   =/bar/i
               does not contain baz             -->   !/foo/ """
    
    OPERATORS = { '=' : re.search,
                  '!' : lambda *v: not re.search(*v) }
    FLAGS = { 'i' : re.IGNORECASE,
              'l' : re.LOCALE }
    
    def __init__(self, key, operator, delimiter, value, flags):
        AbstractRule.__init__(self, key, operator,
                              delimiter, value, flags)
        self.reFlags = 0
        for reFlag in self.flags:
            self.reFlags |= self.FLAGS[reFlag]

    def __match__(self, value):
        try:
            value = str(value)
        except:
            value = value.encode(DEFAULT_ENCODING)
        return self.getOperator()(self.value, value, self.reFlags)
        
class NumberRule(AbstractRule):
    """ Match according to a number comparison, for instance:
               greater or equal than 30         -->   >=#30#
               lesser than 80                   -->   <#80# """
    
    OPERATORS = { '=' : operator.eq,
                  '<' : operator.lt,
                  '>' : operator.gt,
                  '>=' : operator.ge,
                  '<=' : operator.ge }
    
    def __init__(self, key, operator, delimiter, value, flags):
        AbstractRule.__init__(self, key, operator,
                              delimiter, value, flags)
        self.number = float(value)
        
    def __match__(self, value):
        if not value:
            value = 0
        return self.getOperator()(float(value), self.number)
        
class TimeDeltaRule(AbstractRule):
    """ Match according to a timedelta, for instance:
               in the last 3 days   -->   <=%3days%
               before last month    -->   >%1month%
               3 years ago          -->   =%3years% """
    
    OPERATORS = { '=' : operator.eq,
                  '<' : operator.lt,
                  '>' : operator.gt,
                  '>=' : operator.ge,
                  '<=' : operator.le }
    
    TIME_DELTA_REGEX = r'(?P<number>\d+)\s*(?P<unit>[a-zA-Z]+)'

    def __init__(self, key, operator, delimiter, value, flags):
        AbstractRule.__init__(self, key, operator,
                              delimiter, value, flags)
        
        m = re.match(self.TIME_DELTA_REGEX, self.value)
        if not m:
            raise CustomException("Could not parse duration")
        d = m.groupdict()
        self.number = int(d['number'])
        self.unit = d['unit'].lower()
        if not self.unit.endswith('s'):
            self.unit += 's'

        self.value = datetime.timedelta(**{self.unit : self.number})
        self.now = datetime.datetime.now()

    def __match__(self, value):
        delta = self.now - datetime.datetime.fromtimestamp(int(value))
        return self.getOperator()(delta, self.value)

class TimeStampRule(AbstractRule):
    """ Match according to a timestamp, for instance:
               before 2010-01-02            -->   <@[email protected]
               after  2009-12-20 (included) -->   >[email protected]@
               on     2009-11-18            -->   [email protected]@ """
    
    OPERATORS = { '=' : operator.eq,
                  '<' : operator.lt,
                  '>' : operator.gt,
                  '>=' : operator.ge,
                  '<=' : operator.le }
    
    TIME_STAMP_FORMAT = '%Y-%m-%d'

    def __init__(self, key, operator, delimiter, value, flags):
        AbstractRule.__init__(self, key, operator,
                              delimiter, value, flags)
        
        ts = time.strptime(self.value, self.TIME_STAMP_FORMAT)
        self.value = time.mktime(ts)

    def __match__(self, value):
        # round down to the precision of TIME_STAMP_FORMAT before comparing
        value = time.gmtime(float(value)) # in seconds since epoch
        value = time.strftime(self.TIME_STAMP_FORMAT, value)        
        value = time.mktime(time.strptime(value, self.TIME_STAMP_FORMAT))
        return self.getOperator()(value, self.value)

class RuleFactory:
    DELIMITER_TO_RULE = { '/' : RegexRule,
                          '%' : TimeDeltaRule,
                          '@' : TimeStampRule,
                          '#' : NumberRule }

    @staticmethod
    def getRule(ruleString):
        m = re.match(r'(?P<key>\w+)(?P<operator>.+?)(?P<delimiter>[' +
                     ''.join(RuleFactory.DELIMITER_TO_RULE.keys()) +
                     r'])(?P<value>.+)(?P=delimiter)(?P<flags>\w+)?',
                     ruleString)
        if not m:
            raise CustomException("Could not parse rule '%s'" % (ruleString,))

        d = m .groupdict()
        ruleClass = RuleFactory.DELIMITER_TO_RULE[d['delimiter']]
        return ruleClass(**d)

    @staticmethod
    def help():
        s = ""
        for d, r in RuleFactory.DELIMITER_TO_RULE.iteritems():
            s += "          '%s' -> %s\n" % (d, r.__doc__)
        return s

class Playlist:
    REGEX = re.compile(r'\s*,\s*') # how we split rules in a ruleset
    PLAYLIST_DIR = None # where to save m3u files
    CACHE_DIR = None # where to save marshalled playlists
    
    def __init__(self, name, ruleString):
        self.name = name
        self.rules = [ RuleFactory.getRule(r)
                       for r in self.REGEX.split(ruleString) ]
        self.tracks = [] # tracks matching the rules; empty for now

    @staticmethod
    def initStaticAttributes(playlistDir, cacheDir):
        Playlist.PLAYLIST_DIR = playlistDir
        Playlist.CACHE_DIR = cacheDir

    @staticmethod
    def load(name):
        obj = loadgubbage(Playlist.getSaveFile(name))
        try:
            assert isinstance(obj, Playlist)
        except:
            raise CustomException("Restoring old playlists won't work, please rm '%s'." % (playlistfile,))

        return obj

    def save(self):
        savegubbage(self, Playlist.getSaveFile(self.name))

    @staticmethod
    def getSaveFile(name):
        return os.path.join(Playlist.CACHE_DIR, name)

    def findMatchingTracks(self, mpdDB):
        self.tracks = []
    
        for track in mpdDB.getTracks():
            toAdd = True
            for rule in self.rules:
                if not rule.match(track): # Add the track if appropriate
                    toAdd = False
                    break

            if toAdd:
                self.tracks.append(track)

        self.tracks.sort()
        self.setM3u()

    def setM3u(self):
        l = [ track.file for track in self.tracks ]
        self.m3u = '\n'.join(l)

    def getM3uPath(self):
        return os.path.join(self.PLAYLIST_DIR, self.name + ".m3u")

    def writeM3u(self):
        filePath = self.getM3uPath()
        print "Saving playlist '%s' to '%s'" % (playlist.name, filePath)
        codecs.open(filePath, 'w', DEFAULT_ENCODING).write(self.m3u + '\n')

class PlaylistSet:
    def __init__(self, playlists):
        self.playlists = playlists

    def addMarshalled(self, name):
        if name in playlists.keys():
            raise CustomException("Cowardly refusing to create a new '%s' playlist since '%s' already exists." % (name, Playlist.getSaveFile(name)))
        playlists[name] = Playlist.load(name)

    def getPlaylists(self):
        return self.playlists.values()

class Track:
    def __init__(self):
        # create a track object with only empty attributes
        for key in KEYWORDS.values():
            setattr(self, key[0].lower(), "")

    def __cmp__(self, t2):
        return cmp(self.artist +self.album + self.title,
                   t2.artist + t2.album + t2.title)

    def __repr__(self):
        return ("%(artist)s - %(album)s - %(track)s - %(title)s" % self.__dict__).encode(DEFAULT_ENCODING)

class MpdDB:
    CACHE_FILE = None # where to save marshalled DB
    
    def __init__(self, dbFile,
                 stickerFile = None, mpdcronStatsFile = None):
        self.dbFile = dbFile
        self.stickerFile = stickerFile
        self.mpdcronStatsFile = mpdcronStatsFile
        self.tracks = {}
        self.__parseDB()
        if mpdcronStatsFile:
            self.__parseMpdcronDB()            
        elif self.stickerFile:
            self.__parseStickerDB()

    @staticmethod
    def initStaticAttributes(cacheFile):
        MpdDB.CACHE_FILE = cacheFile

    @staticmethod
    def load():
        obj = loadgubbage(MpdDB.CACHE_FILE)
        try:
            assert isinstance(obj, MpdDB)
            tracks = obj.getTracks()
            if len(tracks) > 1:
                assert isinstance(tracks[-1], Track)
        except:
            raise CustomException("Restoring from old cache won't work, please use -f.")

        return obj

    def save(self):
        savegubbage(self, MpdDB.CACHE_FILE)

    @staticmethod
    def needUpdate(dbFile, extraFile):
        return (not os.path.isfile(MpdDB.CACHE_FILE) \
                or os.path.getmtime(dbFile) > os.path.getmtime(MpdDB.CACHE_FILE) \
                or (extraFile \
                    and os.path.isfile(extraFile) \
                    and os.path.getmtime(extraFile) > os.path.getmtime(MpdDB.CACHE_FILE)))
        
    def __parseDB(self):
        parsing = False

        track = None
        for line in codecs.open(self.dbFile, 'r', DEFAULT_ENCODING):
            line = line.strip()

            if line == "songList begin": # enter parsing mode
                parsing = True
                continue
            if line == "songList end": # exit parsing mode
                parsing = False
                continue

            if parsing:
                if line.startswith("key: "):
                    if track is not None: # save the previous one
                        self.tracks[track.file] = track
                    track = Track() # create a new one

                key, value = line.split(": ", 1)
                setattr(track, key.lower(), value)

    def __parseStickerDB(self):
        conn = sqlite3.connect(self.stickerFile)

        curs = conn.cursor()

        curs.execute('SELECT * FROM sticker WHERE type=? and name=?',
                     ("song", "rating"))

        for row in curs:
            filePath = row[1]
            if filePath in self.tracks:
                self.tracks[filePath].rating = row[3]

    def __parseMpdcronDB(self):
        conn = sqlite3.connect(self.mpdcronStatsFile)

        curs = conn.cursor()

        curs.execute('''
SELECT song.uri, song.rating, artist.rating, album.rating, genre.rating, song.play_count
FROM song, artist, album, genre
WHERE song.artist = artist.name
AND song.album = album.name
AND song.genre = genre.name
AND song.rating + artist.rating + album.rating + genre.rating > 0''', ())

        for row in curs:
            filePath = row[0]
            if filePath in self.tracks:
                self.tracks[filePath].rating = row[1]
                self.tracks[filePath].ratingar = row[2]
                self.tracks[filePath].ratingal = row[3]
                self.tracks[filePath].ratingge = row[4]
                self.tracks[filePath].playcount = row[5]

    def getTracks(self):
        return self.tracks.values()

class IndentedHelpFormatterWithNL(optparse.IndentedHelpFormatter):
    """ So optparse doesn't mangle our help description. """
    def format_description(self, description):
        if not description: return ""
        desc_width = self.width - self.current_indent
        indent = " "*self.current_indent
        bits = description.split('\n')
        formatted_bits = [ textwrap.fill(bit,
                                         desc_width,
                                         initial_indent=indent,
                                         subsequent_indent=indent)
                           for bit in bits]
        result = "\n".join(formatted_bits) + "\n"
        return result 

def parseargs(args):
    parser = optparse.OptionParser(formatter=IndentedHelpFormatterWithNL(),
                                   description="""Playlist ruleset:
        Each ruleset is made of several rules, separated by commas.
        Each rule is made of a keyword, an operator, a value to match
        surrounded by delimiters, and several optional flags influencing the
        match.
        There are """ + str(len(RuleFactory.DELIMITER_TO_RULE.keys())) + \
        """ types of rules, each defined by a specific delimiter:\n\n""" + \

        RuleFactory.help() + \

        """\n        These available keywords are:
""" + \

        '\n'.join([ "            " + k + "/" + v[0] + " : " + v[1].lower() for k, v in KEYWORDS.iteritems() ]) + \

        """

        For example, a rule for all tracks by 'Fred' or 'George', which have a
        title containing (case-insensitive) 'the' and 'and', which don't
        include the word 'when' (case-insensitive), and whose modification
        time was in the last 3 days would be written:

          ar=/(Fred|George)/ , ti=/(the.*and|and.*the)/i , ti!/when/i , mt<%3days%
          
    Notes:
        Paths specified in the MPD config file containing a '~' will have the
        '~'s replaced by the user MPD runs as..""")

    parser.add_option("-f", "--force-update", dest="forceUpdate",
                      action="store_true", default=False,
                      help="Force an update of the cache file and any playlists")

    parser.add_option("-C", "--cache-file", dest="cacheFile",
                      default=DEFAULT_CACHE_FILE,
                      help="Location of the cache file", metavar="FILE")

    parser.add_option("-D", "--data-dir", dest="dataDir",
                      default=DEFAULT_DATA_DIR,
                      help="Location of the data directory (where we save playlist info)",
                      metavar="DIR")

    parser.add_option("-d", "--database-file", dest="dbFile", 
                      help="Location of the MPD database file",
                      metavar="FILE")

    parser.add_option("-s", "--sticker-file", dest="stickerFile",
                      help="Location of the MPD sticker file (holding ratings)",
                      metavar="FILE")

    parser.add_option("-m", "--mpdcron-stats-file", dest="mpdcronStatsFile",
                      help="Location of the mpdcron stats file (holding ratings and other info)",
                      default=None,
                      metavar="FILE")

    parser.add_option("-c", "--config-file", dest="configFile",
                      default=DEFAULT_MDP_CONFIG_FILE,
                      help="Location of the MPD config file",
                      metavar="FILE")

    parser.add_option("-p", "--playlist-dir", dest="playlistDirectory",
                      help="Location of the MPD playlist directory",
                      metavar="DIR")

    parser.add_option("-u", "--user", dest="mpdUser",
                      help="User MPD runs as", metavar="USER")

    parser.add_option("-n", "--new-playlist", dest="playlists",
                      action="append", default=[], nargs=2,
                      help="Create a new playlist",
                      metavar="NAME 'RULESET'")

    parser.add_option("-o", "--output-only", dest="simpleOutput",
                      action="store_true", default=False,
                      help="Only print the final track list to STDOUT")

    options, args = parser.parse_args(args)

    if getattr(options, "mpdcronStatsFile") and getattr(options, "stickerFile"):
        print "Can't use -s and -m at the same time, as they both provide ratings."
        sys.exit(2)

    # we'll use dataDir=None to indicate we want simpleOutput
    if options.simpleOutput:
        options.dataDir = None

    # go from ((name,rule),(name1,rule1),...) to {name:rule,name1:rule1,...}
    playlists = {}
    for name, ruleSet in options.playlists:
        playlists[name] = Playlist(name, ruleSet)
    options.playlists = playlists

    configDict = parsempdconf(os.path.expanduser(options.configFile),
                              options.mpdUser)

    # CL arguments take precedence over config file settings
    for key in configDict:
        if key in dir(options) and getattr(options, key):
            configDict[key] = getattr(options, key)

    if not 'stickerFile' in configDict: # need to have this one defined
        configDict['stickerFile'] = None

    return options.forceUpdate, options.cacheFile, options.dataDir, \
           configDict['dbFile'], configDict['stickerFile'], \
           options.mpdcronStatsFile, \
           configDict['playlistDirectory'], options.playlists

def _underscoreToCamelCase(s):
    tokens = s.split('_')
    s = tokens[0]
    for token in tokens[1:]:
        s += token.capitalize()
    return s
    
# Grabbing stuff from the MPD config, a very important step
def parsempdconf(configFile, user = None):
    configDict = {}
    for line in open(configFile, "r"):
        line = line.strip()
        if line and not re.search(r'[#{}]', line):
            key, value = re.split(r'\s+', line, 1)

            key = _underscoreToCamelCase(key)

            value = re.sub(r'(^"|"$)', '', value)

            # account for ~/ in mpd.conf
            if value == '~' or value.count('~/') > 0: # FIXME: others ?
                if user:
                    value = value.replace('~', user)
                else:
                    value = os.path.expanduser(value)
                    
            configDict[key] = value

    return configDict

def savegubbage(data, path):
    if not os.path.isdir(os.path.dirname(path)):
        os.mkdir(os.path.dirname(path))
    cPickle.dump(data, open(path, "wb"))

def loadgubbage(path):
    return cPickle.load(open(path, "rb"))

if __name__ == '__main__':
   try:
      forceUpdate, cacheFile, dataDir, \
                   dbFile, stickerFile, \
                   mpdcronStatsFile, \
                   playlistDir, playlists = parseargs(sys.argv[1:])

      MpdDB.initStaticAttributes(cacheFile)
      Playlist.initStaticAttributes(playlistDir, dataDir)

      playlistSet = PlaylistSet(playlists)

      if not os.path.isfile(dbFile): # no dbFile -> abort
          raise CustomException("The database file '%s' could not be found" %
                                (dbFile,))

      if forceUpdate or MpdDB.needUpdate(dbFile,
                                         mpdcronStatsFile or stickerFile): # update cache
          if dataDir:
              print "Updating database cache..."

          if not os.path.isdir(os.path.dirname(cacheFile)):
              os.mkdir(os.path.dirname(cacheFile))

          # create the MPD DB object
          if mpdcronStatsFile:
              mpdDB = MpdDB(dbFile, mpdcronStatsFile=mpdcronStatsFile)
          else:
              mpdDB = MpdDB(dbFile, stickerFile=stickerFile)
              
          mpdDB.save() # save to file
      else: # we have a valid cache file, use it
          if dataDir:
              print "Loading database cache..."
          mpdDB = MpdDB.load()

      if dataDir: # add pre-existing playlists to our list
          for name in os.listdir(Playlist.CACHE_DIR):
              playlistSet.addMarshalled(name)

      for playlist in playlistSet.getPlaylists():
          playlist.findMatchingTracks(mpdDB)

          if not dataDir: # stdout
              if playlist.m3u:
                  print playlist.m3u.encode(DEFAULT_ENCODING)
          else: # write to .m3u & save
              playlist.writeM3u()
              playlist.save()
   except CustomException, e:
       print e.message
       sys.exit(2)