desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'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) nfo_file_dir = ek.ek(os.path.dirname, nfo_file_path) try: if (not ek.ek(os.path.isdir, nfo_file_dir)): logger.log((u"Metadata dir didn't exist, creat...
'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.ek(os.path.dirname, nfo_file_path) try: if (not ek.ek(os.path.isdir, nfo_file_dir)): logger.log((u"Metadata dir didn't exist, creating...
'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('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_da...
'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('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(p...
'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('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(b...
'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 (len(cur_season_art) == 0): continue (art_id, season_url) = cur_season_art.popitem() season_poster_file_path = self.get...
'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 (len(cur_season_art) == 0): continue (art_id, season_url) = cur_season_art.popitem() season_banner_file_path = self.get...
'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):
if ek.ek(os.path.isfile, image_path): logger.log(u'Image already exists, not downloading', logger.DEBUG) return False if (not image_data): logger.log(u'Unable to retrieve image, skipping', logger.WARNING) return False image_dir = ek.ek(os.path.dirname,...
'Gets an image URL from theTVDB.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 available, o...
def _retrieve_show_image(self, image_type, show_obj, which=None):
tvdb_lang = show_obj.lang try: ltvdb_api_parms = sickbeard.TVDB_API_PARMS.copy() if (tvdb_lang and (not (tvdb_lang == 'en'))): ltvdb_api_parms['language'] = tvdb_lang t = tvdb_api.Tvdb(banners=True, **ltvdb_api_parms) tvdb_show_obj = t[show_obj.tvdbid] except (tvd...
'Should return a dict like: result = {<season number>: {1: \'<url 1>\', 2: <url 2>, ...},}'
def _season_posters_dict(self, show_obj, season):
result = {} tvdb_lang = show_obj.lang try: ltvdb_api_parms = sickbeard.TVDB_API_PARMS.copy() if (tvdb_lang and (not (tvdb_lang == 'en'))): ltvdb_api_parms['language'] = tvdb_lang t = tvdb_api.Tvdb(banners=True, **ltvdb_api_parms) tvdb_show_obj = t[show_obj.tvdbid]...
'Should return a dict like: result = {<season number>: {1: \'<url 1>\', 2: <url 2>, ...},}'
def _season_banners_dict(self, show_obj, season):
result = {} tvdb_lang = show_obj.lang try: ltvdb_api_parms = sickbeard.TVDB_API_PARMS.copy() if (tvdb_lang and (not (tvdb_lang == 'en'))): ltvdb_api_parms['language'] = tvdb_lang t = tvdb_api.Tvdb(banners=True, **ltvdb_api_parms) tvdb_show_obj = t[show_obj.tvdbid]...
'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) metadata_path = ek.ek(os.path.join, folder, self._show_metadata_filename) if ((not ek.ek(os.path.isdir, folder)) or (not ek.ek(os.path.isfile, metadata_path))): logger.log(((u"Can't load the metadata file from " + repr(metadata_path)) + ", it doesn...
'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.ek(os.path.isfile, ep_obj.location): xml_file_name = helpers.replaceExtension(ek.ek(os.path.basename, ep_obj.location), self._ep_nfo_extension) metadata_dir_name = ek.ek(os.path.join, ek.ek(os.path.dirname, ep_obj.location), 'metadata') xml_file_path = ek.ek(os.path.join, metadata_dir_...
'Returns a full show dir/metadata/episode.jpg path for MediaBrowser episode thumbs. ep_obj: a TVEpisode object to get the path from'
def get_episode_thumb_path(self, ep_obj):
if ek.ek(os.path.isfile, ep_obj.location): tbn_file_name = helpers.replaceExtension(ek.ek(os.path.basename, ep_obj.location), 'jpg') metadata_dir_name = ek.ek(os.path.join, ek.ek(os.path.dirname, ep_obj.location), 'metadata') tbn_file_path = ek.ek(os.path.join, metadata_dir_name, tbn_file_na...
'Season thumbs for MediaBrowser go in Show Dir/Season X/folder.jpg If no season folder exists, None is returned'
def get_season_poster_path(self, show_obj, season):
dir_list = [x for x in ek.ek(os.listdir, show_obj.location) if ek.ek(os.path.isdir, ek.ek(os.path.join, show_obj.location, x))] season_dir_regex = '^Season\\s+(\\d+)$' season_dir = None for cur_dir in dir_list: if ((season == 0) and (cur_dir == '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'
def get_season_banner_path(self, show_obj, season):
dir_list = [x for x in ek.ek(os.listdir, show_obj.location) if ek.ek(os.path.isdir, ek.ek(os.path.join, show_obj.location, x))] season_dir_regex = '^Season\\s+(\\d+)$' season_dir = None for cur_dir in dir_list: if ((season == 0) and (cur_dir == '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):
tvdb_lang = show_obj.lang ltvdb_api_parms = sickbeard.TVDB_API_PARMS.copy() if (tvdb_lang and (not (tvdb_lang == 'en'))): ltvdb_api_parms['language'] = tvdb_lang t = tvdb_api.Tvdb(actors=True, **ltvdb_api_parms) tv_node = etree.Element('Series') try: myShow = t[int(show_obj.tvdbi...
'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 = {} persons_dict['Director'] = [] persons_dict['GuestStar'] = [] persons_dict['Writer'] = [] tvdb_lang = ep_obj.show.lang try: ltvdb_api_parms = sickbeard.TVDB_API_PARMS.copy() if (tvdb_lang and (not (tvdb_lang == 'e...
'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):
tvdb_lang = show_obj.lang ltvdb_api_parms = sickbeard.TVDB_API_PARMS.copy() if (tvdb_lang and (not (tvdb_lang == 'en'))): ltvdb_api_parms['language'] = tvdb_lang t = tvdb_api.Tvdb(actors=True, **ltvdb_api_parms) rootNode = etree.Element('details') tv_node = etree.SubElement(rootNode, 'mo...
'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) tvdb_lang = ep_obj.show.lang try: ltvdb_api_parms = sickbeard.TVDB_API_PARMS.copy() if (tvdb_lang and (not (tvdb_lang == 'en'))): ltvdb_api_parms['language'] = tvdb_lang t = tvdb_api.Tvdb(actors=True, **ltvdb_api_parms) ...
'Returns the path where the episode thumbnail should be stored. Defaults to the same path as the episode file but with a .metathumb extension. ep_obj: a TVEpisode instance for which to create the thumbnail'
def get_episode_thumb_path(self, ep_obj):
if ek.ek(os.path.isfile, ep_obj.location): tbn_filename = helpers.replaceExtension(ep_obj.location, 'metathumb') else: return None return tbn_filename
'Season thumbs for WDTV go in Show Dir/Season X/folder.jpg If no season folder exists, None is returned'
def get_season_poster_path(self, show_obj, season):
dir_list = [x for x in ek.ek(os.listdir, show_obj.location) if ek.ek(os.path.isdir, ek.ek(os.path.join, show_obj.location, x))] season_dir_regex = '^Season\\s+(\\d+)$' season_dir = None for cur_dir in dir_list: if ((season == 0) and (cur_dir == 'Specials')): season_dir = cur_dir ...
'Creates an elementTree XML structure for a WDTV style episode.xml and returns the resulting data object. ep_obj: a TVShow instance to create the NFO for'
def _ep_data(self, ep_obj):
eps_to_write = ([ep_obj] + ep_obj.relatedEps) tvdb_lang = ep_obj.show.lang try: ltvdb_api_parms = sickbeard.TVDB_API_PARMS.copy() if (tvdb_lang and (not (tvdb_lang == 'en'))): ltvdb_api_parms['language'] = tvdb_lang t = tvdb_api.Tvdb(actors=True, **ltvdb_api_parms) ...
'Initializes a config migrator that can take the config from the version indicated in the config file up to the version required by SB'
def __init__(self, config_obj):
self.config_obj = config_obj self.config_version = check_setting_int(config_obj, 'General', 'config_version', sickbeard.CONFIG_VERSION) self.expected_config_version = sickbeard.CONFIG_VERSION self.migration_names = {1: 'Custom naming', 2: 'Sync backup number with version number', 3: 'R...
'Calls each successive migration until the config is the same version as SB expects'
def migrate_config(self):
if (self.config_version > self.expected_config_version): logger.log_error_and_exit((((((u'Your config version (' + str(self.config_version)) + ') has been incremented past what this version of Sick Beard supports (') + str(self.expected_config_version)) + ').\n')...
'Reads in the old naming settings from your config and generates a new config template from them.'
def _migrate_v1(self):
sickbeard.NAMING_PATTERN = self._name_to_pattern() logger.log((u"Based on your old settings I'm setting your new naming pattern to: " + sickbeard.NAMING_PATTERN)) sickbeard.NAMING_CUSTOM_ABD = bool(check_setting_int(self.config_obj, 'General', 'naming_dates', 0)) if s...
'Reads in the old naming settings from your config and generates a new config template from them.'
def _migrate_v3(self):
sickbeard.OMGWTFNZBS_USERNAME = check_setting_str(self.config_obj, 'omgwtfnzbs', 'omgwtfnzbs_uid', '') sickbeard.OMGWTFNZBS_APIKEY = check_setting_str(self.config_obj, 'omgwtfnzbs', 'omgwtfnzbs_key', '')
'Update newznab providers so that the category IDs can be set independently via the config'
def _migrate_v4(self):
new_newznab_data = [] old_newznab_data = check_setting_str(self.config_obj, 'Newznab', 'newznab_data', '') if old_newznab_data: old_newznab_data_list = old_newznab_data.split('!!!') for cur_provider_data in old_newznab_data_list: try: (name, url, key, enabled) = c...
'Updates metadata values to the new format'
def _migrate_v5(self):
' Quick overview of what the upgrade does:\n\n new | old | description (new)\n ----+-----+--------------------\n 1 | 1 | show metadata\n ...
'Updates Synology notifier to reflect that their now is an update library option instead misusing the enable option'
def _migrate_v6(self):
sickbeard.SYNOINDEX_UPDATE_LIBRARY = bool(check_setting_int(self.config_obj, 'Synology', 'use_synoindex', 0))
'Returns XBMC JSON-RPC API version (odd # = dev, even # = stable) Sends a request to the XBMC host using the JSON-RPC to determine if the legacy API or if the JSON-RPC API functions should be used. Fallback to testing legacy HTTPAPI before assuming it is just a badly configured host. Args: host: XBMC webserver host:por...
def _get_xbmc_version(self, host, username, password):
socket.setdefaulttimeout(10) checkCommand = '{"jsonrpc":"2.0","method":"JSONRPC.Version","id":1}' result = self._send_to_xbmc_json(checkCommand, host, username, password) socket.setdefaulttimeout(sickbeard.SOCKET_TIMEOUT) if result: return result['result']['version'] else: testCo...
'Internal wrapper for the notify_snatch and notify_download functions Detects JSON-RPC version then branches the logic for either the JSON-RPC or legacy HTTP API methods. Args: message: Message body of the notice to send title: Title of the notice to send host: XBMC webserver host:port username: XBMC webserver username...
def _notify(self, message, title='Sick Beard', host=None, username=None, password=None, force=False):
if ((not sickbeard.USE_XBMC) and (not force)): return False if (not host): host = sickbeard.XBMC_HOST if (not username): username = sickbeard.XBMC_USERNAME if (not password): password = sickbeard.XBMC_PASSWORD result = '' for curHost in [x.strip() for x in host.sp...
'Handles communication to XBMC servers via HTTP API Args: command: Dictionary of field/data pairs, encoded via urllib and passed to the XBMC API via HTTP host: XBMC webserver host:port username: XBMC webserver username password: XBMC webserver password Returns: Returns response.result for successful commands or False i...
def _send_to_xbmc(self, command, host=None, username=None, password=None):
if (not username): username = sickbeard.XBMC_USERNAME if (not password): password = sickbeard.XBMC_PASSWORD if (not host): logger.log(u'XBMC: No host specified, check your settings', logger.DEBUG) return False for key in command: if (type(command...
'Handles updating XBMC host via HTTP API Attempts to update the XBMC video library for a specific tv show if passed, otherwise update the whole library if enabled. Args: host: XBMC webserver host:port showName: Name of a TV show to specifically target the library update for Returns: Returns True or False'
def _update_library(self, host=None, showName=None):
if (not host): logger.log(u'XBMC: No host specified, check your settings', logger.DEBUG) return False if showName: logger.log((u'XBMC: Updating library via HTTP method for show ' + showName), logger.MESSAGE) pathSql = ('select path.str...
'Handles communication to XBMC servers via JSONRPC Args: command: Dictionary of field/data pairs, encoded via urllib and passed to the XBMC JSON-RPC via HTTP host: XBMC webserver host:port username: XBMC webserver username password: XBMC webserver password Returns: Returns response.result for successful commands or Fal...
def _send_to_xbmc_json(self, command, host=None, username=None, password=None):
if (not username): username = sickbeard.XBMC_USERNAME if (not password): password = sickbeard.XBMC_PASSWORD if (not host): logger.log(u'XBMC: No host specified, check your settings', logger.DEBUG) return False command = command.encode('utf-8') logger...
'Handles updating XBMC host via HTTP JSON-RPC Attempts to update the XBMC video library for a specific tv show if passed, otherwise update the whole library if enabled. Args: host: XBMC webserver host:port showName: Name of a TV show to specifically target the library update for Returns: Returns True or False'
def _update_library_json(self, host=None, showName=None):
if (not host): logger.log(u'XBMC: No host specified, check your settings', logger.DEBUG) return False if showName: tvshowid = (-1) logger.log((u'XBMC: Updating library via JSON method for show ' + showName), logger.MESSAGE) showsC...
'Public wrapper for the update library functions to branch the logic for JSON-RPC or legacy HTTP API Checks the XBMC API version to branch the logic to call either the legacy HTTP API or the newer JSON-RPC over HTTP methods. Do the ability of accepting a list of hosts delimited by comma, we split off the first host to ...
def update_library(self, ep_obj=None, show_obj=None):
if ep_obj: showName = ep_obj.show.name elif show_obj: showName = show_obj.name else: showName = None if (sickbeard.USE_XBMC and sickbeard.XBMC_UPDATE_LIBRARY): if (not sickbeard.XBMC_HOST): logger.log(u'XBMC: No host specified, check your set...
'Handles communication to Plex hosts via HTTP API Args: command: Dictionary of field/data pairs, encoded via urllib and passed to the legacy xbmcCmds HTTP API host: Plex host:port username: Plex API username password: Plex API password Returns: Returns \'OK\' for successful commands or False if there was an error'
def _send_to_plex(self, command, host, username=None, password=None):
if (not username): username = sickbeard.PLEX_USERNAME if (not password): password = sickbeard.PLEX_PASSWORD if (not host): logger.log(u'PLEX: No host specified, check your settings', logger.ERROR) return False for key in command: if (type(command...
'Internal wrapper for the notify_snatch and notify_download functions Args: message: Message body of the notice to send title: Title of the notice to send host: Plex Media Client(s) host:port username: Plex username password: Plex password force: Used for the Test method to override config safety checks Returns: Return...
def _notify(self, message, title='Sick Beard', host=None, username=None, password=None, force=False):
if ((not sickbeard.USE_PLEX) and (not force)): return False if (not host): host = sickbeard.PLEX_HOST if (not username): username = sickbeard.PLEX_USERNAME if (not password): password = sickbeard.PLEX_PASSWORD result = '' for curHost in [x.strip() for x in host.sp...
'Handles updating the Plex Media Server host via HTTP API Plex Media Server currently only supports updating the whole video library and not a specific path. Returns: Returns True or False'
def update_library(self, ep_obj=None, host=None, username=None, password=None):
if (not host): host = sickbeard.PLEX_SERVER_HOST if (not username): username = sickbeard.PLEX_USERNAME if (not password): password = sickbeard.PLEX_PASSWORD if (sickbeard.USE_PLEX and sickbeard.PLEX_UPDATE_LIBRARY): if (not sickbeard.PLEX_SERVER_HOST): logger....
'Retrieves the settings from a NMJ/Popcorn Hour host: The hostname/IP of the Popcorn Hour server Returns: True if the settings were retrieved successfully, False otherwise'
def notify_settings(self, host):
terminal = False try: terminal = telnetlib.Telnet(host) except Exception: logger.log((u'NMJ: Unable to get a telnet session to %s' % host), logger.WARNING) return False logger.log((u'NMJ: Connected to %s via telnet' % host), logger.DEBUG) ...
'Sends a NMJ update command to the specified machine host: The hostname/IP to send the request to (no port) database: The database to send the request to mount: The mount URL to use (optional) Returns: True if the request succeeded, False otherwise'
def _sendNMJ(self, host, database, mount=None):
if mount: try: req = urllib2.Request(mount) logger.log((u'NMJ: Try to mount network drive via url: %s' % mount), logger.DEBUG) sickbeard.helpers.getURLFileLike(req) except IOError as e: if hasattr(e, 'reason'): l...
'Sends a NMJ update command based on the SB config settings host: The host to send the command to (optional, defaults to the host in the config) database: The database to use (optional, defaults to the database in the config) mount: The mount URL (optional, defaults to the mount URL in the config) force: If True then t...
def _notifyNMJ(self, host=None, database=None, mount=None, force=False):
if ((not sickbeard.USE_NMJ) and (not force)): return False if (not host): host = sickbeard.NMJ_HOST if (not database): database = sickbeard.NMJ_DATABASE if (not mount): mount = sickbeard.NMJ_MOUNT logger.log(u'NMJ: Sending scan command.', logger.DEBUG) re...
'Sends a boxcar2 notification to the address provided msg: The message to send (unicode) title: The title of the message accessToken: The access token to send notification to returns: True if the message succeeded, False otherwise'
def _sendBoxcar2(self, title, msg, accessToken, sound):
msg = msg.strip().encode('utf-8') data = urllib.urlencode({'user_credentials': accessToken, 'notification[title]': ((title + ' - ') + msg), 'notification[long_message]': msg, 'notification[sound]': sound, 'notification[source_name]': 'SickBeard'}) try: req = urllib2.Request(API_URL, data) ...
'Sends a boxcar2 notification based on the provided info or SB config title: The title of the notification to send message: The message string to send accessToken: The access token to send the notification to (optional, defaults to the access token in the config) force: If True then the notification will be sent even i...
def _notify(self, title, message, accessToken=None, sound=None, force=False):
if ((not sickbeard.USE_BOXCAR2) and (not force)): return False if (not accessToken): accessToken = sickbeard.BOXCAR2_ACCESS_TOKEN if (not sound): sound = sickbeard.BOXCAR2_SOUND logger.log((u'BOXCAR2: Sending notification for ' + message), logger.DEBUG) return sel...
'Sends a pushbullet notification based on the provided info or SB config title: The title of the notification to send body: The body string to send accessToken: The access token to grant access device_iden: The iden of a specific target, if none provided send to all devices force: If True then the notification will be ...
def _notify(self, title, body, accessToken=None, device_iden=None, force=False):
if ((not sickbeard.USE_PUSHBULLET) and (not force)): return False if (not accessToken): accessToken = sickbeard.PUSHBULLET_ACCESS_TOKEN if (not device_iden): device_iden = sickbeard.PUSHBULLET_DEVICE_IDEN logger.log((u'PUSHBULLET: Sending notice with details: title...
'A generic method for communicating with trakt. Uses the method and data provided along with the auth info to send the command. method: The URL to use at trakt, relative, no leading slash. api: The API string to provide to trakt username: The username to use when logging in password: The unencrypted password to use whe...
def _notifyTrakt(self, method, api, username, password, data={}, force=False):
if ((not sickbeard.USE_TRAKT) and (not force)): return False logger.log((u'TRAKT: Calling method ' + method), logger.DEBUG) if (not api): api = sickbeard.TRAKT_API if (not username): username = sickbeard.TRAKT_USERNAME if (not password): password = sickbeard....
'Sends a test notification to trakt with the given authentication info and returns a boolean representing success. api: The api string to use username: The username to use password: The password to use Returns: True if the request succeeded, False otherwise'
def test_notify(self, api, username, password):
method = 'account/test/' return self._notifyTrakt(method, api, username, password, {}, force=True)
'Sends a request to trakt indicating that the given episode is part of our library. ep_obj: The TVEpisode object to add to trakt'
def update_library(self, ep_obj=None):
if sickbeard.USE_TRAKT: method = 'show/episode/library/' data = {'tvdb_id': ep_obj.show.tvdbid, 'title': ep_obj.show.name, 'year': ep_obj.show.startyear, 'episodes': [{'season': ep_obj.season, 'episode': ep_obj.episode}]} if data: self._notifyTrakt(method, None, None, None, data)...
'Sends a pushover notification based on the provided info or SB config'
def _notify(self, title, message, userKey=None, priority=None, device=None, sound=None, force=False):
if ((not sickbeard.USE_PUSHOVER) and (not force)): return False if (not userKey): userKey = sickbeard.PUSHOVER_USERKEY if (not priority): priority = sickbeard.PUSHOVER_PRIORITY if (not device): device = sickbeard.PUSHOVER_DEVICE if (not sound): sound = sickbea...
'Retrieves the NMJv2 database location from Popcorn Hour host: The hostname/IP of the Popcorn Hour server dbloc: \'local\' for PCH internal harddrive. \'network\' for PCH network shares instance: Allows for selection of different DB in case of multiple databases Returns: True if the settings were retrieved successfully...
def notify_settings(self, host, dbloc, instance):
try: url_loc = (((('http://' + host) + ':8008/file_operation?arg0=list_user_storage_file&arg1=&arg2=') + instance) + '&arg3=20&arg4=true&arg5=true&arg6=true&arg7=all&arg8=name_asc&arg9=false&arg10=false') req = urllib2.Request(url_loc) response1 = sickbeard.helpers.getURL(req) xml = ...
'Sends a NMJ update command to the specified machine host: The hostname/IP to send the request to (no port) database: The database to send the request to mount: The mount URL to use (optional) Returns: True if the request succeeded, False otherwise'
def _sendNMJ(self, host):
try: url_scandir = (((('http://' + host) + ':8008/metadata_database?arg0=update_scandir&arg1=') + sickbeard.NMJv2_DATABASE) + '&arg2=&arg3=update_all') logger.log((u'NMJv2: Scan update command send to host: %s' % host), logger.DEBUG) url_updatedb = (((('http://' + host) ...
'Sends a NMJ update command based on the SB config settings host: The host to send the command to (optional, defaults to the host in the config) database: The database to use (optional, defaults to the database in the config) mount: The mount URL (optional, defaults to the mount URL in the config) force: If True then t...
def _notifyNMJ(self, host=None, force=False):
if ((not sickbeard.USE_NMJv2) and (not force)): return False if (not host): host = sickbeard.NMJv2_HOST logger.log(u'NMJv2: Sending scan command.', logger.DEBUG) return self._sendNMJ(host)
'Returns a tuple containing (status, quality)'
@staticmethod def splitCompositeStatus(status):
if (status == UNKNOWN): return (UNKNOWN, Quality.UNKNOWN) for x in sorted(Quality.qualityStrings.keys(), reverse=True): if (status > (x * 100)): return ((status - (x * 100)), x) return (status, Quality.NONE)
'This should be overridden and should return the config setting eg. sickbeard.MYPROVIDER'
def isEnabled(self):
return False
'Returns a result of the correct type for this provider'
def getResult(self, episodes):
if (self.providerType == GenericProvider.NZB): result = classes.NZBSearchResult(episodes) elif (self.providerType == GenericProvider.TORRENT): result = classes.TorrentSearchResult(episodes) else: result = classes.SearchResult(episodes) result.provider = self return result
'By default this is just a simple urlopen call but this method should be overridden for providers with special URL requirements (like cookies)'
def getURL(self, url, post_data=None, heads=None):
if post_data: if heads: req = urllib2.Request(url, post_data, heads) else: req = urllib2.Request(url, post_data) elif heads: req = urllib2.Request(url, headers=heads) else: req = urllib2.Request(url) response = helpers.getURL(req) if (response ...
'Save the result to disk.'
def downloadResult(self, result):
logger.log((((u'Downloading a result from ' + self.name) + ' at ') + result.url)) data = self.getURL(result.url) if (not data): return False if (self.providerType == GenericProvider.NZB): saveDir = sickbeard.NZB_DIR writeMode = 'w' elif (self.providerType ==...
'Checks the saved file to see if it was actually valid, if not then consider the download a failure.'
def _verify_download(self, file_name=None):
if (self.providerType == GenericProvider.TORRENT): parser = createParser(file_name) if parser: mime_type = parser._getMimeType() try: parser.stream._input.close() except: pass if (mime_type != 'application/x-bittorrent')...
'Figures out the quality of the given RSS item node item: An elementtree.ElementTree element representing the <item> tag of the RSS feed Returns a Quality value obtained from the node\'s data'
def getQuality(self, item):
(title, url) = self._get_title_and_url(item) quality = Quality.nameQuality(title) return quality
'Retrieves the title and URL data from the item XML node item: An elementtree.ElementTree element representing the <item> tag of the RSS feed Returns: A tuple containing two strings representing title and URL respectively'
def _get_title_and_url(self, item):
title = helpers.get_xml_text(item.find('title')) if title: title = title.replace(' ', '.') url = helpers.get_xml_text(item.find('link')) if url: url = url.replace('&amp;', '&') return (title, url)
'Add a regular notification to the queue title: The title of the notification message: The message portion of the notification'
def message(self, title, message=''):
self._messages.append(Notification(title, message, MESSAGE))
'Add an error notification to the queue title: The title of the notification message: The message portion of the notification'
def error(self, title, message=''):
self._errors.append(Notification(title, message, ERROR))
'Return all the available notifications in a list. Marks them all as seen as it returns them. Also removes timed out Notifications from the queue. Returns: A list of Notification objects'
def get_notifications(self):
self._errors = [x for x in self._errors if (not x.is_expired())] self._messages = [x for x in self._messages if (not x.is_expired())] return [x.see() for x in (self._errors + self._messages) if x.is_new()]
'Returns True if the notification hasn\'t been displayed to the current client (aka IP address).'
def is_new(self):
return (cherrypy.request.remote.ip not in self._seen)
'Returns True if the notification is older than the specified timeout value.'
def is_expired(self):
return ((datetime.datetime.now() - self._when) > self._timeout)
'Returns this notification object and marks it as seen by the client ip'
def see(self):
self._seen.append(cherrypy.request.remote.ip) return self
'Returns the show name if there is a show object created, if not returns the dir that the show is being added to.'
def _getName(self):
if (self.show is None): return self.showDir return self.show.name
'Returns True if we\'ve gotten far enough to have a show object, or False if we still only know the folder name.'
def _isLoading(self):
if (self.show is None): return True return False
'Cleans up series name by removing any . and _ characters, along with any trailing hyphens. Is basically equivalent to replacing all _ and . with a space, but handles decimal numbers in string, for example: >>> cleanRegexedSeriesName("an.example.1.0.test") \'an example 1.0 test\' >>> cleanRegexedSeriesName("an_example_...
def clean_series_name(self, series_name):
series_name = re.sub('(\\D)\\.(?!\\s)(\\D)', '\\1 \\2', series_name) series_name = re.sub('(\\d)\\.(\\d{4})', '\\1 \\2', series_name) series_name = re.sub('(\\D)\\.(?!\\s)', '\\1 ', series_name) series_name = re.sub('\\.(?!\\s)(\\D)', ' \\1', series_name) series_name = series_name.replac...
'Convert number into an integer. Try force converting into integer first, on error try converting from Roman numerals. Args: number: int or representation of a number: string or unicode Returns: integer: int number Raises: ValueError'
def _convert_number(self, number):
try: integer = int(number) except: roman_numeral_map = (('M', 1000, 3), ('CM', 900, 1), ('D', 500, 1), ('CD', 400, 1), ('C', 100, 3), ('XC', 90, 1), ('L', 50, 1), ('XL', 40, 1), ('X', 10, 3), ('IX', 9, 1), ('V', 5, 1), ('IV', 4, 1), ('I', 1, 3)) roman_numeral = str(number).upper() ...
'Access the API at the path given and with the optional params given. path: A list of the path elements to use (eg. [\'repos\', \'midgetspy\', \'Sick-Beard\', \'commits\']) params: Optional dict of name/value pairs for extra params to send. (eg. {\'per_page\': 10}) Returns a deserialized json object of the result. Does...
def _access_API(self, path, params=None):
url = ('https://api.github.com/' + '/'.join(path)) if (params and (type(params) is dict)): url += ('?' + '&'.join([((str(x) + '=') + str(params[x])) for x in params.keys()])) data = helpers.getURL(url) if data: json_data = json.loads(data) return json_data else: retur...
'Uses the API to get a list of the 100 most recent commits from the specified user/repo/branch, starting from HEAD. user: The github username of the person whose repo you\'re querying repo: The repo name to query branch: Optional, the branch name to show commits from Returns a deserialized json object containing the co...
def commits(self):
access_API = self._access_API(['repos', self.github_repo_user, self.github_repo, 'commits'], params={'per_page': 100, 'sha': self.branch}) return access_API
'Uses the API to get a list of compares between base and head. user: The github username of the person whose repo you\'re querying repo: The repo name to query base: Start compare from branch head: Current commit sha or branch name to compare per_page: number of items per page Returns a deserialized json object contain...
def compare(self, base, head, per_page=1):
access_API = self._access_API(['repos', self.github_repo_user, self.github_repo, 'compare', ((base + '...') + head)], params={'per_page': per_page}) return access_API
'Update bitwise flags to reflect new quality values Check flag bits (clear old then set their new locations) starting with the highest bits so we dont overwrite data we need later on'
def _update_quality(self, old_quality):
result = old_quality if (result & (1 << 5)): result = (result & (~ (1 << 5))) result = (result | (1 << 8)) if (result & (1 << 4)): result = (result & (~ (1 << 4))) result = (result | (1 << 7)) if (result & (1 << 3)): result = (result & (~ (1 << 3))) result...
'Unpack, Update, Return new quality values Unpack the composite archive/initial values. Update either qualities if needed. Then return the new compsite quality value.'
def _update_composite_qualities(self, status):
best = ((status & (65535 << 16)) >> 16) initial = (status & 65535) best = self._update_quality(best) initial = self._update_quality(initial) result = ((best << 16) | initial) return result
'Configure a file handler to log at file_name and return it.'
def _config_handler(self):
file_handler = logging.FileHandler(self.log_file_path, encoding='utf-8') file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)-8s %(message)s', '%Y-%m-%d %H:%M:%S')) return file_handler
'Returns a numbered log file name depending on i. If i==0 it just uses logName, if not it appends it to the extension (blah.log.3 for i == 3) i: Log number to ues'
def _log_file_name(self, i):
return (self.log_file_path + (('.' + str(i)) if i else ''))
'Scans the log folder and figures out how many log files there are already on disk Returns: The number of the last used file (eg. mylog.log.3 would return 3). If there are no logs it returns -1'
def _num_logs(self):
cur_log = 0 while os.path.isfile(self._log_file_name(cur_log)): cur_log += 1 return (cur_log - 1)
'Saves this episode to the database if any of its data has been changed since the last save. forceSave: If True it will save to the database even if no data has been changed since the last save (aka if the record is not dirty).'
def saveToDB(self, forceSave=False):
if ((not self.dirty) and (not forceSave)): logger.log((str(self.show.tvdbid) + u': Not saving episode to db - record is not dirty'), logger.DEBUG) return logger.log((str(self.show.tvdbid) + u': Saving episode details to database'), logger.DEBUG) l...
'Returns the name of this episode in a "pretty" human-readable format. Used for logging and notifications and such. Returns: A string representing the episode\'s name and season/ep numbers'
def prettyName(self):
return self._format_pattern('%SN - %Sx%0E - %EN')
'Returns the name of the episode to use during renaming. Combines the names of related episodes. Eg. "Ep Name (1)" and "Ep Name (2)" becomes "Ep Name" "Ep Name" and "Other Ep Name" becomes "Ep Name & Other Ep Name"'
def _ep_name(self):
multiNameRegex = '(.*) \\(\\d{1,2}\\)' self.relatedEps = sorted(self.relatedEps, key=(lambda x: x.episode)) if (len(self.relatedEps) == 0): goodName = self.name else: goodName = '' singleName = True curGoodName = None for curName in ([self.name] + [x.name for x...
'Generates a replacement map for this episode which maps all possible custom naming patterns to the correct value for this episode. Returns: A dict with patterns as the keys and their replacement values as the values.'
def _replace_map(self):
ep_name = self._ep_name() def dot(name): return helpers.sanitizeSceneName(name) def us(name): return re.sub('[ -]', '_', name) def release_name(name): if name: name = helpers.remove_non_release_groups(helpers.remove_extension(name)) return name def rele...
'Replaces all template strings with the correct value'
def _format_string(self, pattern, replace_map):
result_name = pattern for cur_replacement in sorted(replace_map.keys(), reverse=True): result_name = result_name.replace(cur_replacement, helpers.sanitizeFileName(replace_map[cur_replacement])) result_name = result_name.replace(cur_replacement.lower(), helpers.sanitizeFileName(replace_map[cur_re...
'Manipulates an episode naming pattern and then fills the template in'
def _format_pattern(self, pattern=None, multi=None, debug=False):
if (pattern is None): pattern = sickbeard.NAMING_PATTERN if (multi is None): multi = sickbeard.NAMING_MULTI_EP replace_map = self._replace_map() result_name = pattern if (not replace_map['%RN']): if self.show.air_by_date: result_name = result_name.replace('%RN', '...
'Figures out the path where this episode SHOULD live according to the renaming rules, relative from the show dir'
def proper_path(self):
result = self.formatted_filename() if (self.show.flatten_folders and (not sickbeard.NAMING_FORCE_FOLDERS)): return result else: result = ek.ek(os.path.join, self.formatted_dir(), result) return result
'Just the folder name of the episode'
def formatted_dir(self, pattern=None, multi=None, debug=False):
if (pattern is None): if (self.show.air_by_date and sickbeard.NAMING_CUSTOM_ABD and (not self.relatedEps)): pattern = sickbeard.NAMING_ABD_PATTERN else: pattern = sickbeard.NAMING_PATTERN name_groups = re.split('[\\\\/]', pattern) if (len(name_groups) == 1): r...
'Just the filename of the episode, formatted based on the naming settings'
def formatted_filename(self, pattern=None, multi=None, debug=False):
if (pattern is None): if (self.show.air_by_date and sickbeard.NAMING_CUSTOM_ABD and (not self.relatedEps)): pattern = sickbeard.NAMING_ABD_PATTERN else: pattern = sickbeard.NAMING_PATTERN name_groups = re.split('[\\\\/]', pattern) return self._format_pattern(name_grou...
'Renames an episode file and all related files to the location and filename as specified in the naming settings.'
def rename(self):
if (not ek.ek(os.path.isfile, self.location)): logger.log(((u"Can't perform rename on " + self.location) + " when it doesn't exist, skipping"), logger.WARNING) return proper_path = self.proper_path() absolute_proper_path = ek.ek(os.path.join, self.show.location, pr...
'Implementing classes should call this'
def execute(self):
self.inProgress = True
'Implementing Classes should call this'
def finish(self):
self.inProgress = False
'Read the request body into fp_out (or make_file() if None). Return fp_out.'
def read_into_file(self, fp_out=None):
if (fp_out is None): fp_out = self.make_file() self.read(fp_out=fp_out) return fp_out
'Return a file into which the request body will be read. By default, this will return a TemporaryFile. Override as needed.'
def make_file(self):
return tempfile.TemporaryFile()
'Return this entity as a string, whether stored in a file or not.'
def fullvalue(self):
if self.file: self.file.seek(0) value = self.file.read() self.file.seek(0) else: value = self.value return value
'Execute the best-match processor for the given media type.'
def process(self):
proc = None ct = self.content_type.value try: proc = self.processors[ct] except KeyError: toptype = ct.split(u'/', 1)[0] try: proc = self.processors[toptype] except KeyError: pass if (proc is None): self.default_proc() else: ...
'Read bytes from self.fp and return or write them to a file. If the \'fp_out\' argument is None (the default), all bytes read are returned in a single byte string. If the \'fp_out\' argument is not None, it must be a file-like object that supports the \'write\' method; all bytes read will be written to the fp, and that...
def read_lines_to_boundary(self, fp_out=None):
endmarker = (self.boundary + '--') delim = '' prev_lf = True lines = [] seen = 0 while True: line = self.fp.readline((1 << 16)) if (not line): raise EOFError(u'Illegal end of multipart body.') if (line.startswith('--') and prev_lf): str...
'Read the request body into fp_out (or make_file() if None). Return fp_out.'
def read_into_file(self, fp_out=None):
if (fp_out is None): fp_out = self.make_file() self.read_lines_to_boundary(fp_out=fp_out) return fp_out
'Read bytes from the request body and return or write them to a file. A number of bytes less than or equal to the \'size\' argument are read off the socket. The actual number of bytes read are tracked in self.bytes_read. The number may be smaller than \'size\' when 1) the client sends fewer bytes, 2) the \'Content-Leng...
def read(self, size=None, fp_out=None):
if (self.length is None): if (size is None): remaining = inf else: remaining = size else: remaining = (self.length - self.bytes_read) if (size and (size < remaining)): remaining = size if (remaining == 0): self.finish() if (...
'Read a line from the request body and return it.'
def readline(self, size=None):
chunks = [] while ((size is None) or (size > 0)): chunksize = self.bufsize if ((size is not None) and (size < self.bufsize)): chunksize = size data = self.read(chunksize) if (not data): break pos = (data.find('\n') + 1) if pos: ...