本文整理汇总了Python中sickrage.helper.exceptions.ex函数的典型用法代码示例。如果您正苦于以下问题:Python ex函数的具体用法?Python ex怎么用?Python ex使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ex函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: test_encoding
def test_encoding(self):
"""
Test encoding
"""
root_dir = 'C:\\Temp\\TV'
strings = [u'Les Enfants De La T\xe9l\xe9', u'RT� One']
sickbeard.SYS_ENCODING = None
try:
locale.setlocale(locale.LC_ALL, "")
sickbeard.SYS_ENCODING = locale.getpreferredencoding()
except (locale.Error, IOError):
pass
# For OSes that are poorly configured I'll just randomly force UTF-8
if not sickbeard.SYS_ENCODING or sickbeard.SYS_ENCODING in ('ANSI_X3.4-1968', 'US-ASCII', 'ASCII'):
sickbeard.SYS_ENCODING = 'UTF-8'
for test in strings:
try:
show_dir = ek(os.path.join, root_dir, sanitize_filename(test))
self.assertTrue(isinstance(show_dir, unicode))
except Exception as error: # pylint: disable=broad-except
ex(error)
开发者ID:feld,项目名称:SickRage,代码行数:25,代码来源:encoding_tests.py
示例2: test_notify
def test_notify(self, username, blacklist_name=None):
"""
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
"""
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("users/" + username + "/lists")
found = False
for trakt_list in trakt_lists:
if trakt_list['ids']['slug'] == blacklist_name:
return "Test notice sent successfully to Trakt"
if not found:
return "Trakt blacklist doesn't exists"
else:
return "Test notice sent successfully to Trakt"
except (traktException, traktAuthException, traktServerBusy) as e:
logger.log(u"Could not connect to Trakt service: %s" % ex(e), logger.WARNING)
return "Test notice failed to Trakt: %s" % ex(e)
开发者ID:feld,项目名称:SickRage,代码行数:27,代码来源:trakt.py
示例3: _makeURL
def _makeURL(self, result):
urls = []
filename = u''
if result.url.startswith('magnet'):
try:
torrent_hash = re.findall(r'urn:btih:([\w]{32,40})', result.url)[0].upper()
try:
torrent_name = re.findall('dn=([^&]+)', result.url)[0]
except Exception:
torrent_name = 'NO_DOWNLOAD_NAME'
if len(torrent_hash) == 32:
torrent_hash = b16encode(b32decode(torrent_hash)).upper()
if not torrent_hash:
logger.log(u"Unable to extract torrent hash from magnet: " + ex(result.url), logger.ERROR)
return urls, filename
urls = [x.format(torrent_hash=torrent_hash, torrent_name=torrent_name) for x in self.btCacheURLS]
except Exception:
logger.log(u"Unable to extract torrent hash or name from magnet: " + ex(result.url), logger.ERROR)
return urls, filename
else:
urls = [result.url]
if self.providerType == GenericProvider.TORRENT:
filename = ek(os.path.join, sickbeard.TORRENT_DIR, sanitize_filename(result.name) + '.' + self.providerType)
elif self.providerType == GenericProvider.NZB:
filename = ek(os.path.join, sickbeard.NZB_DIR, sanitize_filename(result.name) + '.' + self.providerType)
return urls, filename
开发者ID:hernandito,项目名称:SickRage,代码行数:33,代码来源:generic.py
示例4: _run_extra_scripts
def _run_extra_scripts(self, ep_obj):
"""
Executes any extra scripts defined in the config.
:param ep_obj: The object to use when calling the extra script
"""
for curScriptName in sickbeard.EXTRA_SCRIPTS:
# generate a safe command line string to execute the script and provide all the parameters
script_cmd = [piece for piece in re.split("( |\\\".*?\\\"|'.*?')", curScriptName) if piece.strip()]
script_cmd[0] = ek(os.path.abspath, script_cmd[0])
self._log(u"Absolute path to script: " + script_cmd[0], logger.DEBUG)
script_cmd = script_cmd + [ep_obj.location, self.file_path, str(ep_obj.show.indexerid), str(ep_obj.season),
str(ep_obj.episode), str(ep_obj.airdate)]
# use subprocess to run the command and capture output
self._log(u"Executing command " + str(script_cmd))
try:
p = subprocess.Popen(script_cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, cwd=sickbeard.PROG_DIR)
out, _ = p.communicate() # @UnusedVariable
self._log(u"Script result: " + str(out), logger.DEBUG)
except OSError, e:
self._log(u"Unable to run extra_script: " + ex(e))
except Exception, e:
self._log(u"Unable to run extra_script: " + ex(e))
开发者ID:nono20004,项目名称:SickRage,代码行数:29,代码来源:postProcessor.py
示例5: _send_to_kodi
def _send_to_kodi(command, host=None, username=None, password=None, dest_app="KODI"): # pylint: disable=too-many-arguments
"""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 if there was an error
"""
# fill in omitted parameters
if not username:
username = sickbeard.KODI_USERNAME
if not password:
password = sickbeard.KODI_PASSWORD
if not host:
logger.log(u'No %s host passed, aborting update' % dest_app, logger.WARNING)
return False
for key in command:
if isinstance(command[key], unicode):
command[key] = command[key].encode('utf-8')
enc_command = urllib.urlencode(command)
logger.log(u"%s encoded API command: %r" % (dest_app, enc_command), logger.DEBUG)
# url = 'http://%s/xbmcCmds/xbmcHttp/?%s' % (host, enc_command) # maybe need for old plex?
url = 'http://%s/kodiCmds/kodiHttp/?%s' % (host, enc_command)
try:
req = urllib2.Request(url)
# if we have a password, use authentication
if password:
base64string = base64.encodestring('%s:%s' % (username, password))[:-1]
authheader = "Basic %s" % base64string
req.add_header("Authorization", authheader)
logger.log(u"Contacting %s (with auth header) via url: %s" % (dest_app, ss(url)), logger.DEBUG)
else:
logger.log(u"Contacting %s via url: %s" % (dest_app, ss(url)), logger.DEBUG)
try:
response = urllib2.urlopen(req)
except (httplib.BadStatusLine, urllib2.URLError) as e:
logger.log(u"Couldn't contact %s HTTP at %r : %r" % (dest_app, url, ex(e)), logger.DEBUG)
return False
result = response.read().decode(sickbeard.SYS_ENCODING)
response.close()
logger.log(u"%s HTTP response: %s" % (dest_app, result.replace('\n', '')), logger.DEBUG)
return result
except Exception as e:
logger.log(u"Couldn't contact %s HTTP at %r : %r" % (dest_app, url, ex(e)), logger.DEBUG)
return False
开发者ID:Hydrog3n,项目名称:SickRage,代码行数:59,代码来源:kodi.py
示例6: _send_to_kodi
def _send_to_kodi(self, command, host=None, username=None, password=None):
"""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 if there was an error
"""
# fill in omitted parameters
if not username:
username = sickbeard.KODI_USERNAME
if not password:
password = sickbeard.KODI_PASSWORD
if not host:
logging.warning('No KODI host passed, aborting update')
return False
for key in command:
if isinstance(command[key], unicode):
command[key] = command[key].encode('utf-8')
enc_command = urllib.urlencode(command)
logging.debug("KODI encoded API command: " + enc_command)
url = 'http://%s/kodiCmds/kodiHttp/?%s' % (host, enc_command)
try:
req = urllib2.Request(url)
# if we have a password, use authentication
if password:
base64string = base64.encodestring('%s:%s' % (username, password))[:-1]
authheader = "Basic %s" % base64string
req.add_header("Authorization", authheader)
logging.debug("Contacting KODI (with auth header) via url: " + ss(url))
else:
logging.debug("Contacting KODI via url: " + ss(url))
try:
response = urllib2.urlopen(req)
except (httplib.BadStatusLine, urllib2.URLError) as e:
logging.debug("Couldn't contact KODI HTTP at %r : %r" % (url, ex(e)))
return False
result = response.read().decode(sickbeard.SYS_ENCODING)
response.close()
logging.debug("KODI HTTP response: " + result.replace('\n', ''))
return result
except Exception as e:
logging.debug("Couldn't contact KODI HTTP at %r : %r" % (url, ex(e)))
return False
开发者ID:coderbone,项目名称:SickRage,代码行数:58,代码来源:kodi.py
示例7: mass_action
def mass_action(self, querylist=None, logTransaction=False, fetchall=False):
"""
Execute multiple queries
:param querylist: list of queries
:param logTransaction: Boolean to wrap all in one transaction
:param fetchall: Boolean, when using a select query force returning all results
:return: list of results
"""
assert hasattr(querylist, '__iter__'), 'You passed a non-iterable to mass_action: {0!r}'.format(querylist)
# remove None types
querylist = [i for i in querylist if i]
sql_results = []
attempt = 0
with db_locks[self.filename]:
self._set_row_factory()
while attempt < 5:
try:
for qu in querylist:
if len(qu) == 1:
if logTransaction:
logger.log(qu[0], logger.DEBUG)
sql_results.append(self._execute(qu[0], fetchall=fetchall))
elif len(qu) > 1:
if logTransaction:
logger.log(qu[0] + " with args " + str(qu[1]), logger.DEBUG)
sql_results.append(self._execute(qu[0], qu[1], fetchall=fetchall))
self.connection.commit()
logger.log(u"Transaction with " + str(len(querylist)) + u" queries executed", logger.DEBUG)
# finished
break
except sqlite3.OperationalError as e:
sql_results = []
if self.connection:
self.connection.rollback()
if "unable to open database file" in e.args[0] or "database is locked" in e.args[0]:
logger.log(u"DB error: " + ex(e), logger.WARNING)
attempt += 1
time.sleep(1)
else:
logger.log(u"DB error: " + ex(e), logger.ERROR)
raise
except sqlite3.DatabaseError as e:
sql_results = []
if self.connection:
self.connection.rollback()
logger.log(u"Fatal error executing query: " + ex(e), logger.ERROR)
raise
# time.sleep(0.02)
return sql_results
开发者ID:Arcanemagus,项目名称:SickRage,代码行数:57,代码来源:db.py
示例8: mass_action
def mass_action(self, querylist=[], logTransaction=False, fetchall=False):
"""
Execute multiple queries
:param querylist: list of queries
:param logTransaction: Boolean to wrap all in one transaction
:param fetchall: Boolean, when using a select query force returning all results
:return: list of results
"""
with self.lock:
querylist = [i for i in querylist if i is not None and len(i)]
sqlResult = []
attempt = 0
while attempt < 5:
try:
for qu in querylist:
if len(qu) == 1:
if logTransaction:
logging.debug(qu[0])
sqlResult.append(self.execute(qu[0], fetchall=fetchall))
elif len(qu) > 1:
if logTransaction:
logging.debug(qu[0] + " with args " + str(qu[1]))
sqlResult.append(self.execute(qu[0], qu[1], fetchall=fetchall))
logging.debug("Transaction with " + str(len(querylist)) + " queries executed")
except sqlite3.OperationalError as e:
sqlResult = []
if self.connection:
self.connection.rollback()
if "unable to open database file" in e.args[0] or "database is locked" in e.args[0]:
logging.warning("DB error: {}".format(ex(e)))
attempt += 1
time.sleep(1)
else:
logging.error("DB error: {}".format(ex(e)))
raise
except sqlite3.DatabaseError as e:
sqlResult = []
if self.connection:
self.connection.rollback()
logging.error("Fatal error executing query: {}".format(ex(e)))
raise
finally:
self.commit()
break
return sqlResult
开发者ID:Sinap,项目名称:SickRage,代码行数:51,代码来源:db.py
示例9: _notify_emby
def _notify_emby(self, message, host=None, emby_apikey=None):
"""Handles notifying Emby host via HTTP API
Returns:
Returns True for no issue or False if there was an error
"""
# fill in omitted parameters
if not host:
host = sickbeard.EMBY_HOST
if not emby_apikey:
emby_apikey = sickbeard.EMBY_APIKEY
url = 'http://%s/emby/Notifications/Admin' % host
values = {'Name': 'SickRage', 'Description': message, 'ImageUrl': 'https://raw.githubusercontent.com/SickRage/SickRage/master/gui/slick/images/sickrage-shark-mascot.png'}
data = json.dumps(values)
try:
req = urllib2.Request(url, data)
req.add_header('X-MediaBrowser-Token', emby_apikey)
req.add_header('Content-Type', 'application/json')
response = urllib2.urlopen(req)
result = response.read()
response.close()
logger.log(u'EMBY: HTTP response: ' + result.replace('\n', ''), logger.DEBUG)
return True
except (urllib2.URLError, IOError) as e:
logger.log(u'EMBY: Warning: Couldn\'t contact Emby at ' + url + ' ' + ex(e), logger.WARNING)
return False
开发者ID:yenoiwesa,项目名称:SickRage,代码行数:32,代码来源:emby.py
示例10: update_cache
def update_cache(self):
# check if we should update
if not self.should_update():
return
try:
data = self._get_rss_data()
if self._check_auth(data):
# clear cache
self._clear_cache()
# set updated
self.set_last_update()
cl = []
for item in data['entries'] or []:
ci = self._parse_item(item)
if ci is not None:
cl.append(ci)
if cl:
cache_db_con = self._get_db()
cache_db_con.mass_action(cl)
except AuthException as e:
logger.log("Authentication error: " + ex(e), logger.WARNING)
except Exception as e:
logger.log("Error while searching " + self.provider.name + ", skipping: " + repr(e), logger.DEBUG)
开发者ID:Elettronik,项目名称:SickRage,代码行数:28,代码来源:tvcache.py
示例11: process_failed
def process_failed(dirName, nzbName, result):
"""Process a download that did not complete correctly"""
if sickbeard.USE_FAILED_DOWNLOADS:
processor = None
try:
processor = failedProcessor.FailedProcessor(dirName, nzbName)
result.result = processor.process()
process_fail_message = ""
except FailedPostProcessingFailedException as e:
result.result = False
process_fail_message = ex(e)
if processor:
result.output += processor.log
if sickbeard.DELETE_FAILED and result.result:
torrent_type = get_torrent_type(dirName, nzbName)
if torrent_type == TorrentType.SINGLE_FILE:
delete_files(dirName, [nzbName], result)
else:
if delete_folder(dirName, check_empty=False):
result.output += logHelper(u"Deleted folder: " + dirName, logger.DEBUG)
if result.result:
result.output += logHelper(u"Failed Download Processing succeeded: (" + str(nzbName) + ", " + dirName + ")")
else:
result.output += logHelper(
u"Failed Download Processing failed: (" + str(nzbName) + ", " + dirName + "): " + process_fail_message,
logger.WARNING)
开发者ID:fabiankaeser,项目名称:SickRage,代码行数:32,代码来源:processTV.py
示例12: _api_call
def _api_call(self, apikey, params=None, results_per_page=1000, offset=0):
server = jsonrpclib.Server(self.urls['base_url'])
parsedJSON = {}
try:
parsedJSON = server.getTorrents(apikey, params or {}, int(results_per_page), int(offset))
time.sleep(cpu_presets[sickbeard.CPU_PRESET])
except jsonrpclib.jsonrpc.ProtocolError as error:
if error.message == 'Call Limit Exceeded':
logger.log("You have exceeded the limit of 150 calls per hour, per API key which is unique to your user account", logger.WARNING)
else:
logger.log("JSON-RPC protocol error while accessing provicer. Error: {0} ".format(repr(error)), logger.ERROR)
parsedJSON = {'api-error': ex(error)}
return parsedJSON
except socket.timeout:
logger.log("Timeout while accessing provider", logger.WARNING)
except socket.error as error:
# Note that sometimes timeouts are thrown as socket errors
logger.log("Socket error while accessing provider. Error: {0} ".format(error[1]), logger.WARNING)
except Exception as error:
errorstring = str(error)
if errorstring.startswith('<') and errorstring.endswith('>'):
errorstring = errorstring[1:-1]
logger.log("Unknown error while accessing provider. Error: {0} ".format(errorstring), logger.WARNING)
return parsedJSON
开发者ID:KraXed112,项目名称:SickRage,代码行数:31,代码来源:btn.py
示例13: process_failed
def process_failed(process_path, release_name, result):
"""Process a download that did not complete correctly"""
if sickbeard.USE_FAILED_DOWNLOADS:
processor = None
try:
processor = failedProcessor.FailedProcessor(process_path, release_name)
result.result = processor.process()
process_fail_message = ""
except FailedPostProcessingFailedException as e:
result.result = False
process_fail_message = ex(e)
if processor:
result.output += processor.log
if sickbeard.DELETE_FAILED and result.result:
if delete_folder(process_path, check_empty=False):
result.output += log_helper("Deleted folder: {0}".format(process_path), logger.DEBUG)
if result.result:
result.output += log_helper("Failed Download Processing succeeded: ({0}, {1})".format(release_name, process_path))
else:
result.output += log_helper("Failed Download Processing failed: ({0}, {1}): {2}".format(release_name, process_path, process_fail_message), logger.WARNING)
开发者ID:magicseb,项目名称:SickRage,代码行数:25,代码来源:processTV.py
示例14: _verify_download
def _verify_download(self, file_name=None):
"""
Checks the saved file to see if it was actually valid, if not then consider the download a failure.
"""
# primitive verification of torrents, just make sure we didn't get a text file or something
if file_name.endswith(GenericProvider.TORRENT):
try:
parser = createParser(file_name)
if parser:
# pylint: disable=protected-access
# Access to a protected member of a client class
mime_type = parser._getMimeType()
try:
parser.stream._input.close()
except Exception:
pass
if mime_type == 'application/x-bittorrent':
return True
except Exception as e:
logger.log(u"Failed to validate torrent file: " + ex(e), logger.DEBUG)
logger.log(u"Result is not a valid torrent file", logger.DEBUG)
return False
return True
开发者ID:hernandito,项目名称:SickRage,代码行数:26,代码来源:generic.py
示例15: addEpisodeToTraktWatchList
def addEpisodeToTraktWatchList(self):
if sickbeard.TRAKT_SYNC_WATCHLIST and sickbeard.USE_TRAKT:
logger.log(u"WATCHLIST::ADD::START - Look for Episodes to Add to Trakt Watchlist", logger.DEBUG)
myDB = db.DBConnection()
sql_selection = 'select tv_shows.indexer, tv_shows.startyear, showid, show_name, season, episode from tv_episodes,tv_shows where tv_shows.indexer_id = tv_episodes.showid and tv_episodes.status in (' + ','.join([str(x) for x in Quality.SNATCHED + Quality.SNATCHED_PROPER + [WANTED]]) + ')'
episodes = myDB.select(sql_selection)
if episodes is not None:
trakt_data = []
for cur_episode in episodes:
trakt_id = sickbeard.indexerApi(cur_episode["indexer"]).config['trakt_id']
if not self._checkInList(trakt_id, str(cur_episode["showid"]), str(cur_episode["season"]), str(cur_episode["episode"])):
logger.log(u"Adding Episode %s S%02dE%02d to watchlist" %
(cur_episode["show_name"], cur_episode["season"], cur_episode["episode"]), logger.DEBUG)
trakt_data.append((cur_episode["showid"], cur_episode["indexer"], cur_episode["show_name"], cur_episode["startyear"], cur_episode["season"],
cur_episode["episode"]))
if len(trakt_data):
try:
data = self.trakt_bulk_data_generate(trakt_data)
self.trakt_api.traktRequest("sync/watchlist", data, method='POST')
self._getEpisodeWatchlist()
except traktException as e:
logger.log(u"Could not connect to Trakt service. Error %s" % ex(e), logger.WARNING)
logger.log(u"WATCHLIST::ADD::FINISH - Look for Episodes to Add to Trakt Watchlist", logger.DEBUG)
开发者ID:madtrix74,项目名称:SickRage,代码行数:29,代码来源:traktChecker.py
示例16: _season_banners_dict
def _season_banners_dict(self, show_obj, season):
"""
Should return a dict like:
result = {<season number>:
{1: '<url 1>', 2: <url 2>, ...},}
"""
# This holds our resulting dictionary of season art
result = {}
indexer_lang = show_obj.lang
try:
# There's gotta be a better way of doing this but we don't wanna
# change the language value elsewhere
lINDEXER_API_PARMS = sickbeard.indexerApi(show_obj.indexer).api_params.copy()
lINDEXER_API_PARMS['banners'] = True
if indexer_lang and not indexer_lang == sickbeard.INDEXER_DEFAULT_LANGUAGE:
lINDEXER_API_PARMS['language'] = indexer_lang
t = sickbeard.indexerApi(show_obj.indexer).indexer(**lINDEXER_API_PARMS)
indexer_show_obj = t[show_obj.indexerid]
except (sickbeard.indexer_error, IOError), e:
logger.log(u"Unable to look up show on " + sickbeard.indexerApi(
show_obj.indexer).name + ", not downloading images: " + ex(e), logger.WARNING)
logger.log(u"Indexer " + sickbeard.indexerApi(show_obj.indexer).name + "maybe experiencing some problems. Try again later", logger.DEBUG)
return result
开发者ID:feld,项目名称:SickRage,代码行数:30,代码来源:generic.py
示例17: run_subs_extra_scripts
def run_subs_extra_scripts(epObj, foundSubs):
for curScriptName in sickbeard.SUBTITLES_EXTRA_SCRIPTS:
script_cmd = [piece for piece in re.split("( |\\\".*?\\\"|'.*?')", curScriptName) if piece.strip()]
script_cmd[0] = ek(os.path.abspath, script_cmd[0])
logger.log(u"Absolute path to script: " + script_cmd[0], logger.DEBUG)
for video, subs in foundSubs.iteritems():
subpaths = []
for sub in subs:
subpath = subliminal.subtitle.get_subtitle_path(video.name, sub.language)
if os.path.isabs(sickbeard.SUBTITLES_DIR):
subpath = ek(os.path.join, sickbeard.SUBTITLES_DIR, ek(os.path.basename, subpath))
elif sickbeard.SUBTITLES_DIR:
subpath = ek(os.path.join, ek(os.path.dirname, subpath), sickbeard.SUBTITLES_DIR, ek(os.path.basename, subpath))
inner_cmd = script_cmd + [video.name, subpath, sub.language.opensubtitles, epObj['show.name'],
str(epObj['season']), str(epObj['episode']), epObj['name'], str(epObj['show.indexerid'])]
# use subprocess to run the command and capture output
logger.log(u"Executing command: %s" % inner_cmd)
try:
p = subprocess.Popen(inner_cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, cwd=sickbeard.PROG_DIR)
out, err = p.communicate() # @UnusedVariable
logger.log(u"Script result: %s" % out, logger.DEBUG)
except Exception as e:
logger.log(u"Unable to run subs_extra_script: " + ex(e))
开发者ID:TCRakt,项目名称:SickRage,代码行数:29,代码来源:subtitles.py
示例18: _checkSabResponse
def _checkSabResponse(f):
"""
Check response from SAB
:param f: Response from SAV
:return: a list of (Boolean, string) which is True if SAB is not reporting an error
"""
try:
result = f.readlines()
except Exception as e:
logger.log(u"Error trying to get result from SAB{}".format(ex(e)), logger.ERROR)
return False, "Error from SAB"
if len(result) == 0:
logger.log(u"No data returned from SABnzbd, NZB not sent", logger.ERROR)
return False, "No data from SAB"
sabText = result[0].strip()
sabJson = {}
try:
sabJson = json.loads(sabText)
except ValueError as e:
pass
if sabText == "Missing authentication":
logger.log(u"Incorrect username/password sent to SAB", logger.ERROR)
return False, "Incorrect username/password sent to SAB"
elif 'error' in sabJson:
logger.log(sabJson['error'], logger.ERROR)
return False, sabJson['error']
else:
return True, sabText
开发者ID:CarlNeuhaus,项目名称:SickRage,代码行数:32,代码来源:sab.py
示例19: _make_url
def _make_url(self, result):
if not result:
return '', ''
urls = []
filename = u''
if result.url.startswith('magnet'):
try:
torrent_hash = re.findall(r'urn:btih:([\w]{32,40})', result.url)[0].upper()
try:
torrent_name = re.findall('dn=([^&]+)', result.url)[0]
except Exception:
torrent_name = 'NO_DOWNLOAD_NAME'
if len(torrent_hash) == 32:
torrent_hash = b16encode(b32decode(torrent_hash)).upper()
if not torrent_hash:
logger.log(u'Unable to extract torrent hash from magnet: %s' % ex(result.url), logger.ERROR)
return urls, filename
urls = [x.format(torrent_hash=torrent_hash, torrent_name=torrent_name) for x in self.bt_cache_urls]
except Exception:
logger.log(u'Unable to extract torrent hash or name from magnet: %s' % ex(result.url), logger.ERROR)
return urls, filename
else:
urls = [result.url]
filename = ek(join, self._get_storage_dir(), sanitize_filename(result.name) + '.' + self.provider_type)
return urls, filename
开发者ID:madtrix74,项目名称:SickRage,代码行数:33,代码来源:GenericProvider.py
示例20: _get_ep_obj
def _get_ep_obj(self, show, season, episodes):
"""
Retrieve the TVEpisode object requested.
:param show: The show object belonging to the show we want to process
:param season: The season of the episode (int)
:param episodes: A list of episodes to find (list of ints)
:return: If the episode(s) can be found then a TVEpisode object with the correct related eps will
be instantiated and returned. If the episode can't be found then None will be returned.
"""
root_ep = None
for cur_episode in episodes:
self._log(u"Retrieving episode object for " + str(season) + "x" + str(cur_episode), logger.DEBUG)
# now that we've figured out which episode this file is just load it manually
try:
curEp = show.getEpisode(season, cur_episode)
if not curEp:
raise EpisodeNotFoundException()
except EpisodeNotFoundException, e:
self._log(u"Unable to create episode: " + ex(e), logger.DEBUG)
raise EpisodePostProcessingFailedException()
# associate all the episodes together under a single root episode
if root_ep == None:
root_ep = curEp
root_ep.relatedEps = []
elif curEp not in root_ep.relatedEps:
root_ep.relatedEps.append(curEp)
开发者ID:nono20004,项目名称:SickRage,代码行数:31,代码来源:postProcessor.py
注:本文中的sickrage.helper.exceptions.ex函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论