本文整理汇总了Python中sickchill.helper.exceptions.ex函数的典型用法代码示例。如果您正苦于以下问题:Python ex函数的具体用法?Python ex怎么用?Python ex使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ex函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: 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("Could not connect to Trakt service: {0}".format(ex(e)), logger.WARNING)
return "Test notice failed to Trakt: {0}".format(ex(e))
开发者ID:murbaniak,项目名称:SickRage,代码行数:27,代码来源:trakt.py
示例2: _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://{0}/emby/Notifications/Admin'.format(host)
values = {'Name': 'SickChill', 'Description': message, 'ImageUrl': sickbeard.LOGO_URL}
data = json.dumps(values)
try:
req = urllib.request.Request(url, data)
req.add_header('X-MediaBrowser-Token', emby_apikey)
req.add_header('Content-Type', 'application/json')
response = urllib.request.urlopen(req)
result = response.read()
response.close()
logger.log('EMBY: HTTP response: ' + result.replace('\n', ''), logger.DEBUG)
return True
except (urllib.error.URLError, IOError) as e:
logger.log('EMBY: Warning: Couldn\'t contact Emby at ' + url + ' ' + ex(e), logger.WARNING)
return False
开发者ID:murbaniak,项目名称:SickRage,代码行数:32,代码来源:emby.py
示例3: 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:murbaniak,项目名称:SickRage,代码行数:25,代码来源:processTV.py
示例4: _api_call
def _api_call(self, apikey, params=None, results_per_page=1000, offset=0):
server = jsonrpclib.Server(self.urls['base_url'])
parsed_json = {}
try:
parsed_json = 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 == (-32001, 'Invalid API Key'):
logger.log("The API key you provided was rejected because it is invalid. Check your provider configuration.", logger.WARNING)
elif error.message == (-32002, '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 provider. Error: {0} ".format(repr(error)), logger.ERROR)
parsed_json = {'api-error': ex(error)}
return parsed_json
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 parsed_json
开发者ID:murbaniak,项目名称:SickRage,代码行数:33,代码来源:btn.py
示例5: _season_posters_dict
def _season_posters_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
lINDEXER_API_PARMS['language'] = indexer_lang or sickbeard.INDEXER_DEFAULT_LANGUAGE
if show_obj.dvdorder:
lINDEXER_API_PARMS['dvdorder'] = True
t = sickbeard.indexerApi(show_obj.indexer).indexer(**lINDEXER_API_PARMS)
indexer_show_obj = t[show_obj.indexerid]
except (sickbeard.indexer_error, IOError) as e:
logger.log("Unable to look up show on " + sickbeard.indexerApi(
show_obj.indexer).name + ", not downloading images: " + ex(e), logger.WARNING)
logger.log("{0} may be experiencing some problems. Try again later.".format(sickbeard.indexerApi(show_obj.indexer).name), logger.DEBUG)
return result
# if we have no season banners then just finish
if not getattr(indexer_show_obj, '_banners', None):
return result
if 'season' not in indexer_show_obj['_banners'] or 'season' not in indexer_show_obj['_banners']['season']:
return result
# Give us just the normal poster-style season graphics
seasonsArtObj = indexer_show_obj['_banners']['season']['season']
# Returns a nested dictionary of season art with the season
# number as primary key. It's really overkill but gives the option
# to present to user via ui to pick down the road.
result[season] = {}
# find the correct season in the TVDB object and just copy the dict into our result dict
for seasonArtID in seasonsArtObj.keys():
if int(seasonsArtObj[seasonArtID]['season']) == season and seasonsArtObj[seasonArtID]['language'] == (
indexer_lang or sickbeard.INDEXER_DEFAULT_LANGUAGE):
result[season][seasonArtID] = seasonsArtObj[seasonArtID]['_bannerpath']
return result
开发者ID:murbaniak,项目名称:SickRage,代码行数:56,代码来源:generic.py
示例6: _send_synologyNotifier
def _send_synologyNotifier(self, message, title):
synodsmnotify_cmd = ["/usr/syno/bin/synodsmnotify", "@administrators", title, message]
logger.log("Executing command " + str(synodsmnotify_cmd))
logger.log("Absolute path to command: " + ek(os.path.abspath, synodsmnotify_cmd[0]), logger.DEBUG)
try:
p = subprocess.Popen(synodsmnotify_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
cwd=sickbeard.PROG_DIR)
out, err = p.communicate() # @UnusedVariable
logger.log("Script result: " + str(out), logger.DEBUG)
except OSError as e:
logger.log("Unable to run synodsmnotify: " + ex(e))
开发者ID:murbaniak,项目名称:SickRage,代码行数:11,代码来源:synologynotifier.py
示例7: run
def run(self, force=False): # pylint: disable=unused-argument, too-many-locals, too-many-branches, too-many-statements
if self.amActive:
return
self.amActive = True
update_timestamp = time.mktime(datetime.datetime.now().timetuple())
cache_db_con = db.DBConnection('cache.db')
result = cache_db_con.select('SELECT `time` FROM lastUpdate WHERE provider = ?', ['theTVDB'])
if result:
last_update = int(result[0][0])
else:
last_update = int(time.mktime(datetime.datetime.min.timetuple()))
cache_db_con.action('INSERT INTO lastUpdate (provider, `time`) VALUES (?, ?)', ['theTVDB', last_update])
network_timezones.update_network_dict()
url = 'http://thetvdb.com/api/Updates.php?type=series&time={0}'.format(last_update)
data = helpers.getURL(url, session=self.session, returns='text', hooks={'response': self.request_hook})
if not data:
logger.log('Could not get the recently updated show data from {0}. Retrying later. Url was: {1}'.format(sickbeard.indexerApi(INDEXER_TVDB).name, url))
self.amActive = False
return
updated_shows = set()
try:
tree = etree.fromstring(data)
for show in tree.findall('Series'):
updated_shows.add(int(show.text))
except SyntaxError:
update_timestamp = last_update
pi_list = []
for cur_show in sickbeard.showList:
if int(cur_show.indexer) in [INDEXER_TVRAGE]:
logger.log('Indexer is no longer available for show [{0}] '.format(cur_show.name), logger.WARNING)
continue
try:
cur_show.nextEpisode()
if sickbeard.indexerApi(cur_show.indexer).name == 'theTVDB':
if cur_show.indexerid in updated_shows:
pi_list.append(sickbeard.showQueueScheduler.action.update_show(cur_show, True))
else:
pi_list.append(sickbeard.showQueueScheduler.action.refresh_show(cur_show, False))
except (CantUpdateShowException, CantRefreshShowException) as error:
logger.log('Automatic update failed: {0}'.format(ex(error)), logger.DEBUG)
ui.ProgressIndicators.setIndicator('dailyUpdate', ui.QueueProgressIndicator('Daily Update', pi_list))
cache_db_con.action('UPDATE lastUpdate SET `time` = ? WHERE provider=?', [update_timestamp, 'theTVDB'])
self.amActive = False
开发者ID:murbaniak,项目名称:SickRage,代码行数:54,代码来源:showUpdater.py
示例8: makeObject
def makeObject(self, cmd_arg, cur_path):
if sickbeard.USE_SYNOINDEX:
synoindex_cmd = ['/usr/syno/bin/synoindex', cmd_arg, ek(os.path.abspath, cur_path)]
logger.log("Executing command " + str(synoindex_cmd), logger.DEBUG)
logger.log("Absolute path to command: " + ek(os.path.abspath, synoindex_cmd[0]), logger.DEBUG)
try:
p = subprocess.Popen(synoindex_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
cwd=sickbeard.PROG_DIR)
out, err = p.communicate() # @UnusedVariable
logger.log("Script result: " + str(out), logger.DEBUG)
except OSError as e:
logger.log("Unable to run synoindex: " + ex(e), logger.ERROR)
开发者ID:murbaniak,项目名称:SickRage,代码行数:12,代码来源:synoindex.py
示例9: delete_folder
def delete_folder(folder, check_empty=True):
"""
Removes a folder from the filesystem
:param folder: Path to folder to remove
:param check_empty: Boolean, check if the folder is empty before removing it, defaults to True
:return: True on success, False on failure
"""
# check if it's a folder
if not ek(os.path.isdir, folder):
return False
# check if it isn't TV_DOWNLOAD_DIR
if sickbeard.TV_DOWNLOAD_DIR and helpers.real_path(folder) == helpers.real_path(sickbeard.TV_DOWNLOAD_DIR):
return False
# check if it's empty folder when wanted checked
if check_empty:
check_files = ek(os.listdir, folder)
if check_files:
logger.log("Not deleting folder {0} found the following files: {1}".format(folder, check_files), logger.INFO)
return False
try:
logger.log("Deleting folder (if it's empty): {0}".format(folder))
ek(os.rmdir, folder)
except (OSError, IOError) as e:
logger.log("Warning: unable to delete folder: {0}: {1}".format(folder, ex(e)), logger.WARNING)
return False
else:
try:
logger.log("Deleting folder: " + folder)
shutil.rmtree(folder)
except (OSError, IOError) as e:
logger.log("Warning: unable to delete folder: {0}: {1}".format(folder, ex(e)), logger.WARNING)
return False
return True
开发者ID:murbaniak,项目名称:SickRage,代码行数:39,代码来源:processTV.py
示例10: save_nzb
def save_nzb(nzb_name, nzb_string):
"""
Save NZB to disk
:param nzb_name: Filename/path to write to
:param nzb_string: Content to write in file
"""
try:
with ek(open, nzb_name + ".nzb", 'w') as nzb_fh:
nzb_fh.write(nzb_string)
except EnvironmentError as error:
logger.log("Unable to save NZB: " + ex(error), logger.ERROR) # pylint: disable=no-member
开发者ID:murbaniak,项目名称:SickRage,代码行数:13,代码来源:nzbSplitter.py
示例11: dumpHTML
def dumpHTML(data):
dumpName = ek(os.path.join, sickbeard.CACHE_DIR, 'custom_torrent.html')
try:
fileOut = io.open(dumpName, 'wb')
fileOut.write(data)
fileOut.close()
helpers.chmodAsParent(dumpName)
except IOError as error:
logger.log('Unable to save the file: {0}'.format(ex(error)), logger.ERROR)
return False
logger.log('Saved custom_torrent html dump {0} '.format(dumpName), logger.INFO)
return True
开发者ID:murbaniak,项目名称:SickRage,代码行数:14,代码来源:rsstorrent.py
示例12: _process_upgrade
def _process_upgrade(connection, upgrade_class):
instance = upgrade_class(connection)
# logger.log("Checking " + pretty_name(upgrade_class.__name__) + " database upgrade", logger.DEBUG)
if not instance.test():
logger.log("Database upgrade required: " + pretty_name(upgrade_class.__name__), logger.DEBUG)
try:
instance.execute()
except Exception as e:
logger.log("Error in " + str(upgrade_class.__name__) + ": " + ex(e), logger.ERROR)
raise
logger.log(upgrade_class.__name__ + " upgrade completed", logger.DEBUG)
# else:
# logger.log(upgrade_class.__name__ + " upgrade not required", logger.DEBUG)
for upgradeSubClass in upgrade_class.__subclasses__():
_process_upgrade(connection, upgradeSubClass)
开发者ID:murbaniak,项目名称:SickRage,代码行数:17,代码来源:db.py
示例13: update_library
def update_library(self, ep_obj):
"""
Sends a request to trakt indicating that the given episode is part of our library.
ep_obj: The TVEpisode object to add to trakt
"""
trakt_id = sickbeard.indexerApi(ep_obj.show.indexer).config['trakt_id']
trakt_api = TraktAPI(sickbeard.SSL_VERIFY, sickbeard.TRAKT_TIMEOUT)
if sickbeard.USE_TRAKT:
try:
# URL parameters
data = {
'shows': [
{
'title': ep_obj.show.name,
'year': ep_obj.show.startyear,
'ids': {},
}
]
}
if trakt_id == 'tvdb_id':
data['shows'][0]['ids']['tvdb'] = ep_obj.show.indexerid
else:
data['shows'][0]['ids']['tvrage'] = ep_obj.show.indexerid
if sickbeard.TRAKT_SYNC_WATCHLIST and sickbeard.TRAKT_REMOVE_SERIESLIST:
trakt_api.traktRequest("sync/watchlist/remove", data, method='POST')
# Add Season and Episode + Related Episodes
data['shows'][0]['seasons'] = [{'number': ep_obj.season, 'episodes': []}]
for relEp_Obj in [ep_obj] + ep_obj.relatedEps:
data['shows'][0]['seasons'][0]['episodes'].append({'number': relEp_Obj.episode})
if sickbeard.TRAKT_SYNC_WATCHLIST and sickbeard.TRAKT_REMOVE_WATCHLIST:
trakt_api.traktRequest("sync/watchlist/remove", data, method='POST')
# update library
trakt_api.traktRequest("sync/collection", data, method='POST')
except (traktException, traktAuthException, traktServerBusy) as e:
logger.log("Could not connect to Trakt service: {0}".format(ex(e)), logger.WARNING)
开发者ID:murbaniak,项目名称:SickRage,代码行数:45,代码来源:trakt.py
示例14: _send_slack
def _send_slack(self, message=None):
slack_webhook = self.SLACK_WEBHOOK_URL + sickbeard.SLACK_WEBHOOK.replace(self.SLACK_WEBHOOK_URL, '')
logger.log("Sending slack message: " + message, logger.INFO)
logger.log("Sending slack message to url: " + slack_webhook, logger.INFO)
if isinstance(message, six.text_type):
message = message.encode('utf-8')
headers = {b"Content-Type": b"application/json"}
try:
r = requests.post(slack_webhook, data=json.dumps(dict(text=message, username="SickChillBot")), headers=headers)
r.raise_for_status()
except Exception as e:
logger.log("Error Sending Slack message: " + ex(e), logger.ERROR)
return False
return True
开发者ID:murbaniak,项目名称:SickRage,代码行数:18,代码来源:slack.py
示例15: update_library
def update_library(self, show=None):
"""Handles updating the Emby Media Server host via HTTP API
Returns:
Returns True for no issue or False if there was an error
"""
if sickbeard.USE_EMBY:
if not sickbeard.EMBY_HOST:
logger.log('EMBY: No host specified, check your settings', logger.DEBUG)
return False
if show:
if show.indexer == 1:
provider = 'tvdb'
elif show.indexer == 2:
logger.log('EMBY: TVRage Provider no longer valid', logger.WARNING)
return False
else:
logger.log('EMBY: Provider unknown', logger.WARNING)
return False
query = '?{0}id={1}'.format(provider, show.indexerid)
else:
query = ''
url = 'http://{0}/emby/Library/Series/Updated{1}'.format(sickbeard.EMBY_HOST, query)
values = {}
data = urllib.parse.urlencode(values)
try:
req = urllib.request.Request(url, data)
req.add_header('X-MediaBrowser-Token', sickbeard.EMBY_APIKEY)
response = urllib.request.urlopen(req)
result = response.read()
response.close()
logger.log('EMBY: HTTP response: ' + result.replace('\n', ''), logger.DEBUG)
return True
except (urllib.error.URLError, IOError) as e:
logger.log('EMBY: Warning: Couldn\'t contact Emby at ' + url + ' ' + ex(e), logger.WARNING)
return False
开发者ID:murbaniak,项目名称:SickRage,代码行数:44,代码来源:emby.py
示例16: markFailed
def markFailed(epObj):
"""
Mark an episode as failed
:param epObj: Episode object to mark as failed
:return: empty string
"""
log_str = ""
try:
with epObj.lock:
quality = Quality.splitCompositeStatus(epObj.status)[1]
epObj.status = Quality.compositeStatus(FAILED, quality)
epObj.saveToDB()
except EpisodeNotFoundException as e:
logger.log("Unable to get episode, please set its status manually: " + ex(e), logger.WARNING)
return log_str
开发者ID:murbaniak,项目名称:SickRage,代码行数:19,代码来源:failed_history.py
示例17: _error_log_helper
def _error_log_helper(self, exception, severity, local_variables, attempts, called_method):
if attempts in (0, self.MAX_ATTEMPTS): # Only log the first try and the final failure
prefix = ("Database", "Fatal")[severity == logger.ERROR]
# noinspection PyUnresolvedReferences
logger.log(
_("{exception_severity} error executing query with {method} in database {db_location}: ").format(
db_location=self.full_path, method=called_method, exception_severity=prefix
) + ex(exception), severity
)
# Lets print out all of the arguments so we can debug this better
# noinspection PyUnresolvedReferences
logger.log(_("If this happened in cache.db, you can safely stop SickChill, and delete the cache.db file without losing any data"))
# noinspection PyUnresolvedReferences
logger.log(
_("Here is the arguments that were passed to this function (This is what the developers need to know): {local_variables:s}").format(
local_variables=local_variables
)
)
开发者ID:murbaniak,项目名称:SickRage,代码行数:19,代码来源:db.py
示例18: _notifyTwilio
def _notifyTwilio(self, message='', force=False, allow_raise=False):
if not (sickbeard.USE_TWILIO or force or self.number_regex.match(sickbeard.TWILIO_TO_NUMBER)):
return False
logger.log('Sending Twilio SMS: ' + message, logger.DEBUG)
try:
self.client.messages.create(
body=message,
to=sickbeard.TWILIO_TO_NUMBER,
from_=self.number.phone_number,
)
except twilio.TwilioRestException as e:
logger.log('Twilio notification failed:' + ex(e), logger.ERROR)
if allow_raise:
raise e
return True
开发者ID:murbaniak,项目名称:SickRage,代码行数:19,代码来源:twilio_notify.py
示例19: get_image_url
def get_image_url(indexer_id):
""" Get poster image url from TVDB """
image_url = None
try:
lINDEXER_API_PARMS = sickbeard.indexerApi(INDEXER_TVDB).api_params.copy()
lINDEXER_API_PARMS['banners'] = True
t = sickbeard.indexerApi(INDEXER_TVDB).indexer(**lINDEXER_API_PARMS)
indexer_show_obj = t[int(indexer_id)]
except (sickbeard.indexer_error, IOError) as e:
logger.log("Show id " + indexer_id + " not found on " + sickbeard.indexerApi(INDEXER_TVDB).name +
", not downloading poster: " + ex(e), logger.DEBUG)
return None
if getattr(indexer_show_obj, 'poster', None):
image_url = indexer_show_obj['poster'].replace('posters', '_cache/posters')
return image_url
开发者ID:murbaniak,项目名称:SickRage,代码行数:20,代码来源:traktTrending.py
示例20: refresh
def refresh(indexer_id):
"""
Try to refresh a show
:param indexer_id: The unique id of the show to refresh
:return: A tuple containing:
- an error message if the show could not be refreshed, ``None`` otherwise
- the show object that was refreshed, if it exists, ``None`` otherwise
"""
error, show = Show._validate_indexer_id(indexer_id)
if error is not None:
return error, show
try:
sickbeard.showQueueScheduler.action.refresh_show(show)
except CantRefreshShowException as exception:
return ex(exception), show
return None, show
开发者ID:murbaniak,项目名称:SickRage,代码行数:20,代码来源:Show.py
注:本文中的sickchill.helper.exceptions.ex函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论