desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'For a given file path searches for files with the same name but different extension and returns their absolute paths :param file_path: The file to check for associated files :return: A list containing all files which are associated to the given file'
def list_associated_files(self, file_path, subtitles_only=False, subfolders=False, rename=False):
def recursive_glob(treeroot, pattern): results = [] for (base, dirnames_, files) in ek(os.walk, treeroot.encode(sickbeard.SYS_ENCODING), followlinks=sickbeard.PROCESSOR_FOLLOW_SYMLINKS): goodfiles = fnmatch.filter(files, pattern) for f in goodfiles: found_file...
'Deletes the file and optionally all associated files. :param file_path: The file to delete :param associated_files: True to delete all files which differ only by extension, False to leave them'
def _delete(self, file_path, associated_files=False):
if (not file_path): return if (not isinstance(file_path, list)): file_list = [file_path] else: file_list = file_path if associated_files: file_list = (file_list + self.list_associated_files(file_path, subfolders=True)) if (not file_list): self._log(((u'There ...
'Performs a generic operation (move or copy) on a file. Can rename the file as well as change its location, and optionally move associated files too. :param file_path: The full path of the media file to act on :param new_path: Destination path where we want to move/copy the file to :param new_base_name: The base filena...
def _combined_file_operation(self, file_path, new_path, new_base_name, associated_files=False, action=None, subtitles=False):
if (not action): self._log(u'Must provide an action for the combined file operation', logger.ERROR) return file_list = [file_path] subfolders = (ek(os.path.normpath, ek(os.path.dirname, file_path)) != ek(os.path.normpath, sickbeard.TV_DOWNLOAD_DIR)) if associated_...
'Move file and set proper permissions :param file_path: The full path of the media file to move :param new_path: Destination path where we want to move the file to :param new_base_name: The base filename (no extension) to use during the move. Use None to keep the same name. :param associated_files: Boolean, whether we ...
def _move(self, file_path, new_path, new_base_name, associated_files=False, subtitles=False):
def _int_move(cur_file_path, new_file_path): self._log((((u'Moving file from ' + cur_file_path) + u' to ') + new_file_path), logger.DEBUG) try: helpers.moveFile(cur_file_path, new_file_path) helpers.chmodAsParent(new_file_path) except (IOError, OSError)...
'Copy file and set proper permissions :param file_path: The full path of the media file to copy :param new_path: Destination path where we want to copy the file to :param new_base_name: The base filename (no extension) to use during the copy. Use None to keep the same name. :param associated_files: Boolean, whether we ...
def _copy(self, file_path, new_path, new_base_name, associated_files=False, subtitles=False):
def _int_copy(cur_file_path, new_file_path): self._log((((u'Copying file from ' + cur_file_path) + u' to ') + new_file_path), logger.DEBUG) try: helpers.copyFile(cur_file_path, new_file_path) helpers.chmodAsParent(new_file_path) except (IOError, OSError...
'Hardlink file and set proper permissions :param file_path: The full path of the media file to move :param new_path: Destination path where we want to create a hard linked file :param new_base_name: The base filename (no extension) to use during the link. Use None to keep the same name. :param associated_files: Boolean...
def _hardlink(self, file_path, new_path, new_base_name, associated_files=False, subtitles=False):
def _int_hard_link(cur_file_path, new_file_path): self._log((((u'Hard linking file from ' + cur_file_path) + u' to ') + new_file_path), logger.DEBUG) try: helpers.hardlinkFile(cur_file_path, new_file_path) helpers.chmodAsParent(new_file_path) except ...
'Move file, symlink source location back to destination, and set proper permissions :param file_path: The full path of the media file to move :param new_path: Destination path where we want to move the file to create a symbolic link to :param new_base_name: The base filename (no extension) to use during the link. Use N...
def _moveAndSymlink(self, file_path, new_path, new_base_name, associated_files=False, subtitles=False):
def _int_move_and_sym_link(cur_file_path, new_file_path): self._log((((u'Moving then symbolic linking file from ' + cur_file_path) + u' to ') + new_file_path), logger.DEBUG) try: helpers.moveAndSymlinkFile(cur_file_path, new_file_path) helpers.chmodAsP...
'symlink destination to source location, and set proper permissions :param file_path: The full path of the media file to move :param new_path: Destination path where we want to move the file to create a symbolic link to :param new_base_name: The base filename (no extension) to use during the link. Use None to keep the ...
def _symlink(self, file_path, new_path, new_base_name, associated_files=False, subtitles=False):
def _int_sym_link(cur_file_path, new_file_path): self._log((((u'Creating then symbolic linking file from ' + new_file_path) + u' to ') + cur_file_path), logger.DEBUG) try: helpers.symlink(cur_file_path, new_file_path) helpers.chmodAsParent(cur_file_pat...
'Look up the NZB name in the history and see if it contains a record for self.nzb_name :return: A (indexer_id, season, [], quality, version) tuple. The first two may be None if none were found.'
def _history_lookup(self):
to_return = (None, None, [], None, None) if ((not self.nzb_name) and (not self.folder_name)): self.in_history = False return to_return names = [] if self.nzb_name: names.append(self.nzb_name) if (u'.' in self.nzb_name): names.append(self.nzb_name.rpartition(u'...
'Store parse result if it is complete and final :param parse_result: Result of parsers'
def _finalize(self, parse_result):
self.release_group = parse_result.release_group if parse_result.extra_info: self.is_proper = (re.search(u'\\b(proper|repack|real)\\b', parse_result.extra_info, re.I) is not None) if (parse_result.series_name and (((parse_result.season_number is not None) and parse_result.episode_numbers) or parse_re...
'Takes a name and tries to figure out a show, season, and episode from it. :param name: A string which we want to analyze to determine show info from (six.text_type) :return: A (indexer_id, season, [episodes]) tuple. The first two may be None and episodes may be [] if none were found.'
def _analyze_name(self, name):
to_return = (None, None, [], None, None) if (not name): return to_return logger.log((u'Analyzing name ' + name), logger.DEBUG) name = helpers.remove_non_release_groups(remove_extension(name)) try: parse_result = NameParser(True, tryIndexers=True).parse(name) except (Invalid...
'Look up anidb properties for an episode :param connection: anidb connection handler :param filePath: file to check :return: episode object'
@staticmethod def _build_anidb_episode(connection, filePath):
ep = adba.Episode(connection, filePath=filePath, paramsF=[u'quality', u'anidb_file_name', u'crc32'], paramsA=[u'epno', u'english_name', u'short_name_list', u'other_name', u'synonym_list']) return ep
'Adds an episode to anidb mylist :param filePath: file to add to mylist'
def _add_to_anidb_mylist(self, filePath):
if helpers.set_up_anidb_connection(): if (not self.anidbEpisode): self.anidbEpisode = self._build_anidb_episode(sickbeard.ADBA_CONNECTION, filePath) self._log(u'Adding the file to the anidb mylist', logger.DEBUG) try: self.anidbEpisode.add_to_mylist(...
'For a given file try to find the showid, season, and episode. :return: A (show, season, episodes, quality, version) tuple'
def _find_info(self):
show = season = quality = version = None episodes = [] attempt_list = [self._history_lookup, (lambda : self._analyze_name(self.nzb_name)), (lambda : self._analyze_name(self.file_name)), (lambda : self._analyze_name(self.folder_name)), (lambda : self._analyze_name(self.file_path)), (lambda : self._analyze_na...
'Retrieve the TVEpisode object requested. :param show: The show object belonging to the show we want to process :param season: The season of the episode (int) :param episodes: A list of episodes to find (list of ints) :return: If the episode(s) can be found then a TVEpisode object with the correct related eps will be i...
def _get_ep_obj(self, show, season, episodes):
root_ep = None for cur_episode in episodes: self._log((((u'Retrieving episode object for ' + str(season)) + u'x') + str(cur_episode)), logger.DEBUG) try: curEp = show.getEpisode(season, cur_episode) if (not curEp): raise EpisodeNotFoundExceptio...
'Determines the quality of the file that is being post processed, first by checking if it is directly available in the TVEpisode\'s status or otherwise by parsing through the data available. :param ep_obj: The TVEpisode object related to the file we are post processing :return: A quality value found in common.Quality'
def _get_quality(self, ep_obj):
if (ep_obj.status in ((common.Quality.SNATCHED + common.Quality.SNATCHED_PROPER) + common.Quality.SNATCHED_BEST)): (ep_status_, ep_quality) = common.Quality.splitCompositeStatus(ep_obj.status) if (ep_quality != common.Quality.UNKNOWN): self._log((u'The old status had a qua...
'Executes any extra scripts defined in the config. :param ep_obj: The object to use when calling the extra script'
def _run_extra_scripts(self, ep_obj):
if (not sickbeard.EXTRA_SCRIPTS): return file_path = self.file_path if isinstance(file_path, six.text_type): try: file_path = file_path.encode(sickbeard.SYS_ENCODING) except UnicodeEncodeError: pass ep_location = ep_obj.location if isinstance(ep_locati...
'Determines if the episode is a priority download or not (if it is expected). Episodes which are expected (snatched) or larger than the existing episode are priority, others are not. :param ep_obj: The TVEpisode object in question :param new_ep_quality: The quality of the episode that is being processed :return: True i...
def _is_priority(self, ep_obj, new_ep_quality):
if self.is_priority: return True (old_ep_status_, old_ep_quality) = common.Quality.splitCompositeStatus(ep_obj.status) if (self.in_history or (ep_obj.status in ((common.Quality.SNATCHED + common.Quality.SNATCHED_PROPER) + common.Quality.SNATCHED_BEST))): if (not self.in_history): ...
'Post-process a given file :return: True on success, False on failure'
def process(self):
self._log(((((u'Processing ' + self.file_path) + u' (') + str(self.nzb_name)) + u')')) if ek(os.path.isdir, self.file_path): self._log(u'File {0} seems to be a directory'.format(self.file_path)) return False if (not ek(os.path.exists, self.file_path)): self._l...
'Gets a list of most popular TV series from imdb'
def __init__(self):
self.url = u'http://akas.imdb.com/search/title' self.params = {u'at': 0, u'sort': u'moviemeter', u'title_type': u'tv_series', u'year': u'{0},{1}'.format((date.today().year - 1), (date.today().year + 1))} self.session = helpers.make_session()
'Get popular show information from IMDB'
def fetch_popular_shows(self):
popular_shows = [] data = helpers.getURL(self.url, session=self.session, params=self.params, headers={u'Referer': u'http://akas.imdb.com/'}, returns=u'text') if (not data): return None soup = BeautifulSoup(data, u'html5lib') results = soup.find_all(u'div', {u'class': u'lister-item'}) for...
'Store cache of image in cache dir :param image_url: Source URL'
def cache_image(self, image_url):
path = ek(os.path.abspath, ek(os.path.join, sickbeard.CACHE_DIR, u'images', u'imdb_popular')) if (not ek(os.path.exists, path)): ek(os.makedirs, path) full_path = ek(os.path.join, path, ek(os.path.basename, image_url)) if (not ek(os.path.isfile, full_path)): helpers.download_file(image_u...
'Runs the postprocessor :param force: Forces postprocessing run :return: Returns when done without a return state/code'
def run(self, force=False):
self.amActive = True sickbeard.postProcessorTaskScheduler.action.add_item(sickbeard.TV_DOWNLOAD_DIR, force=force) self.amActive = False
'Sends a redirect to the given (optionally relative) URL. ----->>>>> NOTE: Removed self.finish <<<<<----- If the ``status`` argument is specified, that value is used as the HTTP status code; otherwise either 301 (permanent) or 302 (temporary) is chosen based on the ``permanent`` argument. The default is 302 (temporary)...
def redirect(self, url, permanent=False, status=None):
from tornado.escape import utf8 if (not url.startswith(sickbeard.WEB_ROOT)): url = (sickbeard.WEB_ROOT + url) if self._headers_written: raise Exception(u'Cannot redirect after headers have been written') if (not status): status = (301 if permanent else 302) ...
'Keep web crawlers out'
def robots_txt(self):
self.set_header(u'Content-Type', u'text/plain') return u'User-agent: *\nDisallow: /'
'Provides a subscribeable URL for iCal subscriptions'
def calendar(self):
logger.log(u'Receiving iCal request from {0}'.format(self.request.remote_ip)) ical = u'BEGIN:VCALENDAR\r\n' ical += u'VERSION:2.0\r\n' ical += u'X-WR-CALNAME:SickRage\r\n' ical += u'X-WR-CALDESC:SickRage\r\n' ical += u'PRODID://Sick-Beard Upcoming Episodes//\r\n' future_wee...
'Get /locale/{lang_code}/LC_MESSAGES/messages.json'
def locale_json(self):
locale_file = ek(os.path.normpath, u'{locale_dir}/{lang}/LC_MESSAGES/messages.json'.format(locale_dir=sickbeard.LOCALE_DIR, lang=sickbeard.GUI_LANG)) if os.path.isfile(locale_file): self.set_header(u'Content-Type', u'application/json') with open(locale_file, u'r') as content: return ...
'Loads show and episode statistics from db'
@staticmethod def show_statistics():
main_db_con = db.DBConnection() today = str(datetime.date.today().toordinal()) status_quality = ((u'(' + u','.join([str(x) for x in ((Quality.SNATCHED + Quality.SNATCHED_PROPER) + Quality.SNATCHED_BEST)])) + u')') status_download = ((u'(' + u','.join([str(x) for x in (Quality.DOWNLOADED + Quality.ARCHIV...
'Display the new show page which collects a tvdb id, folder, and extra options and posts them to addNewShow'
def newShow(self, show_to_add=None, other_shows=None, search_string=None):
t = PageTemplate(rh=self, filename=u'addShows_newShow.mako') (indexer, show_dir, indexer_id, show_name) = self.split_extra_show(show_to_add) if (indexer_id and indexer and show_name): use_provided_info = True else: use_provided_info = False if (not show_dir): if search_string...
'Display the new show page which collects a tvdb id, folder, and extra options and posts them to addNewShow'
def trendingShows(self, traktList=None):
if (not traktList): traktList = u'' traktList = traktList.lower() if (traktList == u'trending'): page_title = _(u'Trending Shows') elif (traktList == u'popular'): page_title = _(u'Popular Shows') elif (traktList == u'anticipated'): page_title = _(u'Most Antic...
'Display the new show page which collects a tvdb id, folder, and extra options and posts them to addNewShow'
def getTrendingShows(self, traktList=None):
t = PageTemplate(rh=self, filename=u'trendingShows.mako') if (not traktList): traktList = u'' traktList = traktList.lower() if (traktList == u'trending'): page_url = u'shows/trending' elif (traktList == u'popular'): page_url = u'shows/popular' elif (traktList == u'anticip...
'Fetches data from IMDB to show a list of popular shows.'
def popularShows(self):
t = PageTemplate(rh=self, filename=u'addShows_popularShows.mako') e = None try: popular_shows = imdb_popular.fetch_popular_shows() except Exception as e: logger.log(u'Could not get popular shows: {0}'.format(ex(e)), logger.WARNING) popular_shows = None return t...
'Prints out the page to add existing shows from a root dir'
def existingShows(self):
t = PageTemplate(rh=self, filename=u'addShows_addExistingShow.mako') return t.render(enable_anime_options=False, title=_(u'Existing Show'), header=_(u'Existing Show'), topmenu=u'home', controller=u'addShows', action=u'addExistingShow')
'Receive tvdb id, dir, and other options and create a show from them. If extra show dirs are provided then it forwards back to newShow, if not it goes to /home.'
def addNewShow(self, whichSeries=None, indexerLang=None, rootDir=None, defaultStatus=None, quality_preset=None, anyQualities=None, bestQualities=None, season_folders=None, subtitles=None, subtitles_sr_metadata=None, fullShowPath=None, other_shows=None, skipShow=None, providedIndexer=None, anime=None, scene=None, blackl...
if (not indexerLang): indexerLang = sickbeard.INDEXER_DEFAULT_LANGUAGE if (not other_shows): other_shows = [] elif (not isinstance(other_shows, list)): other_shows = [other_shows] def finishAddShow(): if (not other_shows): return self.redirect(u'/home/') ...
'Receives a dir list and add them. Adds the ones with given TVDB IDs first, then forwards along to the newShow page.'
def addExistingShows(self, shows_to_add, promptForSettings, **kwargs):
if (not shows_to_add): shows_to_add = [] elif (not isinstance(shows_to_add, list)): shows_to_add = [shows_to_add] shows_to_add = [unquote_plus(x) for x in shows_to_add] indexer_id_given = [] dirs_only = [] for cur_dir in shows_to_add: if (u'|' in cur_dir): spl...
'Test Unpacking Support: - checks if unrar is installed and accesible'
@staticmethod def isRarSupported():
check = config.change_unrar_tool(sickbeard.UNRAR_TOOL, sickbeard.ALT_UNRAR_TOOL) if (not check): logger.log(u'Looks like unrar is not installed, check failed', logger.WARNING) return (u'not supported', u'supported')[check]
'Retrieves a list of possible categories with category id\'s Using the default url/api?cat http://yournewznaburl.com/api?t=caps&apikey=yourapikey'
@staticmethod def getNewznabCategories(name, url, key):
error = u'' success = False if (not name): error += (u'\n' + _(u'No Provider Name specified')) if (not url): error += (u'\n' + _(u'No Provider Url specified')) if (not key): error += (u'\n' + _(u'No Provider Api key specified')) if error: ...
'Determines how this copy of sr was installed. returns: type of installation. Possible values are: \'win\': any compiled windows build \'git\': running from source using git \'source\': running from source without git'
@staticmethod def find_install_type():
if sickbeard.BRANCH.startswith(u'build '): install_type = u'win' elif ek(os.path.isdir, ek(os.path.join, sickbeard.PROG_DIR, u'.git')): install_type = u'git' else: install_type = u'source' return install_type
'Checks the internet for a newer version. returns: bool, True for new version or False for no new version. force: if true the VERSION_NOTIFY setting will be ignored and a check will be forced'
def check_for_new_version(self, force=False):
if ((not self.updater) or ((not sickbeard.VERSION_NOTIFY) and (not sickbeard.AUTO_UPDATE) and (not force))): logger.log(u'Version checking is disabled, not checking for the newest version') return False if (not sickbeard.AUTO_UPDATE): logger.log((u'Checking ...
'Checks GitHub for the latest news. returns: six.text_type, a copy of the news force: ignored'
def check_for_new_news(self):
logger.log(u'check_for_new_news: Checking GitHub for latest news.', logger.DEBUG) try: news = helpers.getURL(sickbeard.NEWS_URL, session=self.session, returns=u'text') except Exception: logger.log(u'check_for_new_news: Could not load news from repo.', logger....
'Attempts to find the currently installed version of SickRage. Uses git show to get commit version. Returns: True for success or False for failure'
def _find_installed_version(self):
(output, errors_, exit_status) = self._run_git(self._git_path, u'rev-parse HEAD') if ((exit_status == 0) and output): cur_commit_hash = output.strip() if (not re.match(u'^[a-z0-9]+$', cur_commit_hash)): logger.log(u"Output doesn't look like a hash, not using ...
'Uses git commands to check if there is a newer version that the provided commit hash. If there is a newer version it sets _num_commits_behind.'
def _check_github_for_update(self):
self._num_commits_behind = 0 self._num_commits_ahead = 0 self.update_remote_origin() (output, errors_, exit_status) = self._run_git(self._git_path, u'fetch {0}'.format(sickbeard.GIT_REMOTE)) if (exit_status != 0): logger.log(u"Unable to contact github, can't check for ...
'Calls git pull origin <branch> in order to update SickRage. Returns a bool depending on the call\'s success.'
def update(self):
self.update_remote_origin() if sickbeard.GIT_RESET: self.reset() if (self.branch == self._find_installed_branch()): (stdout_, stderr_, exit_status) = self._run_git(self._git_path, u'pull -f {0} {1}'.format(sickbeard.GIT_REMOTE, self.branch)) else: (stdout_, stderr_, exit...
'Calls git clean to remove all untracked files. Returns a bool depending on the call\'s success.'
def clean(self):
(stdout_, stderr_, exit_status) = self._run_git(self._git_path, u'clean -df ""') if (exit_status == 0): return True
'Calls git reset --hard to perform a hard reset. Returns a bool depending on the call\'s success.'
def reset(self):
(stdout_, stderr_, exit_status) = self._run_git(self._git_path, u'reset --hard') if (exit_status == 0): return True
'Uses pygithub to ask github if there is a newer version that the provided commit hash. If there is a newer version it sets SickRage\'s version text. commit_hash: hash that we\'re checking against'
def _check_github_for_update(self):
self._num_commits_behind = 0 self._newest_commit_hash = None repo = sickbeard.gh.get_organization(sickbeard.GIT_ORG).get_repo(sickbeard.GIT_REPO) if self._cur_commit_hash: try: branch_compared = repo.compare(base=self.branch, head=self._cur_commit_hash) self._newest_commi...
'Downloads the latest source tarball from github and installs it over the existing version.'
def update(self):
tar_download_url = (((((u'http://github.com/' + sickbeard.GIT_ORG) + u'/') + sickbeard.GIT_REPO) + u'/tarball/') + self.branch) try: sr_update_dir = ek(os.path.join, sickbeard.PROG_DIR, u'sr-update') if ek(os.path.isdir, sr_update_dir): logger.log(((u'Clearing out update fol...
'Builds up the full path to the image cache directory'
@staticmethod def _cache_dir():
return ek(os.path.abspath, ek(os.path.join, sickbeard.CACHE_DIR, u'images'))
'Builds up the full path to the thumbnails image cache directory'
def _thumbnails_dir(self):
return ek(os.path.abspath, ek(os.path.join, self._cache_dir(), u'thumbnails'))
'Builds up the path to a poster cache for a given Indexer ID :param indexer_id: ID of the show to use in the file name :return: a full path to the cached poster file for the given Indexer ID'
def poster_path(self, indexer_id):
poster_file_name = (str(indexer_id) + u'.poster.jpg') return ek(os.path.join, self._cache_dir(), poster_file_name)
'Builds up the path to a banner cache for a given Indexer ID :param indexer_id: ID of the show to use in the file name :return: a full path to the cached banner file for the given Indexer ID'
def banner_path(self, indexer_id):
banner_file_name = (str(indexer_id) + u'.banner.jpg') return ek(os.path.join, self._cache_dir(), banner_file_name)
'Builds up the path to a fanart cache for a given Indexer ID :param indexer_id: ID of the show to use in the file name :return: a full path to the cached fanart file for the given Indexer ID'
def fanart_path(self, indexer_id):
fanart_file_name = (str(indexer_id) + u'.fanart.jpg') return ek(os.path.join, self._cache_dir(), fanart_file_name)
'Builds up the path to a poster thumb cache for a given Indexer ID :param indexer_id: ID of the show to use in the file name :return: a full path to the cached poster thumb file for the given Indexer ID'
def poster_thumb_path(self, indexer_id):
posterthumb_file_name = (str(indexer_id) + u'.poster.jpg') return ek(os.path.join, self._thumbnails_dir(), posterthumb_file_name)
'Builds up the path to a banner thumb cache for a given Indexer ID :param indexer_id: ID of the show to use in the file name :return: a full path to the cached banner thumb file for the given Indexer ID'
def banner_thumb_path(self, indexer_id):
bannerthumb_file_name = (str(indexer_id) + u'.banner.jpg') return ek(os.path.join, self._thumbnails_dir(), bannerthumb_file_name)
'Returns true if a cached poster exists for the given Indexer ID'
def has_poster(self, indexer_id):
poster_path = self.poster_path(indexer_id) logger.log(((u'Checking if file ' + str(poster_path)) + u' exists'), logger.DEBUG) return ek(os.path.isfile, poster_path)
'Returns true if a cached banner exists for the given Indexer ID'
def has_banner(self, indexer_id):
banner_path = self.banner_path(indexer_id) logger.log(((u'Checking if file ' + str(banner_path)) + u' exists'), logger.DEBUG) return ek(os.path.isfile, banner_path)
'Returns true if a cached fanart exists for the given Indexer ID'
def has_fanart(self, indexer_id):
fanart_path = self.fanart_path(indexer_id) logger.log(((u'Checking if file ' + str(fanart_path)) + u' exists'), logger.DEBUG) return ek(os.path.isfile, fanart_path)
'Returns true if a cached poster thumbnail exists for the given Indexer ID'
def has_poster_thumbnail(self, indexer_id):
poster_thumb_path = self.poster_thumb_path(indexer_id) logger.log(((u'Checking if file ' + str(poster_thumb_path)) + u' exists'), logger.DEBUG) return ek(os.path.isfile, poster_thumb_path)
'Returns true if a cached banner exists for the given Indexer ID'
def has_banner_thumbnail(self, indexer_id):
banner_thumb_path = self.banner_thumb_path(indexer_id) logger.log(((u'Checking if file ' + str(banner_thumb_path)) + u' exists'), logger.DEBUG) return ek(os.path.isfile, banner_thumb_path)
'Analyzes the image provided and attempts to determine whether it is a poster or banner. :param path: full path to the image :return: BANNER, POSTER if it concluded one or the other, or None if the image was neither (or didn\'t exist)'
def which_type(self, path):
if (not ek(os.path.isfile, path)): logger.log(((u"Couldn't check the type of " + str(path)) + u" cause it doesn't exist"), logger.WARNING) return None img_parser = createParser(path) img_metadata = extractMetadata(img_parser) if (not img_metadata): logg...
'Takes the image provided and copies it to the cache folder :param image_path: path to the image we\'re caching :param img_type: BANNER or POSTER or FANART :param indexer_id: id of the show this image belongs to :return: bool representing success'
def _cache_image_from_file(self, image_path, img_type, indexer_id):
if (img_type == self.POSTER): dest_path = self.poster_path(indexer_id) elif (img_type == self.BANNER): dest_path = self.banner_path(indexer_id) elif (img_type == self.FANART): dest_path = self.fanart_path(indexer_id) else: logger.log((u'Invalid cache image type: ...
'Retrieves an image of the type specified from indexer and saves it to the cache folder :param show_obj: TVShow object that we want to cache an image for :param img_type: BANNER or POSTER or FANART :return: bool representing success'
def _cache_image_from_indexer(self, show_obj, img_type):
if (img_type == self.POSTER): img_type_name = u'poster' dest_path = self.poster_path(show_obj.indexerid) elif (img_type == self.BANNER): img_type_name = u'banner' dest_path = self.banner_path(show_obj.indexerid) elif (img_type == self.POSTER_THUMB): img_type_name = u'...
'Caches all images for the given show. Copies them from the show dir if possible, or downloads them from indexer if they aren\'t in the show dir. :param show_obj: TVShow object to cache images for'
def fill_cache(self, show_obj):
logger.log((u'Checking if we need any cache images for show ' + str(show_obj.indexerid)), logger.DEBUG) need_images = {self.POSTER: (not self.has_poster(show_obj.indexerid)), self.BANNER: (not self.has_banner(show_obj.indexerid)), self.POSTER_THUMB: (not self.has_poster_thumbnail(show...
'Runs the daily searcher, queuing selected episodes for search :param force: Force search'
def run(self, force=False):
if self.amActive: return self.amActive = True _ = force logger.log(u'Searching for new released episodes ...') if (not network_timezones.network_dict): network_timezones.update_network_dict() if network_timezones.network_dict: curDate = (datetime.date.today...
'Find out if show is anime :return: True if show is anime, False if not'
@property def is_anime(self):
return (self.anime > 0)
'Find out if show is sports :return: True if show is sports, False if not'
@property def is_sports(self):
return (self.sports > 0)
'Find out if show is scene numbering :return: True if show is scene numbering, False if not'
@property def is_scene(self):
return (self.scene > 0)
'Returns the path where the episode thumbnail should be stored. Defaults to the same path as the episode file but with a .cover.jpg extension. ep_obj: a TVEpisode instance for which to create the thumbnail'
@staticmethod def get_episode_thumb_path(ep_obj):
if ek(os.path.isfile, ep_obj.location): tbn_filename = (ep_obj.location + u'.cover.jpg') else: return None return tbn_filename
'Returns a full show dir/.meta/episode.txt path for Tivo episode metadata files. Note, that pyTivo requires the metadata filename to include the original extention. ie If the episode name is foo.avi, the metadata name is foo.avi.txt ep_obj: a TVEpisode object to get the path for'
def get_episode_file_path(self, ep_obj):
if ek(os.path.isfile, ep_obj.location): metadata_file_name = ((ek(os.path.basename, ep_obj.location) + u'.') + self._ep_nfo_extension) metadata_dir_name = ek(os.path.join, ek(os.path.dirname, ep_obj.location), u'.meta') metadata_file_path = ek(os.path.join, metadata_dir_name, metadata_file_n...
'Creates a key value structure for a Tivo episode metadata file and returns the resulting data object. ep_obj: a TVEpisode instance to create the metadata file for. Lookup the show in http://thetvdb.com/ using the python library: https://github.com/dbr/indexer_api/ The results are saved in the object myShow. The key va...
def _ep_data(self, ep_obj):
data = u'' eps_to_write = ([ep_obj] + ep_obj.relatedEps) indexer_lang = ep_obj.show.lang try: lINDEXER_API_PARMS = sickbeard.indexerApi(ep_obj.show.indexer).api_params.copy() lINDEXER_API_PARMS[u'actors'] = True lINDEXER_API_PARMS[u'language'] = (indexer_lang or sickbeard.INDEXER...
'Generates and writes ep_obj\'s metadata under the given path with the given filename root. Uses the episode\'s name with the extension in _ep_nfo_extension. ep_obj: TVEpisode object for which to create the metadata file_name_path: The file name to use for this metadata. Note that the extension will be automatically ad...
def write_ep_file(self, ep_obj):
data = self._ep_data(ep_obj) if (not data): return False nfo_file_path = self.get_episode_file_path(ep_obj) nfo_file_dir = ek(os.path.dirname, nfo_file_path) try: if (not ek(os.path.isdir, nfo_file_dir)): logger.log((u"Metadata dir didn't exist, creating it...
'Returns the path where the episode thumbnail should be stored. ep_obj: a TVEpisode instance for which to create the thumbnail'
@staticmethod def get_episode_thumb_path(ep_obj):
assert isinstance(ep_obj.location, six.text_type) if ek(os.path.isfile, ep_obj.location): tbn_filename = ep_obj.location.rpartition(u'.') if (tbn_filename[0] == u''): tbn_filename = (ep_obj.location + u'-thumb.jpg') else: tbn_filename = (tbn_filename[0] + u'-thumb...
'Returns the full path to the file for a given season poster. show_obj: a TVShow instance for which to generate the path season: a season number to be used for the path. Note that season 0 means specials.'
@staticmethod def get_season_poster_path(show_obj, season):
if (season == 0): season_poster_filename = u'season-specials' else: season_poster_filename = (u'season' + str(season).zfill(2)) return ek(os.path.join, show_obj.location, (season_poster_filename + u'-poster.jpg'))
'Returns the full path to the file for a given season banner. show_obj: a TVShow instance for which to generate the path season: a season number to be used for the path. Note that season 0 means specials.'
@staticmethod def get_season_banner_path(show_obj, season):
if (season == 0): season_banner_filename = u'season-specials' else: season_banner_filename = (u'season' + str(season).zfill(2)) return ek(os.path.join, show_obj.location, (season_banner_filename + u'-banner.jpg'))
'This should be overridden by the implementing class. It should provide the content of the show metadata file.'
def _show_data(self, show_obj):
return None
'This should be overridden by the implementing class. It should provide the content of the episode metadata file.'
def _ep_data(self, ep_obj):
return None
'Returns the URL to use for downloading an episode\'s thumbnail. Uses theTVDB.com data. ep_obj: a TVEpisode object for which to grab the thumb URL'
def _get_episode_thumb_url(self, ep_obj):
all_eps = ([ep_obj] + ep_obj.relatedEps) if (not helpers.validateShow(ep_obj.show)): return None for cur_ep in all_eps: myEp = helpers.validateShow(cur_ep.show, cur_ep.season, cur_ep.episode) if (not myEp): continue thumb_url = getattr(myEp, u'filename', None) ...
'Generates and writes show_obj\'s metadata under the given path to the filename given by get_show_file_path() show_obj: TVShow object for which to create the metadata path: An absolute or relative path where we should put the file. Note that the file name will be the default show_file_name. Note that this method expect...
def write_show_file(self, show_obj):
data = self._show_data(show_obj) if (not data): return False nfo_file_path = self.get_show_file_path(show_obj) assert isinstance(nfo_file_path, six.text_type) nfo_file_dir = ek(os.path.dirname, nfo_file_path) try: if (not ek(os.path.isdir, nfo_file_dir)): logger.log((...
'Generates and writes ep_obj\'s metadata under the given path with the given filename root. Uses the episode\'s name with the extension in _ep_nfo_extension. ep_obj: TVEpisode object for which to create the metadata file_name_path: The file name to use for this metadata. Note that the extension will be automatically ad...
def write_ep_file(self, ep_obj):
data = self._ep_data(ep_obj) if (not data): return False nfo_file_path = self.get_episode_file_path(ep_obj) assert isinstance(nfo_file_path, six.text_type) nfo_file_dir = ek(os.path.dirname, nfo_file_path) try: if (not ek(os.path.isdir, nfo_file_dir)): logger.log((u"M...
'Retrieves a thumbnail and saves it to the correct spot. This method should not need to be overridden by implementing classes, changing get_episode_thumb_path and _get_episode_thumb_url should suffice. ep_obj: a TVEpisode object for which to generate a thumbnail'
def save_thumbnail(self, ep_obj):
file_path = self.get_episode_thumb_path(ep_obj) if (not file_path): logger.log(u'Unable to find a file path to use for this thumbnail, not generating it', logger.DEBUG) return False thumb_url = self._get_episode_thumb_url(ep_obj) if (not thumb_url):...
'Downloads a fanart image and saves it to the filename specified by fanart_name inside the show\'s root folder. show_obj: a TVShow object for which to download fanart'
def save_fanart(self, show_obj, which=None):
fanart_path = self.get_fanart_path(show_obj) fanart_data = self._retrieve_show_image(u'fanart', show_obj, which) if (not fanart_data): logger.log(u'No fanart image was retrieved, unable to write fanart', logger.DEBUG) return False return self._write_image(fanart_d...
'Downloads a poster image and saves it to the filename specified by poster_name inside the show\'s root folder. show_obj: a TVShow object for which to download a poster'
def save_poster(self, show_obj, which=None):
poster_path = self.get_poster_path(show_obj) poster_data = self._retrieve_show_image(u'poster', show_obj, which) if (not poster_data): logger.log(u'No show poster image was retrieved, unable to write poster', logger.DEBUG) return False return self._write_image(...
'Downloads a banner image and saves it to the filename specified by banner_name inside the show\'s root folder. show_obj: a TVShow object for which to download a banner'
def save_banner(self, show_obj, which=None):
banner_path = self.get_banner_path(show_obj) banner_data = self._retrieve_show_image(u'banner', show_obj, which) if (not banner_data): logger.log(u'No show banner image was retrieved, unable to write banner', logger.DEBUG) return False return self._write_image(...
'Saves all season posters to disk for the given show. show_obj: a TVShow object for which to save the season thumbs Cycles through all seasons and saves the season posters if possible. This method should not need to be overridden by implementing classes, changing _season_posters_dict and get_season_poster_path should b...
def save_season_posters(self, show_obj, season):
season_dict = self._season_posters_dict(show_obj, season) result = [] for cur_season in season_dict: cur_season_art = season_dict[cur_season] if (not cur_season_art): continue (_, season_url) = cur_season_art.popitem() season_poster_file_path = self.get_season_pos...
'Saves all season banners to disk for the given show. show_obj: a TVShow object for which to save the season thumbs Cycles through all seasons and saves the season banners if possible. This method should not need to be overridden by implementing classes, changing _season_banners_dict and get_season_banner_path should b...
def save_season_banners(self, show_obj, season):
season_dict = self._season_banners_dict(show_obj, season) result = [] for cur_season in season_dict: cur_season_art = season_dict[cur_season] if (not cur_season_art): continue (_, season_url) = cur_season_art.popitem() season_banner_file_path = self.get_season_ban...
'Saves the data in image_data to the location image_path. Returns True/False to represent success or failure. image_data: binary image data to write to file image_path: file location to save the image to'
def _write_image(self, image_data, image_path, obj=None):
assert isinstance(image_path, six.text_type) if ek(os.path.isfile, image_path): logger.log(u'Image already exists, not downloading', logger.DEBUG) return False image_dir = ek(os.path.dirname, image_path) if (not image_data): logger.log(u'Unable to retrieve im...
'Gets an image URL from theTVDB.com and TMDB.com, downloads it and returns the data. image_type: type of image to retrieve (currently supported: fanart, poster, banner) show_obj: a TVShow object to use when searching for the image which: optional, a specific numbered poster to look for Returns: the binary image data if...
def _retrieve_show_image(self, image_type, show_obj, which=None):
image_url = None indexer_lang = show_obj.lang try: lINDEXER_API_PARMS = sickbeard.indexerApi(show_obj.indexer).api_params.copy() lINDEXER_API_PARMS[u'banners'] = True lINDEXER_API_PARMS[u'language'] = (indexer_lang or sickbeard.INDEXER_DEFAULT_LANGUAGE) if show_obj.dvdorder: ...
'Should return a dict like: result = {<season number>: {1: \'<url 1>\', 2: <url 2>, ...},}'
def _season_posters_dict(self, show_obj, season):
result = {} indexer_lang = show_obj.lang try: lINDEXER_API_PARMS = sickbeard.indexerApi(show_obj.indexer).api_params.copy() lINDEXER_API_PARMS[u'banners'] = True lINDEXER_API_PARMS[u'language'] = (indexer_lang or sickbeard.INDEXER_DEFAULT_LANGUAGE) if show_obj.dvdorder: ...
'Should return a dict like: result = {<season number>: {1: \'<url 1>\', 2: <url 2>, ...},}'
def _season_banners_dict(self, show_obj, season):
result = {} indexer_lang = show_obj.lang try: lINDEXER_API_PARMS = sickbeard.indexerApi(show_obj.indexer).api_params.copy() lINDEXER_API_PARMS[u'banners'] = True lINDEXER_API_PARMS[u'language'] = (indexer_lang or sickbeard.INDEXER_DEFAULT_LANGUAGE) t = sickbeard.indexerApi(sh...
'Used only when mass adding Existing Shows, using previously generated Show metadata to reduce the need to query TVDB.'
def retrieveShowMetadata(self, folder):
empty_return = (None, None, None) assert isinstance(folder, six.text_type) metadata_path = ek(os.path.join, folder, self._show_metadata_filename) if ((not ek(os.path.isdir, folder)) or (not ek(os.path.isfile, metadata_path))): logger.log(((u"Can't load the metadata file from " ...
'Returns the path where the episode thumbnail should be stored. Defaults to the same path as the episode file but with a .tbn extension. ep_obj: a TVEpisode instance for which to create the thumbnail'
@staticmethod def get_episode_thumb_path(ep_obj):
if ek(os.path.isfile, ep_obj.location): tbn_filename = replace_extension(ep_obj.location, u'tbn') else: return None return tbn_filename
'Returns the full path to the file for a given season poster. show_obj: a TVShow instance for which to generate the path season: a season number to be used for the path. Note that season 0 means specials.'
@staticmethod def get_season_poster_path(show_obj, season):
if (season == 0): season_poster_filename = u'season-specials' else: season_poster_filename = (u'season' + str(season).zfill(2)) return ek(os.path.join, show_obj.location, (season_poster_filename + u'.tbn'))
'Returns a full show dir/metadata/episode.xml path for MediaBrowser episode metadata files ep_obj: a TVEpisode object to get the path for'
def get_episode_file_path(self, ep_obj):
if ek(os.path.isfile, ep_obj.location): xml_file_name = replace_extension(ek(os.path.basename, ep_obj.location), self._ep_nfo_extension) metadata_dir_name = ek(os.path.join, ek(os.path.dirname, ep_obj.location), u'metadata') xml_file_path = ek(os.path.join, metadata_dir_name, xml_file_name) ...
'Returns a full show dir/metadata/episode.jpg path for MediaBrowser episode thumbs. ep_obj: a TVEpisode object to get the path from'
@staticmethod def get_episode_thumb_path(ep_obj):
if ek(os.path.isfile, ep_obj.location): tbn_file_name = replace_extension(ek(os.path.basename, ep_obj.location), u'jpg') metadata_dir_name = ek(os.path.join, ek(os.path.dirname, ep_obj.location), u'metadata') tbn_file_path = ek(os.path.join, metadata_dir_name, tbn_file_name) else: ...
'Season thumbs for MediaBrowser go in Show Dir/Season X/folder.jpg If no season folder exists, None is returned'
@staticmethod def get_season_poster_path(show_obj, season):
dir_list = [x for x in ek(os.listdir, show_obj.location) if ek(os.path.isdir, ek(os.path.join, show_obj.location, x))] season_dir_regex = u'^Season\\s+(\\d+)$' season_dir = None for cur_dir in dir_list: if ((season == 0) and (cur_dir == u'Specials')): season_dir = cur_dir ...
'Season thumbs for MediaBrowser go in Show Dir/Season X/banner.jpg If no season folder exists, None is returned'
@staticmethod def get_season_banner_path(show_obj, season):
dir_list = [x for x in ek(os.listdir, show_obj.location) if ek(os.path.isdir, ek(os.path.join, show_obj.location, x))] season_dir_regex = u'^Season\\s+(\\d+)$' season_dir = None for cur_dir in dir_list: if ((season == 0) and (cur_dir == u'Specials')): season_dir = cur_dir ...
'Creates an elementTree XML structure for a MediaBrowser-style series.xml returns the resulting data object. show_obj: a TVShow instance to create the NFO for'
def _show_data(self, show_obj):
indexer_lang = show_obj.lang lINDEXER_API_PARMS = sickbeard.indexerApi(show_obj.indexer).api_params.copy() lINDEXER_API_PARMS[u'actors'] = True lINDEXER_API_PARMS[u'language'] = (indexer_lang or sickbeard.INDEXER_DEFAULT_LANGUAGE) if show_obj.dvdorder: lINDEXER_API_PARMS[u'dvdorder'] = True ...
'Creates an elementTree XML structure for a MediaBrowser style episode.xml and returns the resulting data object. show_obj: a TVShow instance to create the NFO for'
def _ep_data(self, ep_obj):
eps_to_write = ([ep_obj] + ep_obj.relatedEps) persons_dict = {u'Director': [], u'GuestStar': [], u'Writer': []} indexer_lang = ep_obj.show.lang try: lINDEXER_API_PARMS = sickbeard.indexerApi(ep_obj.show.indexer).api_params.copy() lINDEXER_API_PARMS[u'actors'] = True lINDEXER_API_...
'Creates an elementTree XML structure for a MediaBrowser-style series.xml returns the resulting data object. show_obj: a TVShow instance to create the NFO for'
def _show_data(self, show_obj):
indexer_lang = show_obj.lang lINDEXER_API_PARMS = sickbeard.indexerApi(show_obj.indexer).api_params.copy() lINDEXER_API_PARMS[u'actors'] = True lINDEXER_API_PARMS[u'language'] = (indexer_lang or sickbeard.INDEXER_DEFAULT_LANGUAGE) if show_obj.dvdorder: lINDEXER_API_PARMS[u'dvdorder'] = True ...
'Creates an elementTree XML structure for a MediaBrowser style episode.xml and returns the resulting data object. show_obj: a TVShow instance to create the NFO for'
def _ep_data(self, ep_obj):
eps_to_write = ([ep_obj] + ep_obj.relatedEps) indexer_lang = ep_obj.show.lang try: lINDEXER_API_PARMS = sickbeard.indexerApi(ep_obj.show.indexer).api_params.copy() lINDEXER_API_PARMS[u'language'] = (indexer_lang or sickbeard.INDEXER_DEFAULT_LANGUAGE) if ep_obj.show.dvdorder: ...