Ticket #3313: mythvideo_mythtv.diff

File mythvideo_mythtv.diff, 10.9 KB (added by hads, 17 years ago)
  • mythvideo/mythvideo/scripts/imdbpy.py

     
    99
    1010This wrapper script is written by
    1111Pekka JÀÀskelÀinen (gmail: pekka.jaaskelainen).
    12 """ 
     12"""
    1313
    1414import sys
    1515import optparse
    1616import re
     17import socket
    1718
    1819try:
    1920        import imdb
     
    2223                "from (http://imdbpy.sourceforge.net/?page=download)"
    2324        sys.exit(1)
    2425
     26try:
     27        from mythtv import MythTV
     28        mythtv = MythTV()
     29except:
     30        mythtv = None
    2531
    26 
    2732def detect_series_title(search_string):
    2833        """
    2934        Detects a series episode title.
     
    5055                        continue
    5156               
    5257                # Found a regexp that matches the title string.
    53                 return (m.group('title'), m.group('season'), m.group('episode'))               
     58                return (m.group('title'), m.group('season'), m.group('episode'))
    5459               
    5560        return (None, None, None)
    5661
     
    9095                                        meta.toMetadataString(), year])
    9196                                return matches
    9297                        else:
    93                                 matches.append([imdb_access.get_imdbID(serie), 
     98                                matches.append([imdb_access.get_imdbID(serie),
    9499                                        serie['title'], int(serie['year'])])
    95100        return matches
    96101
     
    109114
    110115        imdb_access = imdb.IMDb()
    111116        #print "Search:",search_string
    112         movies = imdb_access.search_movie(search_string.encode("ascii", 'ignore'))     
     117        movies = imdb_access.search_movie(search_string.encode("ascii", 'ignore'))
    113118
    114119        if movies is None or len(movies) == 0:
    115120                return None
     
    192197        countries = None
    193198        akas = None
    194199       
    195         episode_title_format = '%(series_title)s S%(season)02d E%(episode)02d %(episode_title)s'
    196        
    197200        def __init__(self):
    198                 pass
     201                self.episode_title_format = mythtv.getSetting('VideoEpisodeTitleFormat', socket.gethostname())
     202                if self.episode_title_format = None:
     203                        self.episode_title_format = '%(series_title)s S%(season)02d E%(episode)02d %(episode_title)s'
    199204       
    200205        def toMetadataString(self):
    201206               
     
    243248        def metadataFromField(key, default=None, m=movie):
    244249               
    245250                searchKey = key.lower()
    246                 if searchKey not in m.keys(): 
     251                if searchKey not in m.keys():
    247252                        return default
    248253                value = unicode(m[searchKey])
    249254                try:
     
    258263        def metadataFromFirst(key, default=None, m=movie):
    259264               
    260265                searchKey = key.lower()
    261                 if searchKey not in m.keys(): 
     266                if searchKey not in m.keys():
    262267                        return default
    263268               
    264269                value = m[searchKey]
     
    271276                        return default
    272277
    273278        if movie['kind'] == 'episode':
    274                 # print "TV Series episode detected"           
     279                # print "TV Series episode detected"
    275280                metadata.series_episode = True
    276281                if 'series title' in movie.keys():
    277282                        metadata.series_title = movie['series title']
     
    294299        if 'director' in movie.keys():
    295300                directors = movie['director']
    296301                if directors is not None:
    297                         metadata.directors = directors                 
     302                        metadata.directors = directors
    298303
    299304        plots = []
    300305        if 'plot' in movie.keys():
     
    313318                metadata.plot = shortest_found
    314319
    315320        metadata.rating = metadataFromField('rating', metadata.rating)
    316         metadata.mpaa_rating = metadataFromField('mpaa', metadata.mpaa_rating) 
     321        metadata.mpaa_rating = metadataFromField('mpaa', metadata.mpaa_rating)
    317322        metadata.runtime = metadataFromFirst('runtimes', metadata.runtime)
    318323        metadata.genres = metadataFromFirst('genres', metadata.genres)
    319324        metadata.countries = metadataFromFirst('countries', metadata.countries)
     
    359364
    360365        if options.info:
    361366                print """
    362 Uses the IMDbPy package to fetch the data, thus externalizes the actual 
    363 parsing of IMDb data to another project, hopefully reducing the maintenance 
    364 burden in the future, in addition supports fetching data for TV-series 
     367Uses the IMDbPy package to fetch the data, thus externalizes the actual
     368parsing of IMDb data to another project, hopefully reducing the maintenance
     369burden in the future, in addition supports fetching data for TV-series
    365370episodes."""
    366371                sys.exit(0)
    367372
  • mythvideo/mythvideo/scripts/find_meta.py

     
    35350 * * * * find_meta.py -r /videos
    3636
    3737In which /videos is the root of your MythVideo files.
    38 """ 
     38"""
    3939
    4040import sys
    4141import optparse
     
    5252
    5353try:
    5454        # If found, we can insert data directly to MythDB
    55         import MySQLdb 
    56         db_support = True
     55        from mythtv import MythTV, MythVideo
     56        import mythtv
     57        mythtv = MythTV()
     58        mythvideo = MythVideo()
    5759except:
    58         print "MySQLdb (python-mysqldb) not installed, MythDB importing disabled."
    59         db_support = False
     60        print "MythTV module not found, MythDB importing disabled."
     61        mythtv = None
     62        mythvideo = None
    6063
    6164from stat import *
    6265
     
    180183        title = title[0:lowest_cutpoint]
    181184        return title.strip()
    182185
    183 def get_genre_id(genre_name):
    184         """
    185         Find the id of the given genre from MythDB.
    186        
    187         If the genre does not exist, insert it and return its id.
    188         """
    189         global db
    190         c = db.cursor()
    191         c.execute("SELECT intid FROM videocategory WHERE lower(category) = %s", (genre_name,))
    192         row = c.fetchone()
    193         c.close()
    194        
    195         if row is not None:
    196                 return row[0]
    197        
    198         # Insert a new genre.
    199         c = db.cursor()
    200         c.execute("INSERT INTO videocategory(category) VALUES (%s)", (genre_name.capitalize(),))
    201         newid = c.lastrowid
    202         c.close()
    203        
    204         return newid
    205        
    206186def parse_meta(variable, oldvalue, emptyvalue="", meta=""):
    207187        """
    208188        Parses a single metadata from a metadata string (returned by the imdbpy.py, etc.).
     
    320300                       
    321301        return save_video_metadata_to_mythdb(videopath, metadata)
    322302               
    323 def prune_mythdb_metadata():
    324         global db
    325         c = db.cursor()
    326         c.execute("""
    327                 SELECT intid, filename
    328                 FROM videometadata""")
    329        
    330         row = c.fetchone()
    331         while row is not None:
    332                 intid = row[0]
    333                 filename = row[1]
    334                 if not os.path.exists(filename):
    335                         print_verbose("%s not exist, removing metadata..." % filename)
    336                         c2 = db.cursor()
    337                         c2.execute("""DELETE FROM videometadata WHERE intid = %s""", (intid,))
    338                         c2.close()
    339                 row = c.fetchone()
    340         c.close()
    341                
    342 def mythvideo_metadata_id(videopath):
    343         """
    344         Finds the MythVideo metadata id for the given video path from the MythDB, if any.
    345        
    346         Returns None if no metadata was found.
    347         """
    348         global db
    349         c = db.cursor()
    350         c.execute("""
    351                 SELECT intid
    352                 FROM videometadata
    353                 WHERE filename = %s""", (videopath,))
    354         row = c.fetchone()
    355         c.close()
    356        
    357         if row is not None:
    358                 return row[0]
    359         else:
    360                 return None
    361        
    362 def mythtv_setting(value, hostname = '%'):
    363         """
    364         Returns the value for the given MythTV setting.
    365        
    366         Returns None if the settings was not found. If multiple rows are
    367         found (multiple hostnames), returns the value of the first one.
    368         """
    369         global db
    370         c = db.cursor()
    371         c.execute("""
    372                 SELECT data
    373                 FROM settings
    374                 WHERE value LIKE(%s) AND hostname LIKE(%s) LIMIT 1""",
    375                 (value, hostname))
    376         row = c.fetchone()
    377         c.close()
    378        
    379         if row is not None:
    380                 return row[0]
    381         else:
    382                 return None
    383        
    384303def save_video_metadata_to_mythdb(videopath, metadata, child=-1, disc=None):
    385304        """
    386305        Updates the given metadata for the given video file.
     
    406325                 (None, None, 0, None, None, None, None,
    407326                  0.0, None, 0, None, None, child, "")
    408327                 
    409         intid = mythvideo_metadata_id(videopath)
     328        intid = mythvideo.getMetadataId(videopath)
    410329        if intid is not None:
    411                 if not overwrite:               
     330                if not overwrite:
    412331                        print_verbose("Metadata already exist in MythDB, not overwriting it.")
    413                         return None                     
     332                        return None
    414333        else:
    415334                print_verbose("No metadata in MythDB, creating a new one.")
    416335                # Create a new empty entry at this point so we can use the common UPDATE code
    417336                # to actually insert the data.
    418                 c = db.cursor()
    419                 c.execute("""INSERT INTO videometadata(filename) VALUES(%s)""", (videopath,))
    420                 intid = c.lastrowid
    421                 c.close()
     337                intid = mythvideo.setMetadata({'filename': videopath})
    422338       
    423                        
    424339        def parse_metadata(variable, oldvalue, emptyvalue="", meta=metadata):
    425340                return parse_meta(variable, oldvalue, emptyvalue, meta)
    426                                                        
     341               
    427342        if title is None:
    428343                title = parse_metadata('Title', title)
    429344       
     
    437352       
    438353        if poster_search:
    439354                print_verbose("Fetching a poster image...")
    440                 coverfile = find_poster_image(title, inetref)   
     355                coverfile = find_poster_image(title, inetref)
    441356                if coverfile is not None:
    442357                        print_verbose("Found a poster.")
    443358                else:
     
    452367                        m = re.match(akaRegexp, aka)
    453368                        if m is not None:
    454369                                title = m.group(1) + " (" + title + ")"
    455                                 print_verbose("Found AKA: %s" % title)                         
     370                                print_verbose("Found AKA: %s" % title)
    456371                                break
    457372               
    458373        if disc is not None:
     
    505420       
    506421        if len(genres) < 1:
    507422                print_verbose("No genres.")
    508                 category = get_genre_id("Unknown")
     423                category = mythvideo.getGenreId("Unknown")
    509424        else:
    510425                # Only one genre supported?
    511                 category = get_genre_id(genres[0])                     
     426                category = mythvideo.getGenreId(genres[0])
    512427       
    513428        if coverfile == None:
    514429                coverfile = "No cover"
    515430               
    516         c = db.cursor()
    517 
    518         c.execute(u"""UPDATE videometadata
    519                 SET showlevel = 1, browse = 1, childid = %s, playcommand = %s, title = %s,
    520                     director = %s, plot = %s, rating = %s, inetref = %s, category = %s,
    521                     year = %s, userrating = %s, length = %s, filename = %s, coverfile = %s
    522                 WHERE intid = %s""",
    523                                 (childid, playcommand, title.encode("utf8"),
    524                                         director.encode("utf8"), plot.encode("utf8"), rating,
    525                                         inetref, category, year, userrating, length, filename,
    526                                         coverfile, intid))
    527         c.close()
     431        mythvideo.setMetadata({'showlevel': 1, 'browse': 1, 'childid': childid,
     432                                        'playcommand': playcommand, 'title': title.encode('utf8'),
     433                                        'director': director.encode('utf8'), 'plot': plot.encode('utf8'),
     434                                        'rating': rating, 'inetref': inetref, 'category': category,
     435                                        'year': year, 'userrating': userrating, 'length': length,
     436                                        'filename': filename, 'coverfile': coverfile}, intid)
    528437        return intid
    529438                               
    530439def find_poster_image(title, imdb_id):
     
    883792        # Check if we are not in overwrite mode and there is existing data
    884793        # for the wanted targets (metadata files and/or MythDB).
    885794        if not overwrite:               
    886                 need_mythdb_data = dbimport and mythvideo_metadata_id(path) is None
     795                need_mythdb_data = dbimport and mythvideo.getMetadataId(path) is None
    887796                need_metadata_file = metafiles
    888797                if metafiles and meta_file is not None:
    889798                        need_metadata_file = not os.path.exists(meta_file)
     
    991900                print_verbose("IMDb ID %s given manually." % options.imdb_id)           
    992901                       
    993902        if dbimport or prune:
    994                 if not db_support:
    995                         print "You must install MySQLdb module to make direct DB importing to work"
     903                if not mythtv:
     904                        print "You must have the MythTV module to make direct DB importing to work"
    996905                        sys.exit(1)
    997                 if not init_db():
    998                         print "Database connection failed."
    999                         sys.exit(1)     
    1000                 poster_dir = mythtv_setting("VideoArtworkDir", socket.gethostname())
     906                poster_dir = mythtv.getSetting("VideoArtworkDir", socket.gethostname())
    1001907               
    1002908       
    1003909        if prune:
    1004                 prune_mythdb_metadata()
     910                mythvideo.pruneMetadata()
    1005911       
    1006912        for path in paths:
    1007913