PageRenderTime 98ms CodeModel.GetById 41ms app.highlight 18ms RepoModel.GetById 22ms app.codeStats 0ms

/createnfos.py

http://fill-mythvideo-metadata.googlecode.com/
Python | 212 lines | 186 code | 18 blank | 8 comment | 7 complexity | 6016128c62239c29d8240f94a7a1c266 MD5 | raw file
  1#!/usr/bin/env python2.5
  2
  3
  4__author__ = "Fabian Rothfuchs"
  5__license__ = "GNU General Public License v2"
  6__version__ = "$Revision: 1.03 $"
  7
  8import MySQLdb
  9import os.path
 10from optparse import OptionParser
 11from shutil import copyfile
 12
 13
 14class NFOgen:
 15
 16    def __init__(self):
 17        """constructor"""
 18
 19        self.writeCount = 0 #counts written files
 20        self.skipCount = 0 #counts skipped files (always existing)
 21        self.fileCount = 0 #number of files in the database
 22        self.backupCount = 0 #number of backupped files
 23        self.dummyCount = 0 #number pseudo-written of dummy files
 24
 25        self.readOpts()
 26        self.getMySQLConfig()
 27        self.initSQL()
 28
 29    def __del__(self):
 30        """destructor"""
 31
 32        try:
 33            self.options
 34        except AttributeError: #-h option diesnt set self.options and exits immediately
 35            return
 36
 37        print "Found %s files in database" %(self.fileCount)
 38        print "Wrote %s files" %(self.writeCount)
 39        print "Wrote %s dummy files" %(self.dummyCount)
 40        print "Skipped %s files" %(self.skipCount)
 41
 42        self.closeSQL()
 43
 44    def getMySQLConfig(self):
 45        """gather mysql config by using mythtv config file
 46        called by: __init__()
 47        return: None
 48
 49        """
 50
 51        mysql_file = '/etc/mythtv/mysql.txt'
 52        config = {}
 53
 54        try:
 55            f = open(mysql_file,'r')
 56            file = f.read()
 57            f.close()
 58        except IOError, e:
 59            print "Could not open %s ." %(mysql_file,)
 60
 61        for line in file.split("\n"):
 62            if line.startswith("#") or len(line) < 1 or not "=" in line:
 63                continue
 64
 65            key,val = line.split("=")
 66            config[key] = val
 67
 68        self.sql_hostname = config.get('DBHostName','')
 69        self.sql_username = config.get('DBUserName','')
 70        self.sql_password = config.get('DBPassword','')
 71        self.sql_database = config.get('DBName','')
 72
 73    def readOpts(self):
 74        """read options given and store them
 75        called by: __init__()
 76        return: None
 77        
 78        """
 79
 80        parser = OptionParser()
 81        parser.add_option("-d", "--dummy", dest="dummy", default=False, action="store_true",
 82                      help="do not create, just print files and content")
 83        parser.add_option("-f", "--force", dest="force", default=False, action="store_true",
 84                      help="force overwriting of existing files")
 85        parser.add_option("-n", "--no-backup", dest="no_backup", default=False, action="store_true",
 86                      help="do NOT create .backup files")
 87        parser.add_option("-q", "--quiet", dest="quiet", default=False, action="store_true",
 88                      help="don't print status messages")
 89        parser.add_option("-v", "--verbose", dest="verbose", default=False, action="store_true",
 90                      help="print verbose messages")
 91        parser.add_option("-p", "--path", dest="path", default=False, metavar="PATH",
 92                      help="specify path where to recover NFO files")
 93
 94        self.options, self.args = parser.parse_args()
 95
 96    def initSQL(self):
 97        """initialize MySQL connection
 98        called by: __init__()
 99
100        """
101
102        self.my_conn = MySQLdb.connect(self.sql_hostname, self.sql_username, self.sql_password, self.sql_database)
103        self.my_curs = self.my_conn.cursor()
104
105        query = "SELECT title, inetref, filename FROM videometadata"
106
107        self.my_curs.execute(query)
108        self.files = self.my_curs.fetchall()
109
110    def closeSQL(self):
111        """close MySQL connection
112        called by: __del__()
113        return: None
114        
115        """
116
117        self.my_curs.close()
118        self.my_conn.close()
119
120    def notify(self, content):
121        """print `content` if not quiet mode
122        return: None
123
124        content: <str>
125
126        """
127
128        if self.options.quiet:
129            return
130
131        print content
132
133    def writeNFO(self, filepath, content):
134        """write NFO file to path given in `filepath`
135        called by: self.parseDbEntries()
136        return: None
137
138        filepath: <str>, i.e. /home/me/a.nfo
139        content:  <str>, i.e. blah
140
141        """
142
143        msg = filepath
144        if self.options.verbose:
145            msg = "%s: \n%s" %(filepath, content)
146
147        if self.options.dummy:
148            self.dummyCount += 1
149            self.notify("Dummy mode: Would write %s" %(msg,))
150            return
151
152        if self.options.path:
153            index = filepath.rfind("/")
154            folder = filepath[:index]
155            filename = filepath[index:]
156
157            if not self.options.path.startswith("/"): #relative paths require `pwd`
158                self.options.path = "%s/%s" %(os.getcwd(), self.options.path)
159            folder = self.options.path + folder
160
161            if not os.path.exists(folder):
162                os.makedirs(folder)
163
164            filepath = folder + filename
165
166        if os.path.exists(filepath): #backup procedure
167            if not self.options.force:
168                self.writeCount -= 1
169                print "File exists: %s - please give -f option to overwrite" %filepath
170                return
171            else:
172                if not self.options.no_backup:
173                    self.notify("Backupping file: %s" %filepath)
174                    copyfile(filepath, folder + filename + ".backup")
175
176        self.writeCount += 1
177        self.notify("Writing NFO file: %s" %filepath)
178
179        f = open(filepath, 'w')
180        f.write(content+"\n")
181        f.close()
182
183        self.notify("Wrote %s" %(msg,))
184
185    def parseDbEntries(self):
186        """parse DB entries received in self.initSQL().
187        called by: main method
188        return: None
189
190        """
191
192        c = 0
193        for entry in self.files:
194            title, inetref, filepath = entry
195            filepath = "%s.nfo" %filepath[:filepath.rfind(".")]
196
197            if inetref == "00000000" or inetref == "":
198                continue
199
200            c+=1
201            if inetref.startswith("http://www.thetvdb.com"):
202                content = "<thetvdb episodeid='%s'/>" %inetref.split("/")[-2] 
203            else:
204                content = "<imdb id='tt%s'/>" %inetref
205                
206            self.writeNFO(filepath, content) 
207
208
209if __name__ == "__main__":
210
211    n = NFOgen()
212    n.parseDbEntries()