def populate_serie(self, name, orig_name=None): tvdb_en = Tvdb(actors=True, banners=True) tvdb_es = Tvdb(language="es") try: # Si la serie esta en solo en castellano no la reconoce reg_en = tvdb_en[name] reg_es = tvdb_es[name] except: try: reg_en = tvdb_en[orig_name] reg_es = tvdb_es[orig_name] except: return None try: db_serie = m.Serie.objects.get(name=name) except m.Serie.DoesNotExist: db_serie = m.Serie() db_serie.name = name db_serie.name_en = reg_en["seriesname"] db_serie.name_es = reg_es["seriesname"] if reg_en["network"]: db_serie.network = self.populate_network(reg_en["network"]) db_serie.runtime = reg_en["runtime"] db_serie.description_en = reg_en["overview"] db_serie.description_es = reg_es["overview"] db_serie.finished = reg_en["status"] == "Ended" db_serie.save() for genre in self.populate_genres(reg_en["genre"]): db_serie.genres.add(genre) if reg_en["poster"]: img = urllib.urlretrieve(reg_en["poster"]) db_img = m.ImageSerie(is_poster=True, title=reg_en["seriesname"]) db_img.serie = db_serie file_content = ContentFile(open(img[0]).read()) db_img.src.save(os.path.basename(reg_en["poster"]), file_content) db_img.save() for actor in reg_en["_actors"]: if not actor["name"]: continue #This field is needed db_actor = self.populate_actor(actor) db_role = m.Role(actor=db_actor, serie=db_serie, role=actor["role"] or "") try: db_role.save() except: continue self.populate_episodes(db_serie, reg_en, reg_es) return db_serie
def main(): # TODO: on jarvis use sys.listitem and getProperty, getfilename, getVideoInfoTag stream_file = xbmc.getInfoLabel('ListItem.FileNameAndPath') url = get_url(stream_file) if url is None: db_type = xbmc.getInfoLabel('ListItem.DBTYPE') if db_type == "movie": imdbnumber = xbmc.getInfoLabel('ListItem.IMDBNumber') url = "plugin://{0}/movies/play/{1}/{2}/select".format(pluginid, "imdb", imdbnumber) else: storage_path = xbmc.translatePath('special://profile/addon_data/%s/.storage/' % pluginid) if not os.path.isdir(storage_path): os.makedirs(storage_path) tvdb = Tvdb("0629B785CE550C8D", language="all", cache=storage_path) title = xbmc.getInfoLabel('ListItem.TVShowTitle') year = xbmc.getInfoLabel('ListItem.Property(year)') season = xbmc.getInfoLabel('ListItem.Season') episode = xbmc.getInfoLabel('ListItem.Episode') results = [x['id'] for x in tvdb.search(title, year)] if results: tvdb_id = results[0] url = "plugin://{0}/tv/play/{1}/{2}/{3}/select".format(pluginid, tvdb_id, season, episode) else: title = "Meta" msg = "Failed to find media on TVDB" xbmc.executebuiltin('XBMC.Notification("%s", "%s", "%s", "%s")' % (msg, title, 2000, '')) xbmc.executebuiltin("PlayMedia({0})".format(url))
def _get_correct_tv_show(self, full_path): """ Arguments: full_path (str): The path to the episode file. Returns: (tvdb_api.Show): The tv show that the user chose. """ tv_show_info = guessit(full_path) try: tvdb_shows = Tvdb().search(tv_show_info['title']) except tvdb_shownotfound: print('Error: TV Show not found') exit(1) valid_tvdb_shows = [] for show in tvdb_shows: if show['seriesName'] != '** 403: Series Not Permitted **': if len(valid_tvdb_shows) < 5: valid_tvdb_shows.append(show) print('\nTVDB Search Results for \'{0}\''.format( tv_show_info['title'])) for index, show in enumerate(valid_tvdb_shows): print('{0}: {1}'.format(index + 1, show['seriesName'])) if len(valid_tvdb_shows) == 1: print('Automatically choosing only result') return Tvdb()[valid_tvdb_shows[0]['id']] return Tvdb()[valid_tvdb_shows[self._parse_input()]['id']]
def buildCollectionMenu(items, name): menu = [] collection = 0 try: artwork = Tvdb(banners=True)[name]['_banners']['season']['raw'] except: pass details = json.loads( crunchyroll_api("info", {"collection_id": items[0]['collection_id']})) if int(details['data']['season']) > 0: for item in items: if item['free_available'] is True: if collection != item['collection_id']: collection = item['collection_id'] details = json.loads( crunchyroll_api( "info", {"collection_id": item['collection_id']})) if " Dub)" not in details['data']['name']: poster = "" try: t = Tvdb() for s in artwork: logError( str(s['subKey']) + " = " + (details['data']['season'])) if str(s['subKey']) == str( details['data']['season']): poster = "https://www.thetvdb.com/banners/" + s[ 'fileName'] except: pass menu.append({ "title": "Season " + str(details['data']['season']) + " - " + details['data']['name'], "url": "list_media", "extras": { "series_id": item['series_id'], "limit": "10000", "collection_id": collection }, "mode": 6, "poster": poster, "icon": poster, "fanart": item['screenshot_image']['full_url'], "type": "video", "plot": details['data']['description'] }) else: buildEpisodesMenu(items) addMenuItems(menu, isFolder=True)
def main(): # TODO: on jarvis use sys.listitem and getProperty, getfilename, getVideoInfoTag stream_file = xbmc.getInfoLabel('ListItem.FileNameAndPath') url = get_url(stream_file) if url is None: db_type = xbmc.getInfoLabel('ListItem.DBTYPE') if db_type == "movie": imdbnumber = xbmc.getInfoLabel('ListItem.IMDBNumber') url = "plugin://{0}/movies/play/{1}/{2}/select".format( pluginid, "imdb", imdbnumber) elif db_type == "episode": storage_path = xbmc.translatePath( 'special://profile/addon_data/%s/.storage/' % pluginid) if not os.path.isdir(storage_path): os.makedirs(storage_path) tvdb = Tvdb("0629B785CE550C8D", cache=storage_path) title = xbmc.getInfoLabel('ListItem.TVShowTitle') year = xbmc.getInfoLabel('ListItem.Property(year)') season = xbmc.getInfoLabel('ListItem.Season') episode = xbmc.getInfoLabel('ListItem.Episode') dbid = xbmc.getInfoLabel('ListItem.DBID') results = tvdb.search(title, year, language="all") if results: tvdb_id = None identifier = get_tvshow_id_by_episode(dbid) if identifier: by_id = [ x for x in results if x['id'] == identifier or x.get('imdb_id') == identifier ] if by_id: tvdb_id = by_id[0]['id'] if tvdb_id is None: tvdb_id = results[0]['id'] url = "plugin://{0}/tv/play/{1}/{2}/{3}/select".format( pluginid, tvdb_id, season, episode) else: title = "Meta" msg = "Failed to find media on TVDB" xbmc.executebuiltin( 'XBMC.Notification("%s", "%s", "%s", "%s")' % (msg, title, 2000, '')) xbmc.executebuiltin("PlayMedia({0})".format(url))
def populate_seasons(self, db_serie, ntemp): try: db_season = m.Season.objects.get(serie=db_serie, season=ntemp) except m.Season.DoesNotExist: db_season = m.Season() db_season.serie = db_serie db_season.season = int(ntemp) tvdb_en = Tvdb(actors=True, banners=True) reg_en = tvdb_en[db_serie.name] db_season.save() # seasonwide? season_banners = reg_en['_banners']['season']['season'] for img_banner in season_banners: if int(ntemp) == int(season_banners[img_banner]['season']): img_url = season_banners[img_banner]['_bannerpath'] img_title = season_banners[img_banner]['id'] img = urllib.urlretrieve(img_url) db_img = m.ImageSeason(is_poster=True, title=img_title) db_img.season = db_season file_content = ContentFile(open(img[0]).read()) db_img.src.save(os.path.basename(img_url), file_content) db_img.save()
def populate_seasons(self, db_serie, ntemp): try: db_season = m.Season.objects.get(serie=db_serie, season=ntemp) except m.Season.DoesNotExist: db_season = m.Season() db_season.serie = db_serie db_season.season = int(ntemp) tvdb_en = Tvdb(actors=True, banners=True) reg_en = tvdb_en[db_serie.name] db_season.save() # Try Season image, if it's do nothing.. # If not exists, then # check for banners # create banners try: season_banners = reg_en['_banners']['season']['season'] except KeyError: return db_season for img_banner in season_banners: if int(ntemp) == int(season_banners[img_banner]['season']): img_url = season_banners[img_banner]['_bannerpath'] img_title = season_banners[img_banner]['id'] img = urllib.urlretrieve(img_url) db_img = m.ImageSeason(is_poster=True, title=img_title) db_img.season = db_season file_content = ContentFile(open(img[0]).read()) db_img.src.save(os.path.basename(img_url), file_content) db_img.save() return db_season
def __init__(self, opts, dirPath): if opts.verbose: print "Connecting to the TVDB... " #end if verbose self.tvdb = Tvdb(debug = opts.debug, interactive = opts.interactive, banners = True) self.mp4tagger = "mp4tags" self.dirPath = dirPath
def getByURL(self, url): if not url.isdigit(): raise tvdb_shownotfound() tv = Tvdb() return tv[int(url)]
def update_info(self): '''Searches thetvdb.com and updates all episodes it contains ''' database = Tvdb(cache=self.cache, apikey=self.apikey) self.name = database[self.tv_show.real_name][self.s_id][ self.e_id]['episodename'] self.description = database[self.tv_show.real_name][self.s_id][ self.e_id]['overview'] self.episode_number = database[self.tv_show.real_name][self.s_id][ self.e_id]['episodenumber'] self.director = database[self.tv_show.real_name][self.s_id][ self.e_id]['director'] self.writer = database[self.tv_show.real_name][self.s_id][ self.e_id]['writer'] self.rating = database[self.tv_show.real_name][self.s_id][ self.e_id]['rating'] self.season = database[self.tv_show.real_name][self.s_id][ self.e_id]['seasonnumber'] self.image = database[self.tv_show.real_name][self.s_id][ self.e_id]['filename'] imdb_id = database[self.tv_show.real_name][self.s_id][ self.e_id]['imdb_id'] self.imdb_id = IMDB_TITLE + (imdb_id if imdb_id else '') _date = database[self.tv_show.real_name][self.s_id][ self.e_id]['firstaired'] if _date: date_split = _date.split('-') self.airdate = datetime.date(int(date_split[0]), int(date_split[1]), int(date_split[2])) else: self.airdate = datetime.date(1, 1, 1) # ugly... i know
def getBanner(self, url): best = None best_rating = -1 if not url.isdigit(): raise tvdb_shownotfound() tv = Tvdb(banners=True) show = tv[int(url)] banners = show["_banners"] fanart = banners.get("fanart", {}) for res in fanart: items = fanart.get(res) for id in items: item = items.get(id) path = item.get("_thumbnailpath") rating = float(item.get("rating", 0)) if rating > best_rating: best = path return self.downloadBanner(best)
def tvnamer(paths): """Main tvnamer function, takes an array of paths, does stuff. """ p("#" * 20) p("# Starting tvnamer") episodes_found = [] for cfile in findFiles(paths): parser = FileParser(cfile) try: episode = parser.parse() except InvalidFilename as e: warn("Invalid filename: %s" % e) else: if episode.seriesname is None and Config['force_name'] is None and Config['series_id'] is None: warn("Parsed filename did not contain series name (and --name or --series-id not specified), skipping: %s" % cfile) else: episodes_found.append(episode) if len(episodes_found) == 0: raise NoValidFilesFoundError() p("# Found %d episode" % len(episodes_found) + ("s" * (len(episodes_found) > 1))) # Sort episodes by series name, season and episode number episodes_found.sort(key = lambda x: x.sortable_info()) # episode sort order if Config['order'] == 'dvd': dvdorder = True else: dvdorder = False if not PY2 and os.getenv("TRAVIS", "false") == "true": # Disable caching on Travis-CI because in Python 3 it errors with: # # Can't pickle <class 'http.cookiejar.DefaultCookiePolicy'>: it's not the same object as http.cookiejar.DefaultCookiePolicy cache = False else: cache = True tvdb_instance = Tvdb( interactive = not Config['select_first'], search_all_languages = Config['search_all_languages'], language = Config['language'], dvdorder = dvdorder, cache=cache, apikey=TVNAMER_API_KEY, ) for episode in episodes_found: processFile(tvdb_instance, episode) p('') p("#" * 20) p("# Done")
def search_for_show(search_term, apikey=None): '''Auxiliar method to search for TVShows in the database, returns None if no show found''' try: return Tvdb(cache=False, apikey=apikey).search(search_term) except tvdb_error: raise NoConnectionException except tvdb_shownotfound: return None
def create_tvdb(language=LANG): from tvdb_api import Tvdb if len(TVDB_API) == 16: try: TVDB_KEY = TVDB_API except: TVDB_KEY = "0629B785CE550C8D" else: TVDB_KEY = "0629B785CE550C8D" return Tvdb(TVDB_KEY, language=language, cache=plugin.storage_path)
def test_name_generation_on_testfiles(): # Test data stores episode names in English, language= is normally set # via the configuration, same with search_all_languages. tvdb_instance = Tvdb(search_all_languages=True, language='en') for category, testcases in files.items(): for testindex, curtest in enumerate(testcases): cur_tester = lambda x: verify_name_gen(x, tvdb_instance) cur_tester.description = 'test_name_generation_%s_%d: %r' % ( category, testindex, curtest['input']) yield (cur_tester, curtest)
def nameByName(showname, episodename): """Searches for episode with correct name. The tvdb_api search is very simple, along the lines of: if searchterm in current_episodename: ..so the episode name must be accurate """ try: show = Tvdb(interactive=True)[showname] except Exception as e: print e return None, [] sr = show.search(episodename, key='episodename') if len(sr) == 0: another = " ".join(episodename.replace('_', ' ').split(" ")[0:2]) print "Zero results, Searching for {} instead...".format(another) sr = show.search(another, key='episodename') if len(sr) != 1: print "Got %d search results for %s episode named %s" % (len(sr), showname, episodename) return show['seriesname'], sr
def __init__(self, showid, id_type, season=None, episode=None, language='en'): super(FetcherTvdb, self).__init__(showid, id_type, season=season, episode=episode, language=language) fetcher = Tvdb() if language in fetcher.config['valid_languages']: self.language = language else: self.language = 'en' log.error('Language %s not supported by tvdb, defaulting to English. Supported languages are {%s}', language, fetcher.config['valid_languages']) self.fetcher = Tvdb(interactive=False, cache=True, banners=True, actors=True, forceConnect=True, language=self.language) if self.id_type == 'tvdb_id': try: self._fetcherid = int(self.showid) except: raise FetcherException('id for the show should be an int') else: raise FetcherException('Tvdb only supports tvdb ids')
def test_name_generation_on_testfiles(): # type: () -> None # Test data stores episode names in English, language= is normally set # via the configuration, same with search_all_languages. tvdb_instance = Tvdb(search_all_languages=True, cache=True, language='en', apikey=TVNAMER_API_KEY) for category, testcases in files.items(): for curtest in testcases: verify_name_gen(curtest, tvdb_instance)
def update_info(self, header_only=False, override_cache=False, banners=False): '''Searches thetvdb.com and generates class attributes Parameters: header_only - does not retrive season and episodes info override_cache - path to new cache, ignoring class defined cache NOTE: if set, greatly increses performance banners - retrieve season banners and posters This method function is responsible for building the entire data structure of a TV Show It is mandatory that self.real_name is set otherwise build will fail ''' database = Tvdb( cache=(self.cache if not override_cache else override_cache), banners=banners, apikey=self.apikey) if not header_only: # updates seasons list seasons_list = database[ self.real_name].keys() # retrieve list of available seasons if seasons_list[0] == 0: del (seasons_list[0]) # remove first element if it is season 0 self.seasons = [] for i in seasons_list: # generates the seasons list new_season = Season(s_id=i, tv_show=self, cache=(self.cache if not override_cache else override_cache), apikey=self.apikey) self.seasons.append(new_season) self.last_updated = datetime.date.today() # update TV Show info self.description = database[self.real_name]['overview'] self.genre = database[self.real_name]['genre'] self.runtime = database[self.real_name]['runtime'] self.status = database[self.real_name]['status'] self.network = database[self.real_name]['network'] self.air_dayofweek = database[self.real_name]['airs_dayofweek'] self.air_time = database[self.real_name]['airs_time'] self.rating = database[self.real_name]['rating'] self.actors = database[self.real_name]['actors'] self.poster = database[self.real_name]['poster'] self.banner = database[self.real_name]['banner'] if banners: self.all_images = database[self.real_name]['_banners'] imdb_id = database[self.real_name]['imdb_id'] self.imdb_id = IMDB_TITLE + (imdb_id if imdb_id else '')
def rename(showName, seasonNumber, path): tvdb = Tvdb() fileNames = get_files(path) os.chdir(path) flag = False for fileName in fileNames: episodeNumber = get_episode_number(fileName) if episodeNumber: episode = tvdb[showName][seasonNumber][episodeNumber] fileExtension = get_file_extension(fileName) episodeName = str( episodeNumber) + " - " + episode['episodename'] + fileExtension os.rename(fileName, episodeName) flag = True if flag: print("Rename Complete") else: print("No files changed")
def update_info(self, cache=False, banners=True): '''Searches thetvdb.com and updates all episodes it contains Parameters: cache - path to new cache, ignoring class defined cache NOTE: if set, greatly increses performance banners - retrieve season banners and posters ''' # update posters database = Tvdb(cache=self.cache if not cache else cache, banners=banners, apikey=self.apikey) try: posters = database[self.tv_show.real_name]['_banners']['season'] except tvdb_attributenotfound: pass # posters werent loaded so ignore them except KeyError: print "No poster for %d : %s" % (self.s_id, self.tv_show.name) else: # update posters self.poster = [] # clear cached value if 'season' in posters: # check for existance for entry in posters['season']: misc = posters['season'][entry] if misc['language'] == 'en' and misc['season'] == str( self.s_id): self.poster.append(misc['_bannerpath']) # update wide posters self.poster_wide = [] # clear ceched value if 'seasonwide' in posters: # check for existence for entry in posters['seasonwide']: misc = posters['seasonwide'][entry] if misc['language'] == 'en' and misc['season'] == str( self.s_id): self.poster_wide.append(misc['_bannerpath']) # update episodes list episodes_list = database[self.tv_show.real_name][self.s_id].keys() self.episodes = [] # reset cached values for i in episodes_list: # generate the episodes list new_episode = Episode(e_id=i, s_id=self.s_id, tv_show=self.tv_show, cache=self.cache, apikey=self.apikey) self.episodes.append(new_episode)
def main(shows): tvdb = Tvdb() data = [] pool = Pool() for name in tqdm(shows, desc = "Shows", unit = "show"): show = tvdb[name] if name == "Black-ish": name += " 2014" elif name == "The Good Place": name += " 2016" elif name == "What I Like About You": name += " 2002" elif name == "Unbreakable Kimmy Schmidt": name += " 2015" elif name == "Love": name += " 2016" elif name == "Insecure": name += " 2016" elif name == "Jane the Virgin": name += " 2014" elif name == "The Golden Girls": name += " 1985" num_seasons = len(show.keys()) num_seasons = min(num_seasons, 25) query_name = name.lower().replace("!", "").replace("-", " ").replace(" ", "-").replace("'", "") for season in tqdm(range(1, num_seasons), desc = name, unit = "season"): num_episodes = len(show[season]) info = [] for i in range(1, num_episodes + 1): try: info.append((i, query_name, show[season][i], season)) except Exception as e: #print(e) pass for result in tqdm(pool.imap(get_data, info), desc = "Episodes", unit = "episode", total = num_episodes): if result is not None: data.append(result) pool.close() pool.join() with open("scripts.csv", "a") as f: pd.DataFrame(data).to_csv(f, index = False, sep = "\t", header = False)
def test_name_generation_on_testfiles(): # Test data stores episode names in English, language= is normally set # via the configuration, same with search_all_languages. if not PY2 and os.getenv("TRAVIS", "false") == "true": # Disable caching on Travis-CI because in Python 3 it errors with: # # Can't pickle <class 'http.cookiejar.DefaultCookiePolicy'>: it's not the same object as http.cookiejar.DefaultCookiePolicy cache = False else: cache = True tvdb_instance = Tvdb(search_all_languages=True, language='en', cache=cache) for category, testcases in files.items(): for testindex, curtest in enumerate(testcases): cur_tester = lambda x: verify_name_gen(x, tvdb_instance) cur_tester.description = 'test_name_generation_%s_%d: %r' % ( category, testindex, curtest['input']) yield (cur_tester, curtest)
def search(self, text): tv = Tvdb() return tv.search(text)
#!/usr/bin/env python2 from tvdb_api import Tvdb from tvdb_exceptions import tvdb_shownotfound import re import sys import os t=Tvdb(True) DIRECTORY_SLASH = '\\' if os.name =='nt' else '/' BASE_URL = 'http://thetvdb.com/?tab=series&id={tv_show_id}&lid=7' TV_SHOW_NFO = 'tvshow.nfo' MATCH_YEAR = re.compile('\(\d+\)') FAILED = [] SUCCESS = [] SKIPPED = [] def create_url(tv_show_id): return BASE_URL.format(tv_show_id=tv_show_id) def add_slash(directory): if (directory[-1] != DIRECTORY_SLASH): directory += DIRECTORY_SLASH return directory def create_file(directory, url): directory = add_slash(directory)
def create_tvdb(language=LANG): from tvdb_api import Tvdb return Tvdb("0629B785CE550C8D", language=language, cache=plugin.storage_path)
def main(): # Process arguments parser = OptionParser( usage=u"%prog -dhiuv <seriesname> [<seasonnumber> <episodenumber>]") parser.add_option("-d", "--debug", action="store_true", default=False, dest="debug", help=u"Show debugging info") parser.add_option( "-i", "--interactive", action="store_true", default=False, dest="interactive", help= u"Activate the tvdb_api interactive mode\n(allows prompted selection from matching series" ) parser.add_option("-u", "--usage", action="store_true", default=False, dest="usage", help=u"Display examples for executing the meta script") parser.add_option("-v", "--version", action="store_true", default=False, dest="version", help=u"Display version and author") (opts, args) = parser.parse_args() # Output debugging info? if opts.debug == True: print "opts", opts print "\nargs", args # Output version info & terminate? if opts.version == True: sys.stdout.write("%s - %s (%s) by %s\n" % (__file__, __title__, __version__, __author__)) sys.exit(0) # Output usage info & terminate? if opts.usage == True: sys.stdout.write(usage_description) parser.print_usage() sys.stdout.write(usage_examples) sys.exit(0) # Check for required arguments if len(args) == 0: parser.error("Must supply at least a series name!") sys.exit(1) if len(args) > 1: seasonnum = args[1] else: seasonnum = None if len(args) == 2: parser.error("Must supply an episode number as well!") sys.exit(1) if len(args) == 3: episodenum = args[2] else: episodenum = None # Check arguments seriesname = args[0] if seasonnum is not None: if seasonnum.isdigit(): seasonnum = int(seasonnum) else: parser.error("Season number must be numeric!") if episodenum is not None: if episodenum.isdigit(): episodenum = int(episodenum) else: parser.error("Episode number must be numeric!") # Connect to database tvdb = Tvdb(interactive=opts.interactive, cache=True) # Process query show = tvdb[seriesname] if seasonnum is None: print show['seriesname'] + ":" for key in show.data.keys(): if key != 'seriesname': print "\t" + key + ": ", print show[key] else: episode = show[seasonnum][episodenum] print show['seriesname'] + " " + episode['episodename'] + ":" for key in episode.keys(): if key != 'episodename': print "\t" + key + ": ", print episode[key] # Finished sys.exit(0)
from my_password import (p_tvdb,p_mysql) import sys import getopt import sqlite3 import syslog # specify our log file, here local0 ! syslog.openlog('rss', 0, syslog.LOG_LOCAL0) # Setup basic directory http_dir = 'https://fi08.us.to/' xml_dir = "/home/fi08/" watch_dir = "/home/torrent/public/" # Setup tvdb using our apikey tvdb_instance = Tvdb(apikey=p_tvdb.key) # Format filename : lowercase and remove spaces " " with dots "." def format(filename): temp ='' for i in filename.split(' '): temp = temp + i.lower() +"." temp = temp.rstrip(".") name="" for i in temp.split('_'): name = name + i.lower() +"." name = name.rstrip(".") return name # todo, remove double dots...
def main(): parser = OptionParser(usage="%prog [options] <file or directories>") parser.add_option("-d", "--debug", action="store_true", default=False, dest="debug", help="show debugging info") parser.add_option( "-b", "--batch", action="store_false", dest="interactive", help= "selects first search result, requires no human intervention once launched", default=False) parser.add_option( "-i", "--interactive", action="store_true", dest="interactive", default=True, help="interactivly select correct show from search results [default]") parser.add_option( "-s", "--selectfirst", action="store_true", dest="selectfirst", default=False, help= "automatically select first series search result (instead of showing the select-series interface)" ) parser.add_option( "-r", "--recursive", action="store_true", dest="recursive", default=True, help="recursivly search supplied directories for files to rename") parser.add_option( "-a", "--always", action="store_true", default=False, dest="always", help= "always renames files (but still lets user select correct show). Can be changed during runtime with the 'a' prompt-option" ) parser.add_option( "-f", "--force", action="store_true", default=False, dest="force", help= "forces file to be renamed, even if it will overwrite an existing file" ) opts, args = parser.parse_args() if len(args) == 0: parser.error("No filenames or directories supplied") #end if len(args) allFiles = findFiles(args, opts.recursive, verbose=opts.debug) validFiles = processNames(allFiles, verbose=opts.debug) if len(validFiles) == 0: sys.stderr.write("No valid files found\n") sys.exit(2) print "#" * 20 print "# Starting tvnamer" print "# Processing %d files" % (len(validFiles)) t = Tvdb(debug=opts.debug, interactive=opts.interactive, select_first=opts.selectfirst) print "# ..got tvdb mirrors" print "# Starting to process files" print "#" * 20 for cfile in validFiles: print "# Processing %(file_seriesname)s (season: %(seasno)d, episode %(epno)d)" % ( cfile) processFile(t, opts, cfile) print "# Done"
"Parsed filename did not contain series name (and --name not specified), skipping: %s" % cfile) else: episodes_found.append(episode) if len(episodes_found) == 0: raise NoValidFilesFoundError() p("# Found %d episode" % len(episodes_found) + ("s" * (len(episodes_found) > 1))) # Sort episodes by series name, season and episode number episodes_found.sort(key=lambda x: x.sortable_info()) tvdb_instance = Tvdb(interactive=not Config['select_first'], search_all_languages=Config['search_all_languages'], language=Config['language']) for episode in episodes_found: processFile(tvdb_instance, episode) p('') p("#" * 20) p("# Done") def main(): """Parses command line arguments, displays errors from tvnamer in terminal """ opter = cliarg_parser.getCommandlineParser(defaults)
from datetime import datetime import os from configobj import ConfigObj import pinhook.plugin from tvdb_api import Tvdb, tvdb_shownotfound t = Tvdb() conf_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tv.conf') config = ConfigObj(conf_file) aliases = config["aliases"] def get_datekey(date): dkey = "%Y-%m-%d" datekey = datetime.strptime(date, dkey).strftime("%Y%m%d") datekey = int(datekey) return datekey def remove_bad_dates(show): eps = {} datelist = [] if len(show) == 1: for e in range(len(show[1])): e += 1 if show[1][e]['firstaired']: datekey = get_datekey(show[1][e]['firstaired']) eps[datekey] = (1, e) datelist.append(datekey)