]> code.delx.au - mediapc-tools/blob - mythsymlink
monitor-dir: updated usage info
[mediapc-tools] / mythsymlink
1 #!/usr/bin/python
2
3 import MySQLdb
4 import os
5 import re
6 import socket
7 import sys
8
9 from socket import gethostname
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 config_values = {}
25 for line in open(os.path.expanduser("~/.mythtv/mysql.txt")):
26 line = line.strip()
27 if line and not line.startswith("#"):
28 (key, value) = line.split("=")
29 config_values[key] = value
30
31 db_connection = MySQLdb.connect(
32 host = config_values["DBHostName"],
33 user = config_values["DBUserName"],
34 passwd = config_values["DBPassword"],
35 db = config_values["DBName"]
36 )
37 cursor = db_connection.cursor(MySQLdb.cursors.DictCursor)
38
39 # Regexp for what is allowed in the symlink name
40 unsafe = re.compile("[^a-zA-Z0-9\-_ ,\\.]+")
41
42 # Find the recordings directory
43 cursor.execute("""
44 SELECT * FROM settings
45 WHERE value='RecordFilePrefix' AND hostname='%s'
46 """ % socket.gethostname())
47 recordingsdir = cursor.fetchone()["data"]
48
49 # Now find all the recordings we have at the moment
50 cursor.execute("""
51 SELECT title, subtitle, starttime, basename, watched FROM recorded
52 """)
53 for row in cursor:
54 title = row["title"]
55 starttime = str(row["starttime"]).replace(":", "-")
56 subtitle = row["subtitle"]
57 basename = row["basename"]
58 watched = bool(row["watched"])
59
60 title = unsafe.sub("", title)
61 subtitle = unsafe.sub("", subtitle)
62 extn = os.path.splitext(basename)[1]
63
64
65 if subtitle:
66 filename = "%s - %s%s" % (starttime, subtitle, extn)
67 else:
68 filename = "%s%s" % (starttime, extn)
69 if watched:
70 filename = "watched/" + filename
71
72 source = "%s/%s" % (recordingsdir, basename)
73 dest = "%s/%s" % (title, filename)
74
75 dirnames = dest.split("/")[:-1]
76 for i in xrange(1, len(dirnames)+1):
77 dirname = "/".join(dirnames[:i])
78 if not os.path.isdir(dirname):
79 os.mkdir(dirname)
80
81 os.symlink(source, dest)
82