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(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 ...
'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. 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'
@staticmethod def get_episode_thumb_path(ep_obj):
if ek(os.path.isfile, ep_obj.location): tbn_filename = replace_extension(ep_obj.location, u'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'
@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 ...
'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) 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_DEFAULT_LANGUA...
'Creates an elementTree XML structure for an KODI-style tvshow.nfo and returns the resulting data object. show_obj: a TVShow instance to create the NFO for'
def _show_data(self, show_obj):
show_ID = show_obj.indexerid 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: lINDEX...
'Creates an elementTree XML structure for an KODI-style episode.nfo and returns the resulting data object. show_obj: a TVEpisode 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 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_DEFAULT_LANGUAGE) if ep_obj.sho...
'Gets a list of most popular TV series from imdb'
def __init__(self):
self.session = helpers.make_session()
'Get trending show information from Trakt'
def fetch_trending_shows(self, trakt_list, page_url):
trending_shows = [] trakt_api = TraktAPI(sickbeard.SSL_VERIFY, sickbeard.TRAKT_TIMEOUT) try: not_liked_show = u'' if (sickbeard.TRAKT_ACCESS_TOKEN != u''): library_shows = (trakt_api.traktRequest(u'sync/collection/shows?extended=full') or []) if sickbeard.TRAKT_BLACKL...
'Get poster image url from TVDB'
@staticmethod def get_image_url(indexer_id):
image_url = None try: lINDEXER_API_PARMS = sickbeard.indexerApi(INDEXER_TVDB).api_params.copy() lINDEXER_API_PARMS[u'banners'] = True t = sickbeard.indexerApi(INDEXER_TVDB).indexer(**lINDEXER_API_PARMS) indexer_show_obj = t[int(indexer_id)] except (sickbeard.indexer_error, IO...
'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, u'General', u'config_version', sickbeard.CONFIG_VERSION) self.expected_config_version = sickbeard.CONFIG_VERSION self.migration_names = {1: u'Custom naming', 2: u'Sync backup number with version number', 3...
'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 ({0:d}) has been incremented past what this version of SickRage supports ({1:d}).\n If you h...
'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 = check_setting_bool(self.config_obj, u'General', u'naming_dates') if sickbea...
'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, u'omgwtfnzbs', u'omgwtfnzbs_uid') sickbeard.OMGWTFNZBS_APIKEY = check_setting_str(self.config_obj, u'omgwtfnzbs', u'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, u'Newznab', u'newznab_data') if old_newznab_data: old_newznab_data_list = old_newznab_data.split(u'!!!') for cur_provider_data in old_newznab_data_list: try: (name, url, key, enabled) = cu...
'Updates metadata values to the new format'
def _migrate_v5(self):
u' Quick overview of what the upgrade does:\n\n new | old | description (new)\n ----+-----+--------------------\n 1 | 1 | show metadata\n ...
'Sends a SMS notification msg: The message to send (six.text_type) title: The title of the message userKey: The pushover user id to send the message to (or to subscribe with) returns: True if the message succeeded, False otherwise'
def _sendFreeMobileSMS(self, title, msg, cust_id=None, apiKey=None):
if (cust_id is None): cust_id = sickbeard.FREEMOBILE_ID if (apiKey is None): apiKey = sickbeard.FREEMOBILE_APIKEY logger.log((u'Free Mobile in use with API KEY: ' + apiKey), logger.DEBUG) msg = msg.strip() msg_quoted = urllib.parse.quote(((title.encode(u'utf-8') ...
'Sends a SMS notification title: The title of the notification to send message: The message string to send cust_id: Your Free Mobile customer ID apikey: Your Free Mobile API key force: Enforce sending, for instance for testing'
def _notifyFreeMobile(self, title, message, cust_id=None, apiKey=None, force=False):
if ((not sickbeard.USE_FREEMOBILE) and (not force)): logger.log(u'Notification for Free Mobile not enabled, skipping this notification', logger.DEBUG) return (False, u'Disabled') logger.log((u'Sending a SMS for ' + message), logger.DEBUG) return self._send...
'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 Home Theater(s) host:port username: Plex username password: Plex password force: Used for the Test method to override config safety checks Returns: Return...
@staticmethod def _notify_pht(message, title=u'SickRage', host=None, username=None, password=None, force=False):
if ((not sickbeard.USE_PLEX_CLIENT) and (not force)): return False host = (host or sickbeard.PLEX_CLIENT_HOST) username = (username or sickbeard.PLEX_CLIENT_USERNAME) password = (password or sickbeard.PLEX_CLIENT_PASSWORD) return sickbeard.notifiers.kodi_notifier._notify_kodi(message, title=...
'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 None for no issue, else a string of host with connection issues'
def update_library(self, ep_obj=None, host=None, username=None, password=None, plex_server_token=None, force=False):
if ((not (sickbeard.USE_PLEX_SERVER and sickbeard.PLEX_UPDATE_LIBRARY)) and (not force)): return None host = (host or sickbeard.PLEX_SERVER_HOST) if (not host): logger.log(u'PLEX: No Plex Media Server host specified, check your settings', logger.DEBUG) retu...
'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):
try: terminal = telnetlib.Telnet(host) except Exception: logger.log(u'Warning: unable to get a telnet session to {0}'.format(host), logger.WARNING) return False logger.log(u'Connected to {0} via telnet'.format(host), logger.DEBUG) terminal.read...
'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 = urllib.request.Request(mount) logger.log(u'Try to mount network drive via url: {0}'.format(mount), logger.DEBUG) handle = urllib.request.urlopen(req) except IOError as e: if hasattr(e, u'reason'): ...
'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)): logger.log(u'Notification for NMJ scan update not enabled, skipping this notification', logger.DEBUG) return False if (not host): host = sickbeard.NMJ_HOST if (not database): database = sickbeard.NMJ_DAT...
'Check the environment for reasons libnotify isn\'t working. Return a user-readable message indicating possible issues.'
@staticmethod def diagnose():
if (not Notify): return u'<p>Error: gir-notify isn\'t installed. On Ubuntu/Debian, install the <a href="apt:gir1.2-notify-0.7">gir1.2-notify-0.7</a> or <a href="apt:gir1.0-notify-0.4">gir1.0-notify-0.4</a> package.' if ((u'DISPLAY' not in os.environ) and (u'DBUS_SE...
'Sends a boxcar2 notification to the address provided msg: The message to send title: The title of the message accesstoken: to send to this device returns: True if the message succeeded, False otherwise'
def _sendBoxcar2(self, msg, title, accesstoken):
post_data = {u'user_credentials': accesstoken, u'notification[title]': u'SickRage : {0}: {1}'.format(title, msg), u'notification[long_message]': msg, u'notification[sound]': u'notifier-2', u'notification[source_name]': u'SickRage', u'notification[icon_url]': sickbeard.LOGO_URL} response = sickbeard.hel...
'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: to send to this device'
def _notifyBoxcar2(self, title, message, accesstoken=None):
if (not sickbeard.USE_BOXCAR2): logger.log(u'Notification for Boxcar2 not enabled, skipping this notification', logger.DEBUG) return False accesstoken = (accesstoken or sickbeard.BOXCAR2_ACCESSTOKEN) logger.log(u'Sending notification for {0}'.format(message), lo...
'Fetches the list of channels a given access key has permissions to push to'
def get_channels(self, pushbullet_api):
logger.log(u'Testing Pushbullet authentication and retrieving the device list.', logger.DEBUG) headers = {u'Access-Token': pushbullet_api} return (helpers.getURL(urljoin(self.url, u'channels'), session=self.session, headers=headers, returns=u'text') or {})
'Handles notifying Emby host via HTTP API Returns: Returns True for no issue or False if there was an error'
def _notify_emby(self, message, host=None, emby_apikey=None):
if (not host): host = sickbeard.EMBY_HOST if (not emby_apikey): emby_apikey = sickbeard.EMBY_APIKEY url = u'http://{0}/emby/Notifications/Admin'.format(host) values = {u'Name': u'SickRage', u'Description': message, u'ImageUrl': sickbeard.LOGO_URL} data = json.dumps(values) try: ...
'Handles updating the Emby Media Server host via HTTP API Returns: Returns True for no issue or False if there was an error'
def update_library(self, show=None):
if sickbeard.USE_EMBY: if (not sickbeard.EMBY_HOST): logger.log(u'EMBY: No host specified, check your settings', logger.DEBUG) return False if show: if (show.indexer == 1): provider = u'tvdb' elif (show.indexer == 2): ...
'Returns KODI JSON-RPC API version (odd # = dev, even # = stable) Sends a request to the KODI 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: KODI webserver host:por...
def _get_kodi_version(self, host, username, password, dest_app=u'KODI'):
socket.setdefaulttimeout(10) checkCommand = u'{"jsonrpc":"2.0","method":"JSONRPC.Version","id":1}' result = self._send_to_kodi_json(checkCommand, host, username, password, dest_app) socket.setdefaulttimeout(sickbeard.SOCKET_TIMEOUT) if result: return result[u'result'][u'version'] else: ...
'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: KODI webserver host:port username: KODI webserver username...
def _notify_kodi(self, message, title=u'SickRage', host=None, username=None, password=None, force=False, dest_app=u'KODI'):
if (not host): host = sickbeard.KODI_HOST if (not username): username = sickbeard.KODI_USERNAME if (not password): password = sickbeard.KODI_PASSWORD if ((not sickbeard.USE_KODI) and (not force)): logger.log(u'Notification for {0} not enabled, skipping t...
'Internal wrapper for the update library function to branch the logic for JSON-RPC or legacy HTTP API Checks the KODI API version to branch the logic to call either the legacy HTTP API or the newer JSON-RPC over HTTP methods. Args: host: KODI webserver host:port showName: Name of a TV show to specifically target the li...
def _send_update_library(self, host, showName=None):
logger.log(u"Sending request to update library for KODI host: '{0}'".format(host), logger.DEBUG) kodiapi = self._get_kodi_version(host, sickbeard.KODI_USERNAME, sickbeard.KODI_PASSWORD) if kodiapi: if (kodiapi <= 4): if ((not self._update_library(host, showName)) ...
'Handles communication to KODI servers via HTTP API Args: command: Dictionary of field/data pairs, encoded via urllib and passed to the KODI API via HTTP host: KODI webserver host:port username: KODI webserver username password: KODI webserver password Returns: Returns response.result for successful commands or False i...
@staticmethod def _send_to_kodi(command, host=None, username=None, password=None, dest_app=u'KODI'):
if (not username): username = sickbeard.KODI_USERNAME if (not password): password = sickbeard.KODI_PASSWORD if (not host): logger.log(u'No {0} host passed, aborting update'.format(dest_app), logger.WARNING) return False for key in command: if isinst...
'Handles updating KODI host via HTTP API Attempts to update the KODI video library for a specific tv show if passed, otherwise update the whole library if enabled. Args: host: KODI 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'No KODI host passed, aborting update', logger.WARNING) return False logger.log((u'Updating KODI library via HTTP method for host: ' + host), logger.DEBUG) if showName: logger.log((u'Updating library in KODI ...
'Handles communication to KODI servers via JSONRPC Args: command: Dictionary of field/data pairs, encoded via urllib and passed to the KODI JSON-RPC via HTTP host: KODI webserver host:port username: KODI webserver username password: KODI webserver password Returns: Returns response.result for successful commands or Fal...
@staticmethod def _send_to_kodi_json(command, host=None, username=None, password=None, dest_app=u'KODI'):
if (not username): username = sickbeard.KODI_USERNAME if (not password): password = sickbeard.KODI_PASSWORD if (not host): logger.log(u'No {0} host passed, aborting update'.format(dest_app), logger.WARNING) return False command = command.encode(u'utf-8') ...
'Handles updating KODI host via HTTP JSON-RPC Attempts to update the KODI video library for a specific tv show if passed, otherwise update the whole library if enabled. Args: host: KODI 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'No KODI host passed, aborting update', logger.WARNING) return False logger.log((u'Updating KODI library via JSON method for host: ' + host), logger.DEBUG) if showName: showName = urllib.parse.unquote_plus(showName) ...
'Public wrapper for the update library functions to branch the logic for JSON-RPC or legacy HTTP API Checks the KODI 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, only one host is updated, the f...
def update_library(self, showName=None):
if (sickbeard.USE_KODI and sickbeard.KODI_UPDATE_LIBRARY): if (not sickbeard.KODI_HOST): logger.log(u'No KODI hosts specified, check your settings', logger.DEBUG) return False result = 0 for host in [x.strip() for x in sickbeard.KODI_HOST.split(u',')...
'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):
trakt_id = sickbeard.indexerApi(ep_obj.show.indexer).config[u'trakt_id'] trakt_api = TraktAPI(sickbeard.SSL_VERIFY, sickbeard.TRAKT_TIMEOUT) if sickbeard.USE_TRAKT: try: data = {u'shows': [{u'title': ep_obj.show.name, u'year': ep_obj.show.startyear, u'ids': {}}]} if (trakt_id...
'Sends a request to trakt indicating that the given episode is part of our library. show_obj: The TVShow object to add to trakt s: season number e: episode number data_show: structured object of shows trakt type data_episode: structured object of episodes trakt type update: type o action add or remove'
def update_watchlist(self, show_obj=None, s=None, e=None, data_show=None, data_episode=None, update=u'add'):
trakt_api = TraktAPI(sickbeard.SSL_VERIFY, sickbeard.TRAKT_TIMEOUT) if sickbeard.USE_TRAKT: data = {} try: if (show_obj is not None): trakt_id = sickbeard.indexerApi(show_obj.indexer).config[u'trakt_id'] data = {u'shows': [{u'title': show_obj.name, u'y...
'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 blacklist_name: slug of trakt list used to hide not interested show Returns: True if the request succeeded, False otherwise'
def test_notify(self, username, blacklist_name=None):
try: trakt_api = TraktAPI(sickbeard.SSL_VERIFY, sickbeard.TRAKT_TIMEOUT) trakt_api.validateAccount() if (blacklist_name and (blacklist_name is not None)): trakt_lists = trakt_api.traktRequest(((u'users/' + username) + u'/lists')) found = False for trakt_li...
'Sends a pushover notification to the address provided msg: The message to send (six.text_type) title: The title of the message sound: The notification sound to use userKey: The pushover user id to send the message to (or to subscribe with) apiKey: The pushover api key to use returns: True if the message succeeded, Fal...
def _sendPushover(self, msg, title, sound=None, userKey=None, apiKey=None, priority=None):
if (userKey is None): userKey = sickbeard.PUSHOVER_USERKEY if (apiKey is None): apiKey = sickbeard.PUSHOVER_APIKEY if (sound is None): sound = sickbeard.PUSHOVER_SOUND if (priority is None): priority = sickbeard.PUSHOVER_PRIORITY logger.log((u'Pushover API KEY ...
'Sends a pushover notification based on the provided info or SR config title: The title of the notification to send message: The message string to send sound: The notification sound to use userKey: The userKey to send the notification to apiKey: The apiKey to use to send the notification force: Enforce sending, for ins...
def _notifyPushover(self, title, message, sound=None, userKey=None, apiKey=None, force=False):
if ((not sickbeard.USE_PUSHOVER) and (not force)): logger.log(u'Notification for Pushover not enabled, skipping this notification', logger.DEBUG) return False logger.log((u'Sending notification for ' + message), logger.DEBUG) return self._sendPushover(message, t...
'Send a notification that an episode was snatched ep_name: The name of the episode that was snatched title: The title of the notification (optional)'
def notify_snatch(self, ep_name, title=u'Snatched:'):
ep_name = ss(ep_name) if (sickbeard.USE_EMAIL and sickbeard.EMAIL_NOTIFY_ONSNATCH): show = self._parseEp(ep_name) to = self._generate_recipients(show) if (not to): logger.log(u'Skipping email notify because there are no configured recipients', logger.D...
'Send a notification that an episode was downloaded ep_name: The name of the episode that was downloaded title: The title of the notification (optional)'
def notify_download(self, ep_name, title=u'Completed:'):
ep_name = ss(ep_name) if (sickbeard.USE_EMAIL and sickbeard.EMAIL_NOTIFY_ONDOWNLOAD): show = self._parseEp(ep_name) to = self._generate_recipients(show) if (not to): logger.log(u'Skipping email notify because there are no configured recipients', logger...
'Send a notification that an subtitle was downloaded ep_name: The name of the episode that was downloaded lang: Subtitle language wanted'
def notify_subtitle_download(self, ep_name, lang, title=u'Downloaded subtitle:'):
ep_name = ss(ep_name) if (sickbeard.USE_EMAIL and sickbeard.EMAIL_NOTIFY_ONSUBTITLEDOWNLOAD): show = self._parseEp(ep_name) to = self._generate_recipients(show) if (not to): logger.log(u'Skipping email notify because there are no configured recipients'...
'Send a notification that SickRage was updated new_version: The commit SickRage was updated to'
def notify_git_update(self, new_version=u'??'):
if sickbeard.USE_EMAIL: to = self._generate_recipients(None) if (not to): logger.log(u'Skipping email notify because there are no configured recipients', logger.DEBUG) else: try: msg = MIMEMultipart(u'alternative') ...
'Send a notification that SickRage was logged into remotely ipaddress: The ip SickRage was logged into from'
def notify_login(self, ipaddress=u''):
if sickbeard.USE_EMAIL: to = self._generate_recipients(None) if (not len(to)): logger.log(u'Skipping email notify because there are no configured recipients', logger.DEBUG) else: try: msg = MIMEMultipart(u'alternative') ...
'Retrieves the NMJv2 database location from Popcorn hour host: The hostname/IP of the Popcorn Hour server dbloc: \'local\' for PCH internal hard drive. \'network\' for PCH network shares instance: Allows for selection of different DB in case of multiple databases Returns: True if the settings were retrieved successfull...
def notify_settings(self, host, dbloc, instance):
try: url_loc = u'http://{0}:8008/file_operation?arg0=list_user_storage_file&arg1=&arg2={1}&arg3=20&arg4=true&arg5=true&arg6=true&arg7=all&arg8=name_asc&arg9=false&arg10=false'.format(host, instance) req = urllib.request.Request(url_loc) handle1 = urllib.request.urlopen(req) response1...
'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 = ((((u'http://' + host) + u':8008/metadata_database?arg0=update_scandir&arg1=') + sickbeard.NMJv2_DATABASE) + u'&arg2=&arg3=update_all') logger.log(u'NMJ scan update command sent to host: {0}'.format(host), logger.DEBUG) url_updatedb = ((((u'http://' + ...
'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)): logger.log(u'Notification for NMJ scan update not enabled, skipping this notification', logger.DEBUG) return False if (not host): host = sickbeard.NMJv2_HOST logger.log(u'Sending scan command for N...
'Send a test notification :param id: The Device ID :param id: The User\'s API Key :returns: the notification'
def test_notify(self, id=None, apikey=None):
return self._notify_join(u'Test', u'This is a test notification from SickRage', id, apikey, force=True)
'Sends a Join notification :param title: The title of the notification to send :param msg: The message string to send :param id: The Device ID :param id: The User\'s API Key :returns: True if the message succeeded, False otherwise'
def _send_join_msg(self, title, msg, id=None, apikey=None):
id = (sickbeard.JOIN_ID if (id is None) else id) apikey = (sickbeard.JOIN_APIKEY if (apikey is None) else apikey) logger.log(u'Join in use with device ID: {0}'.format(id), logger.DEBUG) message = u'{0} : {1}'.format(title.encode(), msg.encode()) params = {u'apikey': apikey, u...
'Sends a Join notification when an episode is snatched :param ep_name: The name of the episode snatched :param title: The title of the notification to send'
def notify_snatch(self, ep_name, title=notifyStrings[NOTIFY_SNATCH]):
if sickbeard.JOIN_NOTIFY_ONSNATCH: self._notify_join(title, ep_name)
'Sends a Join notification when an episode is downloaded :param ep_name: The name of the episode downloaded :param title: The title of the notification to send'
def notify_download(self, ep_name, title=notifyStrings[NOTIFY_DOWNLOAD]):
if sickbeard.JOIN_NOTIFY_ONDOWNLOAD: self._notify_join(title, ep_name)
'Sends a Join notification when subtitles for an episode are downloaded :param ep_name: The name of the episode subtitles were downloaded for :param lang: The language of the downloaded subtitles :param title: The title of the notification to send'
def notify_subtitle_download(self, ep_name, lang, title=notifyStrings[NOTIFY_SUBTITLE_DOWNLOAD]):
if sickbeard.JOIN_NOTIFY_ONSUBTITLEDOWNLOAD: self._notify_join(title, u'{0}: {1}'.format(ep_name, lang))
'Sends a Join notification for git updates :param new_version: The new version available from git'
def notify_git_update(self, new_version=u'??'):
if sickbeard.USE_JOIN: update_text = notifyStrings[NOTIFY_GIT_UPDATE_TEXT] title = notifyStrings[NOTIFY_GIT_UPDATE] self._notify_join(title, (update_text + new_version))
'Sends a Join notification on login :param ipaddress: The IP address the login is originating from'
def notify_login(self, ipaddress=u''):
if sickbeard.USE_JOIN: update_text = notifyStrings[NOTIFY_LOGIN_TEXT] title = notifyStrings[NOTIFY_LOGIN] self._notify_join(title, update_text.format(ipaddress))
'Sends a Join notification :param title: The title of the notification to send :param message: The message string to send :param id: The Device ID :param id: The User\'s API Key :param force: Enforce sending, for instance for testing :returns: the message to send'
def _notify_join(self, title, message, id=None, apikey=None, force=False):
if (not (force or sickbeard.USE_JOIN)): logger.log(u'Notification for Join not enabled, skipping this notification', logger.DEBUG) return (False, u'Disabled') logger.log(u'Sending a Join message for {0}'.format(message), logger.DEBUG) return self._send_joi...
'Send a test notification :param id: The Telegram user/group id to send the message to :param api_key: Your Telegram bot API token :returns: the notification'
def test_notify(self, id=None, api_key=None):
return self._notify_telegram(u'Test', u'This is a test notification from SickRage', id, api_key, force=True)
'Sends a Telegram notification :param title: The title of the notification to send :param msg: The message string to send :param id: The Telegram user/group id to send the message to :param api_key: Your Telegram bot API token :returns: True if the message succeeded, False otherwise'
def _send_telegram_msg(self, title, msg, id=None, api_key=None):
id = (sickbeard.TELEGRAM_ID if (id is None) else id) api_key = (sickbeard.TELEGRAM_APIKEY if (api_key is None) else api_key) logger.log(u'Telegram in use with API KEY: {0}'.format(api_key), logger.DEBUG) message = u'{0} : {1}'.format(title.encode(), msg.encode()) payload = ur...
'Sends a Telegram notification when an episode is snatched :param ep_name: The name of the episode snatched :param title: The title of the notification to send'
def notify_snatch(self, ep_name, title=notifyStrings[NOTIFY_SNATCH]):
if sickbeard.TELEGRAM_NOTIFY_ONSNATCH: self._notify_telegram(title, ep_name)
'Sends a Telegram notification when an episode is downloaded :param ep_name: The name of the episode downloaded :param title: The title of the notification to send'
def notify_download(self, ep_name, title=notifyStrings[NOTIFY_DOWNLOAD]):
if sickbeard.TELEGRAM_NOTIFY_ONDOWNLOAD: self._notify_telegram(title, ep_name)
'Sends a Telegram notification when subtitles for an episode are downloaded :param ep_name: The name of the episode subtitles were downloaded for :param lang: The language of the downloaded subtitles :param title: The title of the notification to send'
def notify_subtitle_download(self, ep_name, lang, title=notifyStrings[NOTIFY_SUBTITLE_DOWNLOAD]):
if sickbeard.TELEGRAM_NOTIFY_ONSUBTITLEDOWNLOAD: self._notify_telegram(title, u'{0}: {1}'.format(ep_name, lang))
'Sends a Telegram notification for git updates :param new_version: The new version available from git'
def notify_git_update(self, new_version=u'??'):
if sickbeard.USE_TELEGRAM: update_text = notifyStrings[NOTIFY_GIT_UPDATE_TEXT] title = notifyStrings[NOTIFY_GIT_UPDATE] self._notify_telegram(title, (update_text + new_version))
'Sends a Telegram notification on login :param ipaddress: The ip address the login is originating from'
def notify_login(self, ipaddress=u''):
if sickbeard.USE_TELEGRAM: update_text = notifyStrings[NOTIFY_LOGIN_TEXT] title = notifyStrings[NOTIFY_LOGIN] self._notify_telegram(title, update_text.format(ipaddress))
'Sends a Telegram notification :param title: The title of the notification to send :param message: The message string to send :param id: The Telegram user/group id to send the message to :param api_key: Your Telegram bot API token :param force: Enforce sending, for instance for testing :returns: the message to send'
def _notify_telegram(self, title, message, id=None, api_key=None, force=False):
if (not (force or sickbeard.USE_TELEGRAM)): logger.log(u'Notification for Telegram not enabled, skipping this notification', logger.DEBUG) return (False, u'Disabled') logger.log(u'Sending a Telegram message for {0}'.format(message), logger.DEBUG) return se...
':rtype: object'
def __init__(self):
generic_queue.GenericQueue.__init__(self) self.queue_name = u'POSTPROCESSOR'
'Finds any item in the queue with the given directory and mode pair :param directory: directory to be processed by the task :param mode: processing type, auto/manual :return: instance of PostProcessorTask or None'
def find_in_queue(self, directory, mode):
for cur_item in (self.queue + [self.currentItem]): if (isinstance(cur_item, PostProcessorTask) and (cur_item.directory == directory) and (cur_item.mode == mode)): return cur_item return None
'Shows if the post processing queue is paused :return: bool'
@property def is_paused(self):
return (self.min_priority == generic_queue.QueuePriorities.HIGH)
'Pause the post processing queue'
@property def pause(self):
self.min_priority = generic_queue.QueuePriorities.HIGH return True
'Unpause the processing queue'
@property def unpause(self):
self.min_priority = 0
'Returns a dict showing how many auto and manual tasks are in the queue :return: dict'
def queue_length(self):
length = {u'auto': 0, u'manual': 0} for cur_item in (self.queue + [self.currentItem]): if isinstance(cur_item, PostProcessorTask): if (cur_item.mode == u'auto'): length[u'auto'] += 1 else: length[u'manual'] += 1 return length
'Adds a processing task to the queue :param directory: directory to process :param filename: release/nzb name if available :param method: processing method, copy/move/symlink/link :param force: force overwriting of existing files regardless of quality :param is_priority: whether to replace the file even if it exists at...
def add_item(self, directory, filename=None, method=None, force=False, is_priority=None, delete=None, failed=False, mode=u'auto', force_next=False):
replacements = dict(mode=mode.title(), directory=directory) if (not directory): return log_helper(u'{mode} post-processing attempted but directory is not set: {directory}'.format(**replacements), logger.WARNING) if (not ek(os.path.isabs, directory)): return log_helper...
':param directory: directory to process :param filename: release/nzb name if available :param method: processing method, copy/move/symlink/link :param force: force overwriting of existing files regardless of quality :param is_priority: whether to replace the file even if it exists at higher quality :param delete: delet...
def __init__(self, directory, filename=None, method=None, force=False, is_priority=None, delete=False, failed=False, mode=u'auto'):
super(PostProcessorTask, self).__init__(u'{mode}'.format(mode=mode.title()), (MANUAL_POST_PROCESS, AUTO_POST_PROCESS)[(mode == u'auto')]) self.directory = directory self.filename = filename self.method = method self.force = config.checkbox_to_value(force) self.is_priority = config.checkbox_to_va...
'Adjust settings for a task that is already in the queue :param directory: directory to process :param filename: release/nzb name if available :param method: processing method, copy/move/symlink/link :param force: force overwriting of existing files regardless of quality :param is_priority: whether to replace the file ...
def set_params(self, directory, filename=None, method=None, force=False, is_priority=None, delete=False, failed=False, mode=u'auto'):
self.directory = directory self.filename = filename self.method = method self.force = config.checkbox_to_value(force) self.is_priority = config.checkbox_to_value(is_priority) self.delete = config.checkbox_to_value(delete) self.failed = config.checkbox_to_value(failed) self.mode = mode
'Runs the task :return: None'
def run(self):
super(PostProcessorTask, self).run() try: logger.log(u'Beginning {mode} post processing task: {directory}'.format(mode=self.mode, directory=self.directory)) self.last_result = process_dir(process_path=self.directory, release_name=self.filename, process_method=self.method, force=se...
'Builds black and whitelist'
def load(self):
logger.log(u'Building black and white list for {id}'.format(id=self.show_id), logger.DEBUG) self.blacklist = self._load_list('blacklist') self.whitelist = self._load_list('whitelist')
'DB: Adds keywords into database for current show :param table: SQL table to add keywords to :param values: Values to be inserted in table'
def _add_keywords(self, table, values):
main_db_con = db.DBConnection() for value in values: main_db_con.action(((u'INSERT INTO [' + table) + u'] (show_id, keyword) VALUES (?,?)'), [self.show_id, value])
'Sets blacklist to new value :param values: Complete list of keywords to be set as blacklist'
def set_black_keywords(self, values):
self._del_all_keywords('blacklist') self._add_keywords('blacklist', values) self.blacklist = values logger.log(u'Blacklist set to: {blacklist}'.format(blacklist=self.blacklist), logger.DEBUG)
'Sets whitelist to new value :param values: Complete list of keywords to be set as whitelist'
def set_white_keywords(self, values):
self._del_all_keywords('whitelist') self._add_keywords('whitelist', values) self.whitelist = values logger.log(u'Whitelist set to: {whitelist}'.format(whitelist=self.whitelist), logger.DEBUG)
'DB: Remove all keywords for current show :param table: SQL table remove keywords from'
def _del_all_keywords(self, table):
main_db_con = db.DBConnection() main_db_con.action(((u'DELETE FROM [' + table) + u'] WHERE show_id = ?'), [self.show_id])
'DB: Fetch keywords for current show :param table: Table to fetch list of keywords from :return: keywords in list'
def _load_list(self, table):
main_db_con = db.DBConnection() sql_results = main_db_con.select(((u'SELECT keyword FROM [' + table) + u'] WHERE show_id = ?'), [self.show_id]) if ((not sql_results) or (not len(sql_results))): return [] groups = [] for result in sql_results: groups.append(result...
'Check if result is valid according to white/blacklist for current show :param result: Result to analyse :return: False if result is not allowed in white/blacklist, True if it is'
def is_valid(self, result):
if (self.whitelist or self.blacklist): if (not result.release_group): logger.log(u'Failed to detect release group, invalid result', logger.DEBUG) return False if (result.release_group.lower() in [x.lower() for x in self.whitelist]): white_result ...
'Delegate access to implementation'
def __getattr__(self, attr):
return getattr(self._instance, attr)
'Returns string values associated with Status prefix :param status: Status prefix to resolve :return: Human readable status value'
@staticmethod def _getStatusStrings(status):
to_return = {} for quality in Quality.qualityStrings: if (quality is not None): stat = Quality.statusPrefixes[status] qual = Quality.qualityStrings[quality] comp = Quality.compositeStatus(status, quality) to_return[comp] = u'{0} ({1})'.format(stat, qual...
'Return The quality from an episode File renamed by SickRage If no quality is achieved it will try scene_quality regex :param name: to parse :param anime: Boolean to indicate if the show we\'re resolving is Anime :return: Quality prefix'
@staticmethod def nameQuality(name, anime=False):
quality = Quality.scene_quality(name, anime) if (quality != Quality.UNKNOWN): return quality quality = Quality.qualityFromFileMeta(name) if (quality != Quality.UNKNOWN): return quality if name.lower().endswith(u'.ts'): return Quality.RAWHDTV else: return Quality.U...
'Return The quality from the scene episode File :param name: Episode filename to analyse :param anime: Boolean to indicate if the show we\'re resolving is Anime :return: Quality'
@staticmethod def scene_quality(name, anime=False):
if (not name): return Quality.UNKNOWN name = ek(path.basename, name) result = None ep = EpisodeTags(name) if anime: sd_options = tags.anime_sd.search(name) hd_options = tags.anime_hd.search(name) full_hd = tags.anime_fullhd.search(name) ep.rex['bluray'] = tags...
'Get quality file file metadata :param filename: Filename to analyse :return: Quality prefix'
@staticmethod def qualityFromFileMeta(filename):
height = video_screen_size(filename)[1] if (not height): return Quality.UNKNOWN base_filename = ek(path.basename, filename) bluray = (re.search(u'blue?-?ray|hddvd|b[rd](rip|mux)', base_filename, re.I) is not None) webdl = (re.search(u'web.?dl|web(rip|mux|hd)', base_filename, re.I) is not Non...
'Split a composite status code into a status and quality. :param status: to split :returns: a tuple containing (status, quality)'
@staticmethod def splitCompositeStatus(status):
status = int(status) if (status == UNKNOWN): return (UNKNOWN, Quality.UNKNOWN) for q in sorted(Quality.qualityStrings.keys(), reverse=True): if (status > (q * 100)): return ((status - (q * 100)), q) return (status, Quality.NONE)
'Get scene naming parameters from filename and quality :param name: Filename to check :param quality: int of quality to make sure we get the right rip type :return: encoder type for scene quality naming'
@staticmethod def sceneQualityFromName(name, quality):
codec_list = [u'xvid', u'divx'] x264_list = [u'x264', u'x 264', u'x.264'] h264_list = [u'h264', u'h 264', u'h.264', u'avc'] x265_list = [u'x265', u'x 265', u'x.265'] h265_list = [u'h265', u'h 265', u'h.265', u'hevc'] codec_list += (((x264_list + h264_list) + x265_list) + h265_list) ...
'Get a status object from filename :param name: Filename to check :param anime: boolean to enable anime parsing :return: Composite status/quality object'
@staticmethod def statusFromName(name, anime=False):
return Quality.compositeStatus(DOWNLOADED, Quality.nameQuality(name, anime))
'If the key is not found try to determine a status from Quality :param key: A numeric key or None :raise KeyError: if the key is invalid and can\'t be determined from Quality'
def __missing__(self, key):
key = self.numeric(key) if (key in self.qualities): (status, quality) = Quality.splitCompositeStatus(key) return (self[status] if (not quality) else (((self[status] + u' (') + Quality.qualityStrings[quality]) + u')')) else: raise KeyError(key)
'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 = item.get(u'description') if title: if self.descTitleStart.match(title): title = self.descTitleStart.sub(u'', title) title = self.descTitleEnd.sub(u'', title) title = title.replace(u'+', u'.') else: title = item.get(u'title') if ...
'Return The quality from the scene episode HTML row.'
@staticmethod def _episodeQuality(torrent_rows):
file_quality = torrent_rows(u'td')[1].find(u'a')[u'href'].replace(u'_', u' ') logger.log(u'Episode quality: {0}'.format(file_quality), logger.DEBUG) def checkName(options, func): return func([re.search(option, file_quality, re.I) for option in options]) dvdOptions = checkName([u'dvd', u...
'Return The quality from the scene episode HTML row.'
@staticmethod def _episodeQuality(torrent_rows):
file_quality = u'' img_all = torrent_rows(u'td')[1](u'img') if img_all: for img_type in img_all: try: file_quality = ((file_quality + u' ') + img_type[u'src'].replace(u'style_images/mkportal-636/', u'').replace(u'.gif', u'').replace(u'.png', u'')) except Ex...
'Generates a \'|\' delimited string of instance attributes, for saving to config.ini'
def configStr(self):
return ((((((((((((((((self.name + u'|') + self.url) + u'|') + self.key) + u'|') + self.catIDs) + u'|') + str(int(self.enabled))) + u'|') + self.search_mode) + u'|') + str(int(self.search_fallback))) + u'|') + str(int(self.enable_daily))) + u'|') + str(int(self.enable_backlog)))
'Checks if we have an image for this provider already. Returns found image or the default newznab image'
def image_name(self):
if ek(os.path.isfile, ek(os.path.join, sickbeard.PROG_DIR, u'gui', sickbeard.GUI_NAME, u'images', u'providers', (self.get_id() + u'.png'))): return (self.get_id() + u'.png') return u'newznab.png'
'Uses the newznab provider url and apikey to get the capabilities. Makes use of the default newznab caps param. e.a. http://yournewznab/api?t=caps&apikey=skdfiw7823sdkdsfjsfk Returns a tuple with (succes or not, array with dicts [{\'id\': \'5070\', \'name\': \'Anime\'}, {\'id\': \'5080\', \'name\': \'Documentary\'}, {\...
def get_newznab_categories(self, just_caps=False):
return_categories = [] if (not self._check_auth()): return (False, return_categories, u'Provider requires auth and your key is not set') url_params = {u't': u'caps'} if (self.needs_auth and self.key): url_params[u'apikey'] = self.key data = self.get_url(urljoi...
'Checks that user has set their api key if it is needed Returns: True/False'
def _check_auth(self):
if (self.needs_auth and (not self.key)): logger.log(u'Invalid api key. Check your settings', logger.WARNING) return False return True
'Checks that the returned data is valid Returns: _check_auth if valid otherwise False if there is an error'
def _check_auth_from_data(self, data):
if (data(u'categories') + data(u'item')): return self._check_auth() try: err_desc = data.error.attrs[u'description'] if (not err_desc): raise AttributeError except (AttributeError, TypeError): return self._check_auth() logger.log(ss(err_desc)) return False...