#!/usr/bin/env python3 import MySQLdb import os import random import re import sys import mythlib def main(): config_xml = mythlib.get_config() db_connection = mythlib.get_db_connection(config_xml) recordings_dir = mythlib.get_recordings_dir(config_xml, db_connection) symlinks_dir = recordings_dir + "-symlinks" os.chdir(symlinks_dir) os.umask(0o22) clean_dir() for_each_recording(db_connection, handle_recording, recordings_dir) def clean_dir(): for dirpath, dirnames, filenames in os.walk(".", topdown=False): for filename in filenames: filename = os.path.join(dirpath, filename) if os.path.islink(filename): os.unlink(filename) for dirname in dirnames: dirname = os.path.join(dirpath, dirname) os.rmdir(dirname) def for_each_recording(db_connection, fn, *args): with db_connection.cursor(MySQLdb.cursors.DictCursor) as cursor: cursor.execute(""" SELECT title, subtitle, CONVERT_TZ(starttime, 'UTC', '%s') as starttime, basename, watched FROM recorded """ % "Australia/Sydney") for row in cursor: fn(row, *args) def handle_recording(row, recordings_dir): title = row["title"] starttime = str(row["starttime"]).replace(":", "-") subtitle = row["subtitle"] basename = row["basename"] watched = bool(row["watched"]) title = sanitize_filename(title) subtitle = sanitize_filename(subtitle) extn = os.path.splitext(basename)[1] if subtitle: filename = "%s - %s%s" % (starttime, subtitle, extn) else: filename = "%s%s" % (starttime, extn) if watched: filename = "watched/" + filename source = "%s/%s" % (recordings_dir, basename) dest = "%s/%s" % (title, filename) if not os.path.isfile(source): return if os.path.isfile(dest): dest = os.path.splitext(dest)[0] + " - unique" + str(random.randint(1000, 9999)) + extn dirnames = dest.split("/")[:-1] for i in range(1, len(dirnames)+1): dirname = "/".join(dirnames[:i]) if not os.path.isdir(dirname): os.mkdir(dirname) try: os.symlink(source, dest) except Exception as e: print(e, "--", source, "->", dest) sys.exit(1) def sanitize_filename(filename): unsafe = re.compile("[^a-zA-Z0-9\-_ ,\\.]+") return unsafe.sub("", filename) if __name__ == "__main__": main()