Advertisement
gregwa

FCM 72 - TVFileSearch-2.py

Apr 9th, 2013
405
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. import os
  5. from os.path import join, getsize, exists
  6. import sys
  7. import apsw
  8. import re
  9. from xml.etree import ElementTree as ET
  10. import urllib
  11. import string
  12. from TvRage import TvRage
  13.  
  14. #=========================================
  15. def GetSeasonEpisode(filename):
  16.     GoOn = False
  17.     filename = filename.upper()
  18.    
  19.     #Should catch multi episode .S01E01.S01E02 type filenames
  20.     resp = re.search(r'(.*)\.s(\d{1,2})e(\d{1,2})\.s(\d{1,2})e(\d{1,2})',filename, re.I)
  21.     if resp:
  22.         showname = resp.group(1)
  23.         GoOn = True  
  24.     else:
  25.         # Should catch SddEdd or sddedd
  26.         resp = re.search(r'(.*).S(\d\d?)E(\d\d?)(\.*)', filename, re.I)  
  27.         if resp:
  28.             showname = resp.group(1)
  29.             GoOn = True
  30.         else:
  31.             #check for ddxdd
  32.             #resp = re.search(r'(.*).(\d\d?)x(\d\d?)(\.*)', filename, re.I)
  33.             resp = re.search(r'(.*)\.(\d{1,2})x(\d{1,2})(.*)', filename, re.I)
  34.             if resp:
  35.                 showname = resp.group(1)
  36.                 GoOn = True
  37.             else:
  38.                 #check for Sdddd
  39.                 resp = re.search(r'(.*).S(\d\d)(.\d\d?)' , filename, re.I)
  40.                 if resp:
  41.                     showname = resp.group(1)
  42.                     GoOn = True
  43.                 else:
  44.                     # Should catch xxx
  45.                     resp = re.search(r'(.*)(\d)(.\d\d?)',filename,re.I)
  46.                     if resp:
  47.                         showname = resp.group(1)
  48.                         GoOn = True
  49.     if GoOn:
  50.         shownamelength = len(showname) + 1
  51.         showname = showname.replace("."," ")
  52.         season = resp.group(2)
  53.         if len(season) == 1:
  54.             season = "0" + season
  55.         episode = resp.group(3)
  56.         ret = [showname,season,episode]
  57.         return True,ret
  58.     else:
  59.         ret = ["",-1,-1]
  60.         return False,ret
  61.  
  62. #=========================================
  63. def MakeDataBase():
  64.     # IF the table does not exist, this will create the table.  
  65.     # Otherwise, this will be ignored due to the 'IF NOT EXISTS' clause
  66.     sql = 'CREATE TABLE IF NOT EXISTS TvShows (pkID INTEGER PRIMARY KEY, Series TEXT, RootPath TEXT, Filename TEXT, Season TEXT, Episode TEXT, tvrageid TEXT,status TEXT);'
  67.     cursor.execute(sql)
  68.  
  69. #=========================================    
  70. def WalkThePath(filepath):
  71.  
  72.     showname = ""
  73.     # Open the error log file
  74.     efile = open('errors.log',"w")
  75.     for root, dirs, files in os.walk(filepath,topdown=True):
  76.         for file in [f for f in files if f.endswith (('.avi','mkv','mp4','m4v'))]:
  77.             # Combine path and filename to create a single variable.
  78.             fn = join(root,file)  
  79.             OriginalFilename,ext = os.path.splitext(file)
  80.             fl = file
  81.             isok,data = GetSeasonEpisode(fl)
  82.             if isok:
  83.                 showname = data[0]
  84.                 season = data[1]
  85.                 episode = data[2]
  86.                 print("Season {0} Episode {1}".format(season,episode))
  87.             else:
  88.                 print("No Season/EPisode")
  89.                 efile.writelines('---------------------------\n')
  90.                 efile.writelines('{0} has no series/episode informaiton\n'.format(file))
  91.                 efile.writelines('---------------------------\n\n')
  92.             #--------------------------------
  93.             sqlquery = 'SELECT count(pkid) as rowcount from TvShows where Filename = "%s";' % fl
  94.             try:
  95.                 for x in cursor.execute(sqlquery):
  96.                     rcntr = x[0]
  97.                 if rcntr == 0:  # It's not there, so add it
  98.                     try:
  99.                         sql = 'INSERT INTO TvShows (Series,RootPath,Filename,Season,Episode,tvrageid) VALUES (?,?,?,?,?,?)'
  100.                         cursor.execute(sql,(showname,root,fl,season,episode,-1))
  101.                     except:
  102.                         print("Error")
  103.                         efile.writelines('---------------------------\n')
  104.                         efile.writelines('Error writing to database...\n')
  105.                         efile.writelines('Filename = {0}\n'.format(file))                        
  106.                         efile.writelines('---------------------------\n\n')
  107.             except:
  108.                 print("Error")
  109.             print('Series - {0} File - {1}'.format(showname,file))
  110.         # Close the log file
  111.         efile.close
  112.     # End of WalkThePath  
  113.      
  114. def WalkTheDatabase():
  115.     tr = TvRage()
  116.     SeriesCursor = connection.cursor()
  117.     sqlstring = "SELECT DISTINCT series FROM TvShows WHERE tvrageid = -1"
  118.     for x in SeriesCursor.execute(sqlstring):
  119.         seriesname = x[0]
  120.         searchname = string.capwords(x[0]," ")
  121.         print("Requesting information on " + searchname)
  122.         sl = tr.FindIdByName(searchname)
  123.         which = tr.DisplayShowResult(sl)
  124.         if which == 0:
  125.             print("Nothing found for %s" % seriesname)
  126.         else:
  127.             option = int(which)-1
  128.             id = sl[option]['ID']
  129.             UpdateDatabase(seriesname,id)
  130.             GetShowStatus(seriesname,id)
  131.            
  132. def UpdateDatabase(seriesname,id):
  133.     idcursor = connection.cursor()
  134.     sqlstring = 'UPDATE tvshows SET tvrageid = ' + id + ' WHERE series = "' + seriesname + '"'
  135.     try:
  136.         idcursor.execute(sqlstring)
  137.     except:
  138.         print "error"
  139.  
  140. def GetShowStatus(seriesname,id):
  141.     tr = TvRage()
  142.     idcursor = connection.cursor()
  143.     dict = tr.GetShowInfo(id)
  144.     status = dict['Status']
  145.     sqlstring = 'UPDATE tvshows SET status = "' + status + '" WHERE series = "' + seriesname + '"'
  146.     try:
  147.         idcursor.execute(sqlstring)
  148.     except:
  149.         print "Error"
  150.        
  151. #=========================================    
  152. def main():
  153.     global connection
  154.     global cursor  
  155.  
  156.     # Create the connection and cursor.
  157.     connection = apsw.Connection("TvShows.db3")
  158.     cursor = connection.cursor()
  159.     MakeDataBase()
  160.     #=========================================
  161.     # Set your video media paths
  162.     #=========================================
  163.     startfolder = ["/extramedia/tv_files","/media/freeagnt/tv_files_2"]
  164.     #for cntr in range(0,2):
  165.         #WalkThePath(startfolder[cntr])    
  166.     WalkTheDatabase()
  167.     # Close the cursor and the database
  168.     cursor.close()
  169.     connection.close()
  170.  
  171.     print("Finished")
  172.  
  173. #=======================================
  174. if __name__ == '__main__':
  175.     main()
Advertisement
Advertisement
Advertisement
RAW Paste Data Copied
Advertisement