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