]> code.delx.au - mediapc-tools/blob - mythsymlink
mythsymlink: generate a random filename if there is a conflict
[mediapc-tools] / mythsymlink
1 #!/usr/bin/env python2
2
3 import os
4 import random
5 import re
6 import socket
7 import sys
8
9 import lxml.etree
10 import MySQLdb
11
12 os.chdir(sys.argv[1])
13
14 # Remove any symlinks and empty dirs in the tree
15 for dirpath, dirnames, filenames in os.walk(".", topdown=False):
16 for filename in filenames:
17 filename = os.path.join(dirpath, filename)
18 if os.path.islink(filename):
19 os.unlink(filename)
20 for dirname in dirnames:
21 dirname = os.path.join(dirpath, dirname)
22 os.rmdir(dirname)
23
24 # Connect to the MythTV database based on the MythTV config
25 with open(os.path.expanduser("~/.mythtv/config.xml")) as f:
26 config_xml = lxml.etree.parse(f, lxml.etree.XMLParser(encoding="utf-8"))
27
28 db_connection = MySQLdb.connect(
29 host = config_xml.xpath("/Configuration/Database/Host/text()")[0],
30 port = int(config_xml.xpath("/Configuration/Database/Port/text()")[0]),
31 user = config_xml.xpath("/Configuration/Database/UserName/text()")[0],
32 passwd = config_xml.xpath("/Configuration/Database/Password/text()")[0],
33 db = config_xml.xpath("/Configuration/Database/DatabaseName/text()")[0],
34 )
35 cursor = db_connection.cursor(MySQLdb.cursors.DictCursor)
36
37 # Regexp for what is allowed in the symlink name
38 unsafe = re.compile("[^a-zA-Z0-9\-_ ,\\.]+")
39
40 try:
41 localhostname = config_xml.xpath("/Configuration/LocalHostName/text()")[0]
42 except IndexError:
43 localhostname = socket.gethostname()
44
45 # Find the recordings directory
46 cursor.execute("""
47 SELECT * FROM settings
48 WHERE value='RecordFilePrefix' AND hostname='%s'
49 """ % localhostname)
50 recordingsdir = cursor.fetchone()["data"]
51
52 # Now find all the recordings we have at the moment
53 cursor.execute("""
54 SELECT title, subtitle, starttime, basename, watched FROM recorded
55 """)
56 for row in cursor:
57 title = row["title"]
58 starttime = str(row["starttime"]).replace(":", "-")
59 subtitle = row["subtitle"]
60 basename = row["basename"]
61 watched = bool(row["watched"])
62
63 title = unsafe.sub("", title)
64 subtitle = unsafe.sub("", subtitle)
65 extn = os.path.splitext(basename)[1]
66
67
68 if subtitle:
69 filename = "%s - %s%s" % (starttime, subtitle, extn)
70 else:
71 filename = "%s%s" % (starttime, extn)
72 if watched:
73 filename = "watched/" + filename
74
75 source = "%s/%s" % (recordingsdir, basename)
76 dest = "%s/%s" % (title, filename)
77
78 if not os.path.isfile(source):
79 continue
80
81 if os.path.isfile(dest):
82 dest = os.path.splitext(dest)[0] + ' - unique' + str(random.randint(1000, 9999)) + extn
83
84 dirnames = dest.split("/")[:-1]
85 for i in xrange(1, len(dirnames)+1):
86 dirname = "/".join(dirnames[:i])
87 if not os.path.isdir(dirname):
88 os.mkdir(dirname)
89
90 try:
91 os.symlink(source, dest)
92 except Exception, e:
93 print e, "--", source, "->", dest
94 sys.exit(1)