def setup_apikey(user_provided=None): '''Sets up the TVDB API key for this session This is done by looking to 4 different places in this order of preference: 1. If the user provided a key via the command-line, use it 2. If no key was provided, check the environment variable ``TVDB_APIKEY``. If that is set, uset it 3. If 1. and 2. failed and if the user has a file called ``.librarianrc`` on the current directory, load a config file from it and use the values set on it 4. If everything else fails and if the user has a file called ``.librarianrc`` on ther home directory, load a config file from it and use the values set on it If no key is found, a :py:exc:`RuntimeError` is raised Parameters: user_provided (:py:class:`str`, optional): If the user provided a key via the application command-line, pass it here Raises: RuntimeError: In case it cannot find a proper API key for TVDB ''' global server if user_provided is not None: server = tvdb.TVDB(user_provided) return envkey = os.environ.get('TVDB_APIKEY') if envkey is not None: server = tvdb.TVDB(envkey) return if os.path.exists('.librarianrc'): key = var_from_config('.librarianrc', 'apikeys', 'tvdb') if key is not None: server = tvdb.TVDB(key) return home_path = os.path.join(os.environ['HOME'], '.librarianrc') if os.path.exists(home_path): key = var_from_config(home_path, 'apikeys', 'tvdb') if key is not None: server = tvdb.TVDB(key) return raise RuntimeError('Cannot setup TVDB API key')
def get_new_show_input(db_directory): db = api.TVDB("B43FF87DE395DF56") if not os.path.exists(db_directory): print "tv shows directory does not exist" os.makedirs(db_directory) while True: print("--------------------------------------") name = raw_input("Enter TV Show name? : ") results = db.search(name, "en") print "Search Results :" count = 1 for result in results: print(str(count) + " - " + result.SeriesName) count = count + 1 print(str(count) + " - Search Again") sel = raw_input("Select 1 - " + str(count) + " : ") if (int(sel) == count): continue else: show = results[int(sel) - 1] print("Selected Series : " + show.SeriesName) show_data = { 'title': show.SeriesName, 'imdb_id': show.IMDB_ID, 'seasons': [], "erred_episodes": [] } json.dump( show_data, open(db_directory + show.SeriesName.replace(' ', '_') + ".json", 'w')) break
def show_covers(season, number, series): """ This function fetches show screenshots, called covers in this instance. You can think of them as thumbnails but I needed a word that could be generalised for movies and TV show images. In the event that a cover can't be found, a local placeholder will be used instead. This often triggers for recently aired shows but it's usually fixed within a day or so. You'll probably find anime is the most lacking since there's less eyeballs on fresh seasonal releases compared to eg; a Netflix series. :param season: A string containing the season number of the requested episode. :param number: A string containing the episode number of the requested episode. :param series: A string containing the name of the requested show. :return: A string containing a URL to an image. """ tvdb = api.TVDB(settings.TVDB) result = tvdb.search(series, 'en') try: show = result[0] url = show[season][number].filename if url != '': img = 'https://www.thetvdb.com/banners/{}'.format(url) else: raise Exception except Exception: img = 'https://static.thingsima.de/shared/img/no_still.png' return img
def _get_result(self, query, select_result): # First, fetch the show itself not_found_exception = self.MediaNotFoundException( 'Could not find the anime on thetvdb.') database = api.TVDB(config['thetvdb']['api_key']) try: results = database.search(query, config['thetvdb']['language']) if len(results) == 0: raise not_found_exception elif len(results) == 1: show = results[0] else: identifier = select_result( list((x.id, x.SeriesName) for x in results)) # We'll use the last iteration show variable for show in results: if show.id == identifier: break # Fetch the metadata show.update() except TVDBIndexError: raise not_found_exception return show
def get_series_id(series=None, language='en'): tv = api.TVDB(API_KEY) result = tv.search(series, language, cache=True) if result: series = result[0] return series.id return None
def load(self): self.settings.load() tpb_base_url = self.settings.get('tpb_base_url') self.api_tpb = TPB( 'https://thepiratebay.se' if not tpb_base_url else tpb_base_url) tvdb_api_key = self.settings.get('tvdb_api_key') self.api_tvdb = TVDB.TVDB( '81DD35DB106172E7' if not tvdb_api_key else tvdb_api_key)
class Plex2IMDb(threading.Thread): imdbpy = IMDb() tvdb = api.TVDB('B43FF87DE395DF56') thread_limiter = threading.BoundedSemaphore(10) def __init__(self, plex_obj): super().__init__() self.plex_obj = plex_obj self.imdb_id = None self.imdb_keywords = [] def run(self): self.thread_limiter.acquire() try: self.plex_guid = self.get_plex_guid() if 'imdb' in self.plex_guid: self.imdb_id = self.get_movie_id() elif 'tvdb' in self.plex_guid: self.imdb_id = self.get_episode_id() self.imdb_keywords = self.get_imdb_keywords() finally: self.thread_limiter.release() # @retry(ConnectTimeout, delay=2) def get_plex_guid(self): return self.plex_obj.guid def get_movie_id(self): return re.search(r'tt(\d*)\?', self.plex_guid).group() def get_episode_id(self): regex = r'\/\/(\d*)\/(\d*)\/(\d*)' series_id, season, episode = map(int, re.search(regex, self.plex_guid).groups()) series = self.get_tvdb_series(series_id) try: episode = series[season][episode] except TVDBIndexError: return None imdb_id = str(episode.IMDB_ID) if imdb_id.startswith('tt'): return imdb_id[2:] return imdb_id @retry((RemoteDisconnected, ResponseNotReady, AttributeError), delay=2) def get_tvdb_series(self, series_id): return self.tvdb.get_series(series_id, 'en') @retry(IMDbDataAccessError, delay=2) def get_imdb_keywords(self): if not self.imdb_id: return [] data = self.imdbpy.get_movie_keywords(self.imdb_id)['data'] return data.get('keywords', [])
def get_cast_name_tvdb(series_name='two and half man'): """ return cast name from tvdb series_name : name of series """ db = api.TVDB("05669A6CC3005169", actors=True, banners=True) result = db.search(series_name, "en") show = result[0] show.update() return show.Actors
def get_cast_name_tvdb(self, series_name='two and half man'): """ tv series name return cast list """ db = api.TVDB("05669A6CC3005169", actors=True, banners=True) result = db.search(series_name, "en") show = result[0] show.update() return show.Actors
def __init__(self, rtnDict=True): log.trace('SeriesInfo.__init__') super(SeriesInfo, self).__init__() seriesinfo_group = self.options.parser.add_argument_group( "Episode Detail Options", description=None) seriesinfo_group.add_argument("--sn", "--name", type=str, dest='series_name') seriesinfo_group.add_argument("--season", type=int, dest='season') seriesinfo_group.add_argument("--epno", type=int, action='append', dest='epno') seriesinfo_group.add_argument("--tvdb", dest="processes", action="append_const", const='tvdb', help="Information to come from TVDB") seriesinfo_group.add_argument("--tvrage", dest="processes", action="append_const", const='tvrage', help="Information to come from TVRage") seriesinfo_group.add_argument( "--MyTrakt", dest="processes", action="append_const", const='MyTrakt', help="Information to come from MyTrakt.tv") seriesinfo_group.add_argument( "--series-only", "--so", dest="get_episodes", action="store_false", default=False, help="Information to come from MyTrakt.tv") self.db = api.TVDB("959D8E76B796A1FB") self.trakt_user = None self._check_suffix = re.compile( '^(?P<SeriesName>.*)[ \._\-][\(](?P<Suffix>(?:19|20)\d{2}|[a-zA-Z]*)[\)].*$', re.I) self.last_series = Series() self.series = Series() self.rtnDict = rtnDict
def getNumAiredEpisodes(self, seriesId, season): tvdb = api.TVDB(self.__api_key) numEpisodes = 0 self.__numCheckedTvShows += 1 progress = self.__numCheckedTvShows * 100 / self.__numTvShows sys.stdout.write('\r') sys.stdout.write('[%-100s] %d%%' % ('=' * int(math.ceil(progress)), progress )) sys.stdout.flush() show = tvdb.get_series(seriesId, 'en') numEpisodes = len(show[season].filter(self.hasEpisodeAired)) return numEpisodes
def tvdb_info(self): from pytvdbapi import api from pytvdbapi.error import ConnectionError, TVDBNotFoundError, TVDBIdError db = api.TVDB("959D8E76B796A1FB") try: _tvdb = db.get_series(self.tvdb_id, "en") self.titleTVDB = _tvdb.SeriesName if type(self.titleTVDB) is unicode: self.titleTVDB = self.titleTVDB.encode('ascii', 'ignore') if not self.title == self.titleTVDB: if self.alias is None: self.alias = [] self.alias.append(self.titleTVDB) if hasattr(self, 'fileDetails'): self.fileDetails.seriesTitle = self.titleTVDB except (ConnectionError, TVDBNotFoundError, TVDBIdError): an_error = traceback.format_exc() self.ids['tvdb'] = None
def get_show_info(): tvdb = tvapi.TVDB(TVDB_API_KEY) page_names = get_all_page_names() split_page_names = split_camel_case(page_names) logfile = open("tvdb_data.log", "w") tvdb_data = {} num_pages_found = 0 for page, sp in itertools.izip(page_names, split_page_names): try: print(page), logfile.write((page + ',')) show = None results = tvdb.search(sp, 'en') # just pick the first result, I guess if len(results) > 0: show = results[0] num_pages_found += 1 if show: tvdb_data[page] = show print(show) logfile.write(repr(show)) except: print("There was an error; continuing") logfile.write(',ERROR') logfile.write('\n') logfile.flush() # I'm impatient time.sleep(2) print("TVDB entries found for {} of {} pages".format( num_pages_found, len(page_names))) print("pickling output to tvdb_data.pkl") pickle.dump((page_names, tvdb_data), open("tvdb_data.pkl", "wb"), -1)
def get_thumb(id=None, series=None, language='en', scale=False): thumb = None if not id: tv = api.TVDB(API_KEY, banners=True) result = tv.search(series, language, cache=True) if result: series = result[0] #can store the id's domain = tv.mirrors.data.pop(0).url #only get one banner #if we do anupdate we get full attribute list url = domain + '/banners/fanart/original/' + str( series.id) + u'-1.jpg' if scale: thumb = get_image(imageURL=url, scale=True) else: thumb = get_image(imageURL=url) #file = io.open('AppData\\Local\\Plex Media Server\\Plug-ins\\Dreambox.bundle\\Contents\\Resources\\{}.jpg'.format(series.id), 'wb') #file.write(thumb) #file.close() return thumb
#!/usr/bin/python3 """.""" import json from pytvdbapi import api DB_OB = api.TVDB('B43FF87DE395DF56') EPI_JSON = {} def get_episodes_json(show_name): """.""" result = DB_OB.search(show_name, 'en') show = result[0] no_of_seasons = len(show) for index in range(1, no_of_seasons): EPI_JSON[show_name.title() + ' Season ' + str(index)] = [] for index in range(1, no_of_seasons): season = show[index] no_of_episodes = len(season) for ep_index in range(1, no_of_episodes + 1): episode = season[ep_index] s_number = season.season_number e_number = episode.EpisodeNumber if s_number < 10: s_number = '0' + str(s_number) if e_number < 10: e_number = '0' + str(e_number) EPI_JSON[show_name.title() + ' Season ' + str( season.season_number)].append('S' + str(s_number) + 'E' + str(e_number) + ' ' + str(episode.EpisodeName)) with open(show_name.title() + '_episodes.json', 'w+') as jsonfile:
def simpleName(videoFileName): split = str.split(videoFileName) datepattern = re.compile(r'^[1,2][9,0,1]\d\d[0,1]\d[0-3]\d$') seasonpattern = re.compile(r'^[S,s]\d\d[E,e]\d\d$') #S03E20 abpattern = re.compile(r'^[E,e][P,p][0-9]+$') seasoninfo, title, aired, seasonepisode, newfilename, season, episode, apepi, absolute = None, None, None, None, None, None, None, None, None exclude = [ ':', '#', '%', '&', '{', '}', '\\', '<', '>', '*', '?', '/', '$', '!', "'", '/', '"', '@', '+', '|', '=', '.', ',', '-' ] sc = set(exclude) if int(dir.vidtype) == 1: print("Video is a TV Show", file=dir.thelog) for i in range(0, len(split)): if seasonpattern.match(split[i]) is not None: seasoninfo = split[i] season = seasoninfo[1:3] episode = seasoninfo[4:] title = " ".join(split[:i]) if seasoninfo is None: for i in range(0, len(split)): if abpattern.match(split[i]) is not None: title = " ".join(split[:i]) apepi = split[i] absolute = apepi[1:] if datepattern.match(split[i]) is not None: aired = split[i] if apepi is None: title = " ".join(split[:i]) if title is not None: print("Found video title", file=dir.thelog) db = api.TVDB(TVDB_APIKEY) show = None result = db.search(str(title), "en") try: show = result[0] except IndexError: print("no match found in TVDB with name", file=dir.thelog) show = None if show is not None: print("match found in TVDB", file=dir.thelog) if seasoninfo is not None: print("season info found in name", file=dir.thelog) try: season = show[int(season)] except IndexError: print("Episode Error: no season found for this show", file=dir.thelog) show = None try: episode = season[int(episode)] except IndexError: print("Episode Error: no episode found within season", file=dir.thelog) show = None if show is not None: newshowname = show.SeriesName newepisodename = None newepisodename = ''.join([ c for c in str(episode.EpisodeName) if c not in sc ]) newshowname = ''.join( [c for c in str(newshowname) if c not in sc]) newfilename = str(newshowname) + "-S" + str( format(episode.SeasonNumber, '02')) + "E" + str( format(episode.EpisodeNumber, '02')) + "-" + str(newepisodename) elif seasoninfo is None: print("show and season info not found in name", file=dir.thelog) if aired is not None: print("using airdate to find episode info", file=dir.thelog) newshowname = show.SeriesName match = datetime.datetime.strptime(aired, "%Y%m%d").date() episodes = show.filter( key=lambda ep: ep.FirstAired == match) newepisodename = None for ep in episodes: season = ep.SeasonNumber episode = ep.EpisodeNumber newepisodename = ep.EpisodeName if newepisodename is not None and season is not None and episode is not None: newepisodename = ''.join([ c for c in str(newepisodename) if c not in sc ]) newshowname = ''.join( [c for c in str(newshowname) if c not in sc]) newfilename = str(newshowname) + "-S" + str( format(season, '02')) + "E" + str( format(episode, '02')) + "-" + str(newepisodename) else: print("no episode found by airdate", file=dir.thelog) print("using airdate only", file=dir.thelog) newshowname = ''.join( [c for c in str(title) if c not in sc]) newfilename = str(newshowname) + "-" + str(aired) elif aired is None: print("no matches season, episode, or airdate", file=dir.thelog) newshowname = ''.join( [c for c in str(videoFileName) if c not in sc]) newfilename = str(newshowname) if show is None: print("no match found manually", file=dir.thelog) if seasoninfo is not None: print("show and season info found in name", file=dir.thelog) newshowname = ''.join( [c for c in str(title) if c not in sc]) newfilename = str(newshowname) + "-" + str(seasoninfo) elif seasoninfo is None: print("show and season info not found in name", file=dir.thelog) if aired is not None: print("using airdate only", file=dir.thelog) newshowname = ''.join( [c for c in str(title) if c not in sc]) newfilename = str(newshowname) + "-" + str(aired) elif aired is None: print("no matches season, episode, or airdate", file=dir.thelog) newshowname = ''.join( [c for c in str(videoFileName) if c not in sc]) newfilename = str(newshowname) else: print("no title found filename not changed", file=dir.thelog) title = " ".join(split[:i]) newshowname = ''.join( [c for c in str(videoFileName) if c not in sc]) newfilename = str(newshowname) elif int(dir.vidtype) == 0: print("video is a Movie", file=dir.thelog) for i in range(0, len(split)): if datepattern.match(split[i]) is not None: print("using movie date to find title only", file=dir.thelog) title = " ".join(split[:i]) newfilename = str(title) if title is None: print("no title found filename not changed", file=dir.thelog) newshowname = ''.join( [c for c in str(videoFileName) if c not in sc]) newfilename = str(newshowname) return newfilename
def init_tvdb(api_key='0629B785CE550C8D') -> api.TVDB: return api.TVDB(api_key)
from pytvdbapi import api from icalendar import Calendar, Event, Timezone from datetime import datetime, timedelta tvdb = api.TVDB("B43FF87DE395DF56") shows = [ "American Dad", "Brickleberry", "Family Guy", "Futurama", "Game of Thrones", "Hannibal", "Lucifer", "Narcos", "Sherlock", "South Park", "Vikings" ] class DateUtil: @staticmethod def getNextDay(date): return date + timedelta(days=1) class Show: show = None episodes = [] def __init__(self, showName): self.getShowByName(showName) self.parseEpisodes() def getShowByName(self, showName): self.show = tvdb.search(showName, "en")[0] def parseEpisodes(self):
def announce(ratingkey): tvdb = tapi.TVDB(conf.ttdb_key, banners=True) omdb.set_default('apikey', conf.omdb_key) year = datetime.datetime.today().year '''function returns viable data from tautulli''' taut = bot.api.Tautulli() # metadata = taut.get('get_metadata', rating_key=ratingkey) _type = metadata['response']['data']['library_name'] if _type == 'Series': thetvdb = metadata['response']['data']['parent_guid'].split( '//')[1].split('/')[0] episode = int(metadata['response']['data']['media_index']) season = int(metadata['response']['data']['parent_media_index']) #episode_name = metadata['response']['data']['title'] #title = metadata['response']['data']['grandparent_title'] #rating = metadata['response']['data']['rating'] + '/10' #release = metadata['response']['data']['originally_available_at'] #plot = metadata['response']['data']['summary'] _metadata = tvdb.get_series(thetvdb, 'en') title = _metadata.SeriesName plot = _metadata[season][episode].Overview rating = str(_metadata[season][episode].Rating) + '/10' episode_name = _metadata[season][episode].EpisodeName release = _metadata[season][episode].FirstAired from bot.api import ttdb imdbid = ttdb(thetvdb) omdbdata = omdb.imdbid('{}'.format(imdbid)) url = 'https://www.imdb.com/title/{}/'.format(imdbid) if rating == '0/10': rating = 'N/A' if release is '': release = str(year) + '*' if rating is '' or rating == '/10' or rating == 'N/A': rating = '1.0/10*' if plot == '': plot = 'N/A' if title == '' or title == 'N/A': title = 'N/A' embed = discord.Embed(title='New episode from {}'.format(title), url=url, colour=discord.Colour(0xf9c38b)) embed.add_field(name='Episode name', value=episode_name, inline=False) embed.add_field(name='Season', value=season, inline=True) embed.add_field(name='Episode', value=episode, inline=True) embed.add_field(name='Release date', value=release, inline=True) embed.add_field(name='Rating', value=rating, inline=True) embed.add_field(name='Plot', value=plot, inline=False) try: if omdbdata['poster'] != 'N/A': embed.set_thumbnail(url=omdbdata['poster']) except: pass embed.set_footer( text='Plexbot.py', icon_url= 'https://zhf1943ap1t4f26r11i05c7l-wpengine.netdna-ssl.com/wp-content/uploads/2018/01/pmp-icon-1.png' ) elif _type == 'Films' or _type == '4k Movies' or _type == 'Norsk': title = metadata['response']['data']['title'] release = metadata['response']['data']['originally_available_at'] plot = metadata['response']['data']['summary'] rating = metadata['response']['data']['rating'] + '/10' imdbid = metadata['response']['data']['guid'].split('//')[1].split( '?')[0] omdbdata = omdb.imdbid('{}'.format(imdbid)) if rating == '0/10': rating = 'N/A' if release is '': release = str(year) + '*' if rating is '' or rating == '/10': rating = '1.0/10*' if plot == '': plot = 'N/A' if title == '' or title == 'N/A': title = 'N/A' url = 'https://www.imdb.com/title/{}/'.format(imdbid) embed = discord.Embed(title='New movie "{}" available'.format(title), url=url, colour=discord.Colour(0xf9c38b)) embed.add_field(name='Original title', value=title) embed.add_field(name='Release date', value=release, inline=True) embed.add_field(name='Rating', value=rating, inline=True) embed.add_field(name='Plot', value=plot) try: if omdbdata['poster'] != 'N/A': embed.set_thumbnail(url=omdbdata['poster']) except: pass embed.set_footer( text='Plexbot.py', icon_url= 'https://zhf1943ap1t4f26r11i05c7l-wpengine.netdna-ssl.com/wp-content/uploads/2018/01/pmp-icon-1.png' ) else: logging.info('Added rating key {} in new library: {}'.format( ratingkey, _type)) embed = discord.Embed(title='A new item was added') embed.add_field(name='Rating key', value=ratingkey) embed.add_field(name='Section', value=_type) embed.set_footer( text='Plexbot.py', icon_url= 'https://zhf1943ap1t4f26r11i05c7l-wpengine.netdna-ssl.com/wp-content/uploads/2018/01/pmp-icon-1.png' ) webhook = Webhook.partial(conf.discord_webhook, conf.discord_webtoken, adapter=RequestsWebhookAdapter()) webhook.send('', embed=embed, username='******')
import os from pytvdbapi import api # local imports import dirmanager as dman import filemanager as fman import interface as ui # test git gittt = "gittt" git0 = gittt[0] # pytvdbapi key and instance TVDBAPI_KEY = "4452E85C22F29289" TVDB = api.TVDB(TVDBAPI_KEY) # initialise user interface cwd = os.getcwd() ui.initialise(cwd) # build dict mapping show folders to show objects showdirs_dict = dman.dirs_to_shows(TVDB) # loop through folders identified as tv series folders for show_folder, show in showdirs_dict.items(): # switch working directory to current tv show directory show_dir_path = os.path.abspath(show_folder) os.chdir(show_dir_path) # loop through each tv show folder
connection = MySQLdb.connect(host='localhost', user='******', passwd='Petransikey18', db='aristia') cursor = connection.cursor() dt0 = timezone.make_aware(datetime.combine(today - timedelta(days=2), time.min)) dt1 = timezone.make_aware( datetime.combine(today - timedelta(days=30), time.min)) dt3 = timezone.make_aware( datetime.combine(today - timedelta(days=500), time.min)) module_dir = os.path.dirname(__file__) # get current directory db = api.TVDB("D620620B2C727377", banners=True) #series = Series.objects.filter(lastlookup__lt=dt0) sql = "SELECT id,title FROM shows_series WHERE lastlookup < '%s'", (dt0) cursor.execute(sql) series = cursor.fetchall() for show in series: result = db.search(show.title, "en") tvdbshow = result[0] for tvdbseason in tvdbshow: for tvdbepi in tvdbseason: #Episode.objects.filter(due__lte=dt3).delete()# delete old episodes try: AiredDT = timezone.make_aware(
def __init__(self): log.trace('__init__ method: Started') super(CleanUp, self).__init__() trakt_auth_group = DadVision.cmdoptions.parser.add_argument_group( "Profiles", description=None) trakt_auth_group.add_argument("-y", "--grumpy", dest="HostName", action="append_const", const="grumpy", help="Entries for Grumpy") trakt_auth_group.add_argument("-t", "--tigger", dest="HostName", action="append_const", const="tigger", help="Entires for Tigger") trakt_auth_group.add_argument("-g", "--goofy", dest="HostName", action="append_const", const="goofy", help="Entries for Goofy") trakt_auth_group.add_argument("-e", "--eeyore", dest="HostName", action="append_const", const="eeyore", help="Entries for Eeore") trakt_auth_group.add_argument("-p", "--pluto", dest="HostName", action="append_const", const="pluto", help="Entries for Pluto") trakt_options_group = DadVision.cmdoptions.parser.add_argument_group( "Options", description=None) trakt_options_group.add_argument( "-c", "--clear", dest="Clear", nargs='*', action='store', default='None', help='Clear/Delete all entries in requested area: shows, movies') trakt_options_group.add_argument( "-l", "--list", dest="list", nargs='*', action='store', default='None', help='Clear/Delete all entries in requested area: shows, movies') tmdb3.set_key('587c13e576f991c0a653f783b290a065') tmdb3.set_cache(filename='tmdb3.cache') self.db = api.TVDB("959D8E76B796A1FB") #self.tmdbinfo = TMDBInfo() self._collectedShows = [] self._watchedShows = [] self._watchlistShows = [] self._trakt_sdtv = [] self._trakt_720P = [] self._trakt_list = [] self.errorLog = [] return
def main(argv): load_configuration() get_rss_movie_updates() exit() # debug.dbprint("this is sparta mofo : " + str(10), 1); offcloud_api.offcloud_init() # debug.dbprint("this is sparta mofo : " + str(10), 1); db = api.TVDB("B43FF87DE395DF56") db_directory = cwd + "/database/tvshows/" if len(argv) > 1: print "extra arguements provided" if argv[1] == 'add': # Adding new TV shows to download list get_new_show_input(db_directory) else: print "invalid arguement passed" file_list = [] for file in os.listdir(db_directory): if fnmatch.fnmatch(file, '*.json'): file_list.append(file) print file_list for show_file in file_list: show_data = json.load(open(db_directory + show_file)) show = db.get_series(show_data["imdb_id"], "en", id_type='imdb', cache=True) show.update() print '-------------------' + str( show.SeriesName) + ' ------------------------' for season in show: season_no = season.season_number - 1 if season.season_number == 0: continue print 'Season : ' + str(season.season_number) if (len(show_data['seasons']) < (season.season_number)): show_data['seasons'].append([]) for episode in season: print '\tEpisode : ' + str(episode.EpisodeNumber) episode_no = episode.EpisodeNumber - 1 today = (date.today()).toordinal() # print episode.FirstAired # print type(episode.FirstAired) if type(episode.FirstAired) != type(date.today()): ep_date = (datetime.strptime(episode.FirstAired, "%Y-%m-%d")).toordinal() else: ep_date = (episode.FirstAired).toordinal() # print "ep_date : "+(ep_date) # print "today : "+ (today) if ep_date < today - 1: # - 1 to download episodes that are atleast a day old. if (len(show_data['seasons'][season_no]) < (episode.EpisodeNumber)): show_data['seasons'][season_no].append({}) if show_data['seasons'][season_no][episode_no] == {}: episode_torrent = kat_search.get_tv_show_episode( show.SeriesName, season.season_number, episode.EpisodeNumber) cur_ep = { "season": season.season_number, "episode": episode.EpisodeNumber } if episode_torrent == None: if cur_ep not in show_data["erred_episodes"]: show_data["erred_episodes"].append(cur_ep) print "Adding to Errored episodes No torrent found" # show_data['seasons'][season_no][episode_no] = { 'magnet' : "", 'status' : "ERROR_no_magnet",'request_id' : 0, 'attempt' : 1} print("ERROR_no_magnet") else: show_data['seasons'][season_no][ episode_no] = start_episode_download( episode_torrent['magnet'], 0) if cur_ep in show_data["erred_episodes"]: show_data["erred_episodes"].remove(cur_ep) # print(show_data['seasons'][season_no][episode_no]["status"]) else: cur_episode = show_data['seasons'][season_no][ episode_no] if cur_episode['status'] == "Error_retry": if cur_episode["attempt"] <= 5: show_data['seasons'][season_no][ episode_no] = start_episode_download( cur_episode['magnet'], cur_episode["attempt"]) else: show_data['seasons'][season_no][episode_no] = { 'magnet': "", 'status': "ERROR_retry_failed", 'request_id': 0, 'attempt': 5 } else: #if (cur_episode['status']== "downloaded" ): # print "downloaded succesfully" #elif (cur_episode['status'] != "ERROR_no_magnet") and (cur_episode['status'] != "ERROR_retry_failed"): if (cur_episode['status'] != "ERROR_no_magnet" ) and (cur_episode['status'] != "ERROR_retry_failed"): off_cloud_status = offcloud_api.get_torrent_status( cur_episode['request_id']) print(off_cloud_status['status']) if off_cloud_status['status'][ 'status'] == "downloaded": show_data['seasons'][season_no][ episode_no][ 'status'] = off_cloud_status[ 'status']['status'] print "send the follwing data to a google sheet" print "title " + show_data['title'] print "season " + str(season.season_number) print "episode " + str( episode.EpisodeNumber) print "if possible rename the file for convenience" # write code to push the directory structure to google sheets that will be used to organize the files elif off_cloud_status['status'][ 'status'] == "error": show_data['seasons'][season_no][ episode_no]['status'] = "Error_retry" print "these downloads are in error state" #elif off_cloud_status['status']['status'] == "queued": else: break json.dump(show_data, open(db_directory + show_file, 'w')) print("writing updated data to disk") json.dump(show_data, open(db_directory + show_file, 'w'))
for word in words[1:]: final.append(word if word in exceptions else word.capitalize()) return ' '.join(final) # Declare global variables ARTICLES = ['a', 'an', 'of', 'the', 'is'] VIDEOTYPE = ['avi', 'mkv', 'mp4'] ILLEGAL = '<>:"/\|?*' FILEPATH = r"P:\TV Shows" # TheTVDB.com Username: hayntopdawg # TheTVDB.com API key: F35F04BF0C63B299 # TheTVDB.com Account Identifier: 1466EB44A268D300 api_key = 'F35F04BF0C63B299' DB = api.TVDB(api_key) if __name__ == '__main__': global BASEPATH show, season = get_input() title = title_except(show.SeriesName, ARTICLES) BASEPATH = os.path.join(FILEPATH, title, "Season {:02d}".format(int(season))) # print(path) navigate(BASEPATH, show, season) ### How it should work ### # User inputs title of tv show to have the folder organized # Checks to ensure tv show exists in "TV Show" folder # Searches for show on TVDB.com sets SeriesName to global variable # For each Season folder in Series's folder, organize and rename files
series = {} csvOutput = [] with open(os.path.join('.', 'shows.csv'), 'rb') as csvfile: listreader = csv.reader(csvfile, delimiter=',') count = 0 for row in listreader: series[row[0]] = defaultdict(dict) with open(os.path.join('config', 'api_key.txt'), 'r') as f: t = [] for line in f.readlines(): t.append(tuple(line[:-1].split(' = '))) token = dict(t) db = api.TVDB(token['api_key']) for a in sorted(series.keys()): print a for seriesName in sorted(series.keys()): print "Downloading " + seriesName # I'm sure TVDB can handle it, but just to be courteous... #time.sleep(1) # Go to next show if there's an error. try: result = db.search(seriesName, 'en') except (error.ConnectionError, error.TVDBNotFoundError, error.TVDBIndexError): series[seriesName]['name'] = seriesName + ' Lookup Error!'
import errno import subprocess import re from collections import defaultdict from classes import * from tendo import singleton from PyQt4 import QtCore, QtGui from pytvdbapi import api __version__ = "1.8-gui" me = singleton.SingleInstance() CONFIG_FILE = "{}/settings.cfg".format( os.path.dirname(os.path.abspath(__file__))) tvdb = api.TVDB('B43FF87DE395DF56') notify = None def threaded(fn): def wrapper(*args, **kwargs): guihelper.GenericThread(fn, args=args, kwargs=kwargs).start() return wrapper class AutoRippr(QtGui.QMainWindow, gui.Ui_MainWindow): def __init__(self, config, parent=None): QtGui.QMainWindow.__init__(self, parent) self.setupUi(self)
def get_episode_names(show_name, season_num): db = api.TVDB("B43FF87DE395DF56")
def tvdb(showid=''): today = date.today() dt_today = timezone.make_aware(datetime.combine(today, time.min)) dt0 = timezone.make_aware( datetime.combine(today - timedelta(days=2), time.min)) dt1 = timezone.make_aware( datetime.combine(today - timedelta(days=30), time.min)) dt3 = timezone.make_aware( datetime.combine(today - timedelta(days=500), time.min)) module_dir = os.path.dirname(__file__) # get current directory db = api.TVDB("D620620B2C727377", banners=True) if showid: series = {Series.objects.get(pk=showid)} else: series = Series.objects.filter(lastlookup__lt=dt0) for show in series: result = db.search(show.title, "en") tvdbshow = result[0] #['FirstAired', 'IMDB_ID', 'Network', 'Overview', 'SeriesName', 'actor_objects', 'api', 'banner', 'banner_objects', 'id', 'lang', 'language', 'seriesid', 'zap2it_id'] lastDue = timezone.make_aware( datetime.combine(tvdbshow.FirstAired, time.min)) lastEpi = '1x1' for tvdbseason in tvdbshow: #['season_number', 'show'] for tvdbepi in tvdbseason: #['Combined_episodenumber', 'Combined_season', 'DVD_chapter', 'DVD_discid', 'DVD_episodenumber', 'DVD_season', 'Director', 'EpImgFlag', 'EpisodeName', 'EpisodeNumber', 'FirstAired', 'GuestStars', 'IMDB_ID', 'Language', 'Overview', 'ProductionCode', 'Rating', 'RatingCount', 'SeasonNumber', 'Writer', 'absolute_number', 'filename', 'id', 'is_movie', 'lastupdated', 'season', 'seasonid', 'seriesid', 'thumb_added', 'thumb_height', 'thumb_width'] Episode.objects.filter( due__lte=dt3).delete() # delete old episodes try: AiredDT = timezone.make_aware( datetime.combine(tvdbepi.FirstAired, time.min)) except: AiredDT = None if AiredDT is not None and AiredDT > dt1: try: dupe = Episode.objects.get( season=tvdbepi.SeasonNumber, episode=tvdbepi.EpisodeNumber, serid=tvdbshow.id) except: dupe = None if dupe is None: print("Adding {0} S{1}E{2}, date {3}".format( tvdbshow.SeriesName, tvdbepi.SeasonNumber, tvdbepi.EpisodeNumber, tvdbepi.FirstAired)) new = Episode() new.title = tvdbshow.SeriesName new.season = tvdbepi.SeasonNumber new.episode = tvdbepi.EpisodeNumber new.date_added = dt_today new.due = AiredDT new.desc = tvdbepi.Overview new.serid = tvdbshow.id new.epiid = tvdbepi.id new.seaid = tvdbepi.seasonid new.series_id = show.id new.rssdate = dt_1000 new.downloaded = dt_1000 new.save() elif dupe.due != AiredDT: print("Updating {0} S{1}E{2}, date {3}".format( tvdbshow.SeriesName, tvdbepi.SeasonNumber, tvdbepi.EpisodeNumber, tvdbepi.FirstAired)) dupe.date_added = dt_today dupe.due = AiredDT dupe.desc = tvdbepi.Overview dupe.serid = tvdbshow.id dupe.epiid = tvdbepi.id dupe.seaid = tvdbepi.seasonid dupe.series_id = show.id if dupe.rssdate is None: dupe.rssdate = dt_1000 if dupe.downloaded is None: dupe.downloaded = dt_1000 dupe.save() if AiredDT is not None: lastDue = AiredDT lastEpi = str(tvdbepi.SeasonNumber) + 'x' + str( tvdbepi.EpisodeNumber) show.lastlookup = dt_today show.tvdbid = tvdbshow.id show.overview = tvdbshow.Overview #show.period=tvdbshow.FirstAired.strftime('%b') show.firstaired = timezone.make_aware( datetime.combine(tvdbshow.FirstAired, time.min)) show.lastdue = timezone.make_aware(datetime.combine(lastDue, time.min)) show.lastepi = lastEpi show.imdb = tvdbshow.IMDB_ID show.save() # fanart - these require collectstatic. TODO: change to use media folder! file_path = os.path.join( module_dir, os.path.normpath('static/shows/img/fart/{0}.jpg').format( tvdbshow.id)) if os.path.isfile(file_path) == False: try: filemessage = 'Getting Fan Art File: ' + file_path urllib.request.urlretrieve( "http://www.thetvdb.com/banners/fanart/original/{0}-1.jpg". format(tvdbshow.id), file_path) except: filemessage = None if filemessage is not None: print(filemessage) # banner file_path = os.path.join( module_dir, os.path.normpath('static/shows/img/bart/{0}.jpg').format( tvdbshow.id)) if os.path.isfile(file_path) == False: try: filemessage = 'Getting Banner File: ' + file_path urllib.request.urlretrieve( "http://www.thetvdb.com/banners/{0}".format( tvdbshow.banner), file_path) except: filemessage = None if filemessage is not None: print(filemessage)
def __init__(self): super(SyncLibrary, self).__init__() sync1 = self.options.parser.add_argument_group("HostsNames", description=None) sync1.add_argument("-t", "--tigger", dest="hostname", default='', action="store_const", const="tigger", help="Sync Tigger for Aly") sync1.add_argument("-g", "--goofy", dest="hostname", action="store_const", const="goofy", help="Sync Goofy for Kim") sync1.add_argument("-p", "--pooh", dest="hostname", action="store_const", const="pooh", help="Sync Pooh for Michelle") sync1.add_argument("-l", "--pluto", dest="hostname", action="store_const", const="pluto", help="Sync Pluto for Ben and Mac") sync2 = self.options.parser.add_argument_group("Media Type", description=None) sync2.add_argument("-s", "--series", dest="content", action="append_const", const="Series", help="Process Series") sync2.add_argument("-m", "--movies", dest="content", action="append_const", const="Movies", help="Process Movies") sync3 = self.options.parser.add_argument_group("Modifiers", description=None) sync3.add_argument("--checksum", dest="chksum", action="store_true", default=False, help="Use Checksum not Date and Time") sync3.add_argument( "--delete", dest="delete", action="store_true", default=False, help="Delete any files on rmt that do not exist on local") sync3.add_argument("-n", "--dry-run", dest="dryrun", action="store_true", default=False, help="Don't Run Link Create Commands") sync3.add_argument("--ignore-existing", dest='ignore_existing', action="store_true", default=False, help="Skip updating files that exist on receiver") sync3.add_argument("--no-update", dest="no_update", action="store_true", default=False, help="Don't update database info on downloads") sync3.add_argument( "--no-video", dest="novideo", action="store_true", default=False, help="Suppress Video Files, Only Move Support Files/Directories") sync3.add_argument( "--refresh", dest="refresh_limit", action="store", type=int, default=14400, help= 'Refresh existing links if older x seconds, Default: 14400 (4 hours)' ) sync3.add_argument( "--no-reuse", dest="no_reuse", action="store_true", default=False, help='Do not reuse existing links, even if possible') sync3.add_argument( "--reverse", dest="reverse", action="store_true", default=False, help= "Reverse flow of Update, RMT --> Local, --ignore-existing, --rsync, --update implied" ) sync3.add_argument("--rsync", dest="rsync", action="store_true", default=False, help='Bypass database and run full download') sync3.add_argument("-u", "--update", dest="update", action="store_true", default=False, help="Skip files that are newer on the receiver") sync3.add_argument("-x", "--exclude", dest="xclude", action="append", default=[], help="Exclude files/directories") sync4 = self.options.parser.add_argument_group( "syncRMT Already Running") sync4.add_argument("-c", "--cancel", dest="runaction", action="store_const", const='cancel', default='ask', help="Cancel this request and let existing run") sync4.add_argument("-r", "--restart", dest="runaction", action="store_const", const='restart', help="Stop existing and Restart with this request") self.db = api.TVDB("959D8E76B796A1FB") self.tmdb_info = TMDBInfo() self._printfmt = '%P\n' return
#Build list 'files' of all video files to be handled for root, directories, filenames in os.walk(videoRoot): for filename in filenames: for type in videoTypes: if filename.lower().endswith(type): files.append(os.path.join(root, filename)) continue #If not recursive, skip others if not runRecursive: break if not (runSilent): print("%d video files found for processing." % (len(files))) tvdb = api.TVDB('A0857036BEACEE1A') # tvdb = api.TVDB('9E8E50DD-AF0C-45D5-BDC4-2A4BFEBEA36D'); namePairs = {} if os.path.exists('namePairs.cfg'): namePairsF = open('namePairs.cfg', 'rb') namePairs = pickle.load(namePairsF) # Drop requested shows for show in dropShows: showName = cleanShowName(show) if showName in namePairs: print("Confirm that show '%s' should be dropped." % (show)) option = input("Confirm [Y/N]: ").strip().lower() if option == 'y': del namePairs[showName]