desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Searches indexer using the params in search_strings, either for latest releases, or a string/id search
Returns: list of results in dict form'
| def search(self, search_strings, age=0, ep_obj=None):
| results = []
if (not self._check_auth()):
return results
if (u'gingadaddy' not in self.url):
if (not self.caps):
self.get_newznab_categories(just_caps=True)
if (not self.caps):
return results
for mode in search_strings:
torznab = False
sear... |
'Gets size info from a result item
Returns int size or -1'
| def _get_size(self, item):
| return try_int(item.get(u'size', (-1)), (-1))
|
'Initialize the class'
| def __init__(self):
| TorrentProvider.__init__(self, u'Norbits')
self.username = None
self.passkey = None
self.minseed = None
self.minleech = None
self.cache = tvcache.TVCache(self, min_time=20)
self.url = u'https://norbits.net'
self.urls = {u'search': (self.url + u'/api2.php?action=torrents'), u'download': (... |
'Check that we are authenticated.'
| @staticmethod
def _check_auth_from_data(parsed_json):
| if ((u'status' in parsed_json) and (u'message' in parsed_json) and (parsed_json.get(u'status') == 3)):
logger.log(u'Invalid username or password. Check your settings', logger.WARNING)
return True
|
'Do the actual searching and JSON parsing'
| def search(self, search_params, age=0, ep_obj=None):
| results = []
for mode in search_params:
items = []
logger.log(u'Search Mode: {0}'.format(mode), logger.DEBUG)
for search_string in search_params[mode]:
if (mode != u'RSS'):
logger.log(u'Search string: {0}'.format(search_string.decode(u'utf-8')), lo... |
'Search query:
http://www.newpct.com/index.php?l=doSearch&q=fringe&category_=All&idioma_=1&bus_de_=All
q => Show name
category_ = Category \'Shows\' (767)
idioma_ = Language Spanish (1), All
bus_de_ = Date from (All, mes, semana, ayer, hoy)'
| def search(self, search_strings, age=0, ep_obj=None):
| results = []
lang_info = (u'' if ((not ep_obj) or (not ep_obj.show)) else ep_obj.show.lang)
search_params = {u'l': u'doSearch', u'q': u'', u'category_': u'All', u'idioma_': 1, u'bus_de_': u'All'}
for mode in search_strings:
items = []
logger.log(u'Search Mode: {0}'.format(mode), lo... |
'returns=\'content\' when trying access to torrent info (For calling torrent client). Previously we must parse
the URL to get torrent file'
| def get_url(self, url, post_data=None, params=None, timeout=30, **kwargs):
| trickery = kwargs.pop(u'returns', u'')
if (trickery == u'content'):
kwargs[u'returns'] = u'text'
data = super(newpctProvider, self).get_url(url, post_data=post_data, params=params, timeout=timeout, **kwargs)
url = re.search(u'http://tumejorserie.com/descargar/.+\\.torrent', data, re.DOTA... |
'Save the result to disk.'
| def download_result(self, result):
| if (not self.login()):
return False
(urls, filename) = self._make_url(result)
for url in urls:
data = self.get_url(url, returns=u'text')
url_torrent = re.search(u'http://tumejorserie.com/descargar/.+\\.torrent', data, re.DOTALL).group()
if url_torrent.startswith(u'http'):
... |
'Check that we are authenticated.'
| @staticmethod
def _check_auth_from_data(parsed_json):
| if ((u'status' in parsed_json) and (u'message' in parsed_json) and (parsed_json.get(u'status') == 5)):
logger.log(u'Invalid username or password. Check your settings', logger.WARNING)
return True
|
'DEPRECATED: Check for existence of key
:param key: A numeric key
:return: True if key is found, else False'
| def has_key(self, key):
| return (key in self)
|
'Create a copy of a NumDict
:return: A copy'
| def copy(self):
| if (self.__class__ is NumDict):
return NumDict(self.data.copy())
import copy
data = self.data
try:
self.data = {}
c = copy.copy(self)
finally:
self.data = data
c.update(self)
return c
|
'Build a NumDict from a dictionary
:param iterable:
:param value:
:return:'
| @classmethod
def fromkeys(cls, iterable, value=None):
| d = cls()
for key in iterable:
key = cls.numeric(key)
d[key] = value
return d
|
'Converts a key to its numeric representation
:param key: numeric dict key
:raise KeyError: if key can\'t be converted to an integer
:return: a numeric key
:rtype: int'
| @staticmethod
def numeric(key):
| try:
return int(key)
except (TypeError, ValueError):
if (key is not None):
raise KeyError(key)
|
'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=u''):
| 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=u''):
| 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, remote_ip=u'127.0.0.1'):
| 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(remote_ip) for x in (self._errors + self._messages) if x.is_new(remote_ip)]
|
'Returns True if the notification hasn\'t been displayed to the current client (aka IP address).'
| def is_new(self, remote_ip=u'127.0.0.1'):
| return (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, remote_ip=u'127.0.0.1'):
| self._seen.append(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.'
| @property
def show_name(self):
| return (self.show.name if self.show else self.showDir.rsplit(os.sep)[(-1)])
|
'Returns True if we\'ve gotten far enough to have a show object, or False
if we still only know the folder name.'
| @property
def is_loading(self):
| return ((self.show not in sickbeard.showList) or (not self.show))
|
'Actually runs the thread to process events'
| def run(self):
| try:
while (not self.stop.is_set()):
try:
type = self.queue.get(True, 1)
self.callback(type)
self.queue.task_done()
except Empty:
type = None
self.stop.clear()
except Exception as e:
logger.log((((u'E... |
'Check how long we have until we run again
:return: timedelta'
| def timeLeft(self):
| if self.isAlive():
if (self.start_time is None):
delta = (datetime.datetime.now() - self.lastRun)
return ((self.cycleTime - delta), self.cycleTime)[(delta > self.cycleTime)]
else:
time_now = datetime.datetime.now()
start_time_today = datetime.datetime.... |
'Runs the thread'
| def run(self):
| try:
while (not self.stop.is_set()):
if self.enable:
current_time = datetime.datetime.now()
should_run = False
if self.force:
should_run = True
elif ((current_time - self.lastRun) >= self.cycleTime):
... |
'Initializes the utorrent client class and sets the url, username, and password'
| def __init__(self, host=None, username=None, password=None):
| super(uTorrentAPI, self).__init__(u'uTorrent', host, username, password)
self.url = urljoin(self.host, u'gui/')
|
'Overrides the parent _request method to add the auth token'
| def _request(self, method=u'get', params=None, data=None, files=None, cookies=None):
| ordered_params = OrderedDict({u'token': self.auth})
for (k, v) in (six.iteritems(params) or {}):
ordered_params.update({k: v})
return super(uTorrentAPI, self)._request(method=method, params=ordered_params, data=data, files=files, cookies=cookies)
|
'Makes a request to the token url to get a CSRF token'
| def _get_auth(self):
| try:
self.response = self.session.get(urljoin(self.url, u'token.html'), verify=False)
self.response.raise_for_status()
self.auth = re.findall(u'<div.*?>(.*?)</', self.response.text)[0]
except Exception as error:
sickbeard.helpers.handle_requests_exception(error)
self.auth... |
'Adds a torrent either by magnet or url
params: :result: an instance of the searchResult class'
| def _add_torrent_uri(self, result):
| params = {u'action': u'add-url', u's': result.url}
return self._request(params=params)
|
'Adds a torrent file from memory
params: :result: an instance of the searchResult class'
| def _add_torrent_file(self, result):
| params = {u'action': u'add-file'}
files = {u'torrent_file': ((result.name + u'.torrent'), result.content)}
return self._request(method=u'post', params=params, files=files)
|
'Sets a label on an existing torrent in the client
params: :result: an instance of the searchResult class'
| def _set_torrent_label(self, result):
| label = ((sickbeard.TORRENT_LABEL_ANIME or sickbeard.TORRENT_LABEL) if result.show.is_anime else sickbeard.TORRENT_LABEL)
params = {u'action': u'setprops', u'hash': result.hash, u's': u'label', u'v': label}
return self._request(params=params)
|
'Sets the desired seed ratio for an existing torrent in the client
params: :result: an instance of the searchResult class'
| def _set_torrent_ratio(self, result):
| if (result.ratio in (None, u'')):
return True
params = {u'action': u'setprops', u'hash': result.hash, u's': u'seed_override', u'v': u'1'}
if (not self._request(params=params)):
return False
params = {u'action': u'setprops', u'hash': result.hash, u's': u'seed_ratio', u'v': (float(result.r... |
'Sets the amount of time a torrent that exists in the client should seed for
params: :result: an instance of the searchResult class'
| def _set_torrent_seed_time(self, result):
| if (not sickbeard.TORRENT_SEED_TIME):
return True
params = {u'action': u'setprops', u'hash': result.hash, u's': u'seed_override', u'v': u'1'}
if (not self._request(params=params)):
return False
params = {u'action': u'setprops', u'hash': result.hash, u's': u'seed_time', u'v': (3600 * floa... |
'Sets the priority of a torrent that exists in the client
params: :result: an instance of the searchResult class'
| def _set_torrent_priority(self, result):
| if (not result.priority):
return True
params = {u'action': u'queuetop', u'hash': result.hash}
return self._request(params=params)
|
'Pauses a torrent that exists on the client
params: :result: an instance of the searchResult class'
| def _set_torrent_pause(self, result):
| params = {u'action': (u'pause' if sickbeard.TORRENT_PAUSED else u'start'), u'hash': result.hash}
return self._request(params=params)
|
'Initializes the client
:name: str:name of the client
:host: str:url or ip of the client
:username: str: username for authenticating with the client
:password: str: password for authentication with the client'
| def __init__(self, name, host=None, username=None, password=None):
| self.name = name
self.username = (sickbeard.TORRENT_USERNAME if (not username) else username)
self.password = (sickbeard.TORRENT_PASSWORD if (not password) else password)
self.host = (sickbeard.TORRENT_HOST if (not host) else host)
self.url = None
self.response = None
self.auth = None
se... |
'Makes the actual request for the client, for everything except auth'
| def _request(self, method=u'get', params=None, data=None, files=None, cookies=None):
| if ((time.time() > (self.last_time + 1800)) or (not self.auth)):
self.last_time = time.time()
self._get_auth()
log_string = u'{0}: Requested a {1} connection to url {2}'.format(self.name, method.upper(), self.url)
if params:
log_string += u'?{0}'.format(urlencode... |
'This should be overridden and should return the auth_id needed for the client'
| def _get_auth(self):
| return None
|
'This should be overridden should return the True/False from the client
when a torrent is added via url (magnet or .torrent link)'
| def _add_torrent_uri(self, result):
| return False
|
'This should be overridden should return the True/False from the client
when a torrent is added via result.content (only .torrent file)'
| def _add_torrent_file(self, result):
| return False
|
'This should be overridden should return the True/False from the client
when a torrent is set with label'
| def _set_torrent_label(self, result):
| return True
|
'This should be overridden should return the True/False from the client
when a torrent is set with ratio'
| def _set_torrent_ratio(self, result):
| return True
|
'This should be overridden should return the True/False from the client
when a torrent is set with a seed time'
| def _set_torrent_seed_time(self, result):
| return True
|
'This should be overriden should return the True/False from the client
when a torrent is set with result.priority (-1 = low, 0 = normal, 1 = high)'
| def _set_torrent_priority(self, result):
| return True
|
'This should be overridden should return the True/False from the client
when a torrent is set with path'
| def _set_torrent_path(self, torrent_path):
| return True
|
'This should be overridden should return the True/False from the client
when a torrent is set with pause
params: :result: an instance of the searchResult class'
| def _set_torrent_pause(self, result):
| return True
|
'Gets the torrent hash from either the magnet or torrent file content
params: :result: an instance of the searchResult class'
| @staticmethod
def _get_torrent_hash(result):
| if result.url.startswith(u'magnet'):
result.hash = re.findall(u'urn:btih:([\\w]{32,40})', result.url)[0]
if (len(result.hash) == 32):
result.hash = b16encode(b32decode(result.hash)).lower()
else:
if (not result.content):
logger.log(u'Torrent without content'... |
'Sends the magnet, url, or torrent file content to the client
params: :result: an instance of the searchResult class'
| def sendTORRENT(self, result):
| r_code = False
logger.log(u'Calling {0} Client'.format(self.name), logger.DEBUG)
if (not (self.auth or self._get_auth())):
logger.log(u'{0}: Authentication Failed'.format(self.name), logger.WARNING)
return r_code
try:
result.ratio = result.provider.seed_ratio()
... |
'Tests the parameters the user has provided in the ui to see if they are correct'
| def testAuthentication(self):
| try:
self.response = self.session.get(self.url, timeout=120, verify=False)
except Exception:
pass
try:
self._get_auth()
if (not self.response):
raise HTTPError(404, u'Not Found')
self.response.raise_for_status()
if self.auth:
return ... |
'Initializes the DownloadStation client
params: :host: Url to the Download Station API
:username: Username to use for authentication
:password: Password to use for authentication'
| def __init__(self, host=None, username=None, password=None):
| super(DownloadStationAPI, self).__init__(u'DownloadStation', host, username, password)
self.urls = {u'login': urljoin(self.host, u'webapi/auth.cgi'), u'task': urljoin(self.host, u'webapi/DownloadStation/task.cgi')}
self.url = self.urls[u'task']
generic_errors = {100: u'Unknown error', 101: u'Invalid ... |
'Checks the response from Download Station, and logs any errors
params: :data: post data sent in the original request, in case we need to send it with adjusted parameters
:file: file data being sent with the post request, if any'
| def _check_response(self, data=None, files=None):
| try:
jdata = self.response.json()
except (ValueError, AttributeError):
logger.log(u'Could not convert response to json, check the host:port: {0!r}'.format(self.response))
return False
if (not jdata.get(u'success')):
error_code = jdata.get(u'error', ... |
'Authenticates the session with DownloadStation'
| def _get_auth(self):
| if (self.session.cookies and self.auth):
return self.auth
params = {u'api': u'SYNO.API.Auth', u'version': 2, u'method': u'login', u'account': (self.username.encode(u'utf-8') if isinstance(self.username, six.text_type) else self.username), u'passwd': (self.password.encode(u'utf-8') if isinstance(self.pas... |
'Sends a magnet, Torrent url or NZB url to DownloadStation
params: :result: an object subclassing sickbeard.classes.SearchResult'
| def _add_torrent_uri(self, result):
| data = self._task_post_data
data[u'uri'] = result.url
if (result.resultType == u'torrent'):
if sickbeard.TORRENT_PATH:
data[u'destination'] = sickbeard.TORRENT_PATH
elif sickbeard.SYNOLOGY_DSM_PATH:
data[u'destination'] = sickbeard.SYNOLOGY_DSM_PATH
self._request(method=u... |
'Sends a Torrent file or NZB file to DownloadStation
params: :result: an object subclassing sickbeard.classes.SearchResult'
| def _add_torrent_file(self, result):
| data = self._task_post_data
if (result.resultType == u'torrent'):
files = {u'file': ((result.name + u'.torrent'), result.content)}
if sickbeard.TORRENT_PATH:
data[u'destination'] = sickbeard.TORRENT_PATH
else:
files = {u'file': ((result.name + u'.nzb'), result.extraInfo[0... |
'Sends an NZB to DownloadStation
params: :result: an object subclassing sickbeard.classes.SearchResult'
| def sendNZB(self, result):
| logger.log(u'Calling {0} Client'.format(self.name), logger.DEBUG)
if (not (self.auth or self._get_auth())):
logger.log(u'{0}: Authentication Failed'.format(self.name), logger.WARNING)
return False
if (result.resultType == u'nzb'):
return self._add_torrent_uri(result)
... |
':param dirName: Full path to the folder of the failed download
:param nzbName: Full name of the nzb file that failed'
| def __init__(self, dirName, nzbName):
| self.dir_name = dirName
self.nzb_name = nzbName
self.log = u''
|
'Do the actual work
:return: True'
| def process(self):
| self._log(((((u'Failed download detected: (' + str(self.nzb_name)) + u', ') + str(self.dir_name)) + u')'))
releaseName = show_name_helpers.determineReleaseName(self.dir_name, self.nzb_name)
if (not releaseName):
self._log(u'Warning: unable to find a valid release nam... |
'Log to regular logfile and save for return for PP script log'
| def _log(self, message, level=logger.INFO):
| logger.log(message, level)
self.log += (message + u'\n')
|
'Display time in SR format
TODO: Rename this to srftime
:param dt: datetime object
:param show_seconds: Boolean, show seconds
:param t_preset: Preset time format
:return: time string'
| @static_or_instance
def sbftime(self, dt=None, show_seconds=False, t_preset=None):
| try:
locale.setlocale(locale.LC_TIME, u'')
except Exception:
pass
try:
if sbdatetime.has_locale:
locale.setlocale(locale.LC_TIME, u'en_US')
except Exception:
try:
if sbdatetime.has_locale:
locale.setlocale(locale.LC_TIME, sbdatetime... |
'Display date in SR format
TODO: Rename this to srfdate
:param dt: datetime object
:param d_preset: Preset date format
:return: date string'
| @static_or_instance
def sbfdate(self, dt=None, d_preset=None):
| try:
locale.setlocale(locale.LC_TIME, u'')
except Exception:
pass
strd = u''
try:
if (self is None):
if (dt is not None):
if (d_preset is not None):
strd = dt.strftime(d_preset)
else:
strd = dt.st... |
'Show datetime in SR format
TODO: Rename this to srfdatetime
:param dt: datetime object
:param show_seconds: Boolean, show seconds as well
:param d_preset: Preset date format
:param t_preset: Preset time format
:return: datetime string'
| @static_or_instance
def sbfdatetime(self, dt=None, show_seconds=False, d_preset=None, t_preset=None):
| try:
locale.setlocale(locale.LC_TIME, u'')
except Exception:
pass
strd = u''
try:
if (self is None):
if (dt is not None):
if (d_preset is not None):
strd = dt.strftime(d_preset)
else:
strd = dt.st... |
'Sets the last update date for the current provider in the cache database
:param to_date: date to set to, or None for today'
| def set_last_update(self, to_date=None):
| if (not to_date):
to_date = datetime.datetime.today()
cache_db_con = self._get_db()
cache_db_con.upsert(u'lastUpdate', {u'time': int(time.mktime(to_date.timetuple()))}, {u'provider': self.provider_id})
|
'Sets the last search date for the current provider in the cache database
:param to_date: date to set to, or None for today'
| def set_last_search(self, to_date=None):
| if (not to_date):
to_date = datetime.datetime.today()
cache_db_con = self._get_db()
cache_db_con.upsert(u'lastSearch', {u'time': int(time.mktime(to_date.timetuple()))}, {u'provider': self.provider_id})
|
'Sends a request to trakt indicating that the given show and all its episodes is part of our library.
show_obj: The TVShow object to add to trakt'
| def addShowToTraktLibrary(self, show_obj):
| data = {}
if (not self.findShow(show_obj.indexer, show_obj.indexerid)):
trakt_id = sickbeard.indexerApi(show_obj.indexer).config[u'trakt_id']
data = {u'shows': [{u'title': show_obj.name, u'year': show_obj.startyear, u'ids': {}}]}
if (trakt_id == u'tvdb_id'):
data[u'shows'][0]... |
'Sets episodes to wanted that are in trakt watchlist'
| def updateEpisodes(self):
| logger.log(u'SHOW_WATCHLIST::CHECK::START - Trakt Episode Watchlist', logger.DEBUG)
self._getEpisodeWatchlist()
if (not self.EpisodeWatchlist):
logger.log(u'No episode found in your watchlist, aborting episode update', logger.DEBUG)
return
managed_show... |
'Adds a new show with the default settings'
| @staticmethod
def addDefaultShow(indexer, indexer_id, name, status):
| if (not Show.find(sickbeard.showList, int(indexer_id))):
logger.log((u'Adding show ' + str(indexer_id)))
root_dirs = sickbeard.ROOT_DIRS.split(u'|')
try:
location = root_dirs[(int(root_dirs[0]) + 1)]
except Exception:
location = None
if location:... |
'Check in the Watchlist or CollectionList for Show
Is the Show, Season and Episode in the trakt_id list (tvdb / tvrage)'
| def _checkInList(self, trakt_id, showid, season, episode, List=None):
| if (u'Collection' == List):
try:
if (self.Collectionlist[trakt_id][showid][u'seasons'][season][u'episodes'][episode] == episode):
return True
except Exception:
return False
elif (u'Show' == List):
try:
if (self.ShowWatchlist[trakt_id][s... |
'Get Watchlist and parse once into addressable structure'
| def _getShowWatchlist(self):
| try:
self.ShowWatchlist = {u'tvdb_id': {}, u'tvrage_id': {}}
TraktShowWatchlist = self.trakt_api.traktRequest(u'sync/watchlist/shows')
tvdb_id = u'tvdb'
tvrage_id = u'tvrage'
for watchlist_el in TraktShowWatchlist:
tvdb = False
tvrage = False
... |
'Get Watchlist and parse once into addressable structure'
| def _getEpisodeWatchlist(self):
| try:
self.EpisodeWatchlist = {u'tvdb_id': {}, u'tvrage_id': {}}
TraktEpisodeWatchlist = self.trakt_api.traktRequest(u'sync/watchlist/episodes')
tvdb_id = u'tvdb'
tvrage_id = u'tvrage'
for watchlist_el in TraktEpisodeWatchlist:
tvdb = False
tvrage = Fal... |
'Get Collection and parse once into addressable structure'
| def _getShowCollection(self):
| try:
self.Collectionlist = {u'tvdb_id': {}, u'tvrage_id': {}}
logger.log(u'Getting Show Collection', logger.DEBUG)
TraktCollectionList = self.trakt_api.traktRequest(u'sync/collection/shows')
tvdb_id = u'tvdb'
tvrage_id = u'tvrage'
for watchlist_el in TraktCollec... |
'Build the JSON structure to send back to Trakt'
| @staticmethod
def trakt_bulk_data_generate(data):
| uniqueShows = {}
uniqueSeasons = {}
for (showid, indexerid, show_name, startyear, season, episode) in data:
if (showid not in uniqueShows):
uniqueShows[showid] = {u'title': show_name, u'year': startyear, u'ids': {}, u'seasons': []}
trakt_id = sickbeard.indexerApi(indexerid).c... |
'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_... | @staticmethod
def clean_series_name(series_name):
| series_name = re.sub(u'(\\D)\\.(?!\\s)(\\D)', u'\\1 \\2', series_name)
series_name = re.sub(u'(\\d)\\.(\\d{4})', u'\\1 \\2', series_name)
series_name = re.sub(u'(\\D)\\.(?!\\s)', u'\\1 ', series_name)
series_name = re.sub(u'\\.(?!\\s)(\\D)', u' \\1', series_name)
series_name = series_nam... |
'Convert org_number into an integer
org_number: integer or representation of a number: string or six.text_type
Try force converting to int first, on error try converting from Roman numerals
returns integer or 0'
| @staticmethod
def _convert_number(org_number):
| try:
if org_number:
number = int(org_number)
else:
number = 0
except Exception:
roman_to_int_map = ((u'M', 1000), (u'CM', 900), (u'D', 500), (u'CD', 400), (u'C', 100), (u'XC', 90), (u'L', 50), (u'XL', 40), (u'X', 10), (u'IX', 9), (u'V', 5), (u'IV', 4), (u'I', 1))
... |
'Start looking for new propers
:param force: Start even if already running (currently not used, defaults to False)'
| def run(self, force=False):
| logger.log(u'Beginning the search for new propers')
self.amActive = True
propers = self._getProperList()
if propers:
self._downloadPropers(propers)
self._set_lastProperSearch(datetime.datetime.today().toordinal())
run_at = u''
if (None is sickbeard.properFinderSchedule... |
'Walk providers for propers'
| def _getProperList(self):
| propers = {}
search_date = (datetime.datetime.today() - datetime.timedelta(days=2))
origThreadName = threading.currentThread().name
providers = [x for x in sickbeard.providers.sortedProviderList(sickbeard.RANDOMIZE_PROVIDERS) if x.is_active()]
for curProvider in providers:
threading.currentT... |
'Download proper (snatch it)
:param properList:'
| def _downloadPropers(self, properList):
| for curProper in properList:
historyLimit = (datetime.datetime.today() - datetime.timedelta(days=30))
main_db_con = db.DBConnection()
historyResults = main_db_con.select(((((u'SELECT resource FROM history ' + u'WHERE showid = ? AND season = ? AND episod... |
'Record last propersearch in DB
:param when: When was the last proper search'
| @staticmethod
def _set_lastProperSearch(when):
| logger.log((u'Setting the last Proper search in the DB to ' + str(when)), logger.DEBUG)
main_db_con = db.DBConnection()
sql_results = main_db_con.select(u'SELECT last_proper_search FROM info')
if (not sql_results):
main_db_con.action(u'INSERT INTO info ... |
'Find last propersearch from DB'
| @staticmethod
def _get_lastProperSearch():
| main_db_con = db.DBConnection()
sql_results = main_db_con.select(u'SELECT last_proper_search FROM info')
try:
last_proper_search = datetime.date.fromordinal(int(sql_results[0]['last_proper_search']))
except Exception:
return datetime.date.fromordinal(1)
return last_proper_se... |
'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 &= (~ (1 << 5))
result |= (1 << 8)
if (result & (1 << 4)):
result &= (~ (1 << 4))
result |= (1 << 7)
if (result & (1 << 3)):
result &= (~ (1 << 3))
result |= (1 << 5)
return 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
|
'Strips censored items from string
:param record: to censor'
| def format(self, record):
| msg = super(CensoredFormatter, self).format(record)
if (not isinstance(msg, six.text_type)):
msg = msg.decode(self.encoding, u'replace')
censored = {item for (_, item) in six.iteritems(censored_items) if item}
censored = (censored | {quote(item) for item in censored})
censored = list({(item.... |
'Initialize logging
:param console_logging: True if logging to console
:param file_logging: True if logging to file
:param debug_logging: True if debug logging is enabled
:param database_logging: True if logging database access'
| def init_logging(self, console_logging=False, file_logging=False, debug_logging=False, database_logging=False):
| self.log_file = (self.log_file or ek(os.path.join, sickbeard.LOG_DIR, u'sickrage.log'))
global log_file
log_file = self.log_file
self.debug_logging = debug_logging
self.console_logging = console_logging
self.file_logging = file_logging
self.database_logging = database_logging
logging.add... |
'Shut down the logger'
| @staticmethod
def shutdown():
| logging.shutdown()
|
'Create log entry
:param msg: to log
:param level: of log, e.g. DEBUG, INFO, etc.
:param args: to pass to logger
:param kwargs: to pass to logger'
| def log(self, msg, level=INFO, *args, **kwargs):
| cur_thread = threading.currentThread().getName()
cur_hash = u''
if ((level == ERROR) and sickbeard.CUR_COMMIT_HASH and (len(sickbeard.CUR_COMMIT_HASH) > 6)):
cur_hash = u'[{0}] '.format(sickbeard.CUR_COMMIT_HASH[:7])
message = u'{thread} :: {hash}{message}'.format(thread=cur_thread, has... |
'Get the Overview status from the Episode status
:param epStatus: an Episode status
:return: an Overview status'
| def getOverview(self, epStatus):
| ep_status = (try_int(epStatus) or UNKNOWN)
if (ep_status == WANTED):
return Overview.WANTED
elif (ep_status in (UNAIRED, UNKNOWN)):
return Overview.UNAIRED
elif (ep_status in (SKIPPED, IGNORED)):
return Overview.SKIPPED
elif (ep_status in Quality.ARCHIVED):
return Ove... |
'Look for subtitles files and refresh the subtitles property'
| def refreshSubtitles(self):
| (self.subtitles, save_subtitles) = subtitles.refresh_subtitles(self)
if save_subtitles:
self.saveToDB()
|
'Creates SQL queue for this episode if any of its data has been changed since the last save.
forceSave: If True it will create SQL queue even if no data has been changed since the
last save (aka if the record is not dirty).'
| def get_sql(self, forceSave=False):
| try:
if ((not self.dirty) and (not forceSave)):
logger.log((str(self.show.indexerid) + u': Not creating SQL queue - record is not dirty'), logger.DEBUG)
return
main_db_con = db.DBConnection()
rows = main_db_con.select(u'SELECT episode_id,... |
'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)):
return
newValueDict = {u'indexerid': self.indexerid, u'indexer': self.indexer, u'name': self.name, u'description': self.description, u'subtitles': u','.join(self.subtitles), u'subtitles_searchcount': self.subtitles_searchcount, u'subtitles_lastsearch': self.sub... |
'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):
| if (self.show.anime and (not self.show.scene)):
return self._format_pattern(u'%SN - %AB - %EN')
elif self.show.air_by_date:
return self._format_pattern(u'%SN - %AD - %EN')
return self._format_pattern(u'%SN - S%0SE%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 = u'(.*) \\(\\d{1,2}\\)'
self.relatedEps = sorted(self.relatedEps, key=(lambda x: x.episode))
if (not self.relatedEps):
goodName = self.name
else:
goodName = u''
singleName = True
curGoodName = None
for curName in ([self.name] + [x.name for x in ... |
'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(u'[ -]', u'_', name)
def release_name(name):
if name:
name = helpers.remove_non_release_groups(remove_extension(name))
return name
def release_gr... |
'Replaces all template strings with the correct value'
| @staticmethod
def _format_string(pattern, replace_map):
| result_name = pattern
for cur_replacement in sorted(replace_map.keys(), reverse=True):
result_name = result_name.replace(cur_replacement, sanitize_filename(replace_map[cur_replacement]))
result_name = result_name.replace(cur_replacement.lower(), sanitize_filename(replace_map[cur_replacement].low... |
'Manipulates an episode naming pattern and then fills the template in'
| def _format_pattern(self, pattern=None, multi=None, anime_type=None):
| if (pattern is None):
pattern = sickbeard.NAMING_PATTERN
if (multi is None):
multi = sickbeard.NAMING_MULTI_EP
if sickbeard.NAMING_CUSTOM_ANIME:
if (anime_type is None):
anime_type = sickbeard.NAMING_ANIME
else:
anime_type = 3
replace_map = self._replace_m... |
'Figures out the path where this episode SHOULD live according to the renaming rules, relative from the show dir'
| def proper_path(self):
| anime_type = sickbeard.NAMING_ANIME
if (not self.show.is_anime):
anime_type = 3
result = self.formatted_filename(anime_type=anime_type)
if (not (self.show.season_folders or sickbeard.NAMING_FORCE_FOLDERS)):
return result
else:
result = ek(os.path.join, self.formatted_dir(anim... |
'Just the folder name of the episode'
| def formatted_dir(self, pattern=None, multi=None, anime_type=None):
| if (pattern is None):
if (self.show.air_by_date and sickbeard.NAMING_CUSTOM_ABD and (not self.relatedEps)):
pattern = sickbeard.NAMING_ABD_PATTERN
elif (self.show.sports and sickbeard.NAMING_CUSTOM_SPORTS and (not self.relatedEps)):
pattern = sickbeard.NAMING_SPORTS_PATTERN
... |
'Just the filename of the episode, formatted based on the naming settings'
| def formatted_filename(self, pattern=None, multi=None, anime_type=None):
| if (pattern is None):
if (self.show.air_by_date and sickbeard.NAMING_CUSTOM_ABD and (not self.relatedEps)):
pattern = sickbeard.NAMING_ABD_PATTERN
elif (self.show.sports and sickbeard.NAMING_CUSTOM_SPORTS and (not self.relatedEps)):
pattern = sickbeard.NAMING_SPORTS_PATTERN
... |
'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(os.path.isfile, self.location)):
logger.log(((u"Can't perform rename on " + self.location) + u" when it doesn't exist, skipping"), logger.WARNING)
return
proper_path = self.proper_path()
absolute_proper_path = ek(os.path.join, self.show.location, proper_... |
'Make the modify date and time of a file reflect the show air date and time.
Note: Also called from postProcessor'
| def airdateModifyStamp(self):
| if (not all([sickbeard.AIRDATE_EPISODES, self.airdate, self.location, self.show, self.show.airs, self.show.network])):
return
try:
airdate_ordinal = self.airdate.toordinal()
if (airdate_ordinal < 1):
return
airdatetime = network_timezones.parse_date_time(airdate_ordin... |
'Pauses this queue'
| def pause(self):
| logger.log(u'Pausing queue')
self.min_priority = 999999999999
|
'Unpauses this queue'
| def unpause(self):
| logger.log(u'Unpausing queue')
self.min_priority = 0
|
'Adds an item to this queue
:param item: Queue object to add
:return: item'
| def add_item(self, item):
| with self.lock:
item.added = datetime.datetime.now()
self.queue.append(item)
return item
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.