本文整理汇总了Python中sickbeard.encodingKludge.ss函数的典型用法代码示例。如果您正苦于以下问题:Python ss函数的具体用法?Python ss怎么用?Python ss使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ss函数的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ex
def ex(e):
"""
Returns a unicode string from the exception text if it exists.
"""
e_message = u""
if not e or not e.args:
return e_message
for arg in e.args:
if arg is not None:
if isinstance(arg, (str, unicode)):
fixed_arg = ek.ss(arg)
else:
try:
fixed_arg = u"error " + ek.ss(str(arg))
except:
fixed_arg = None
if fixed_arg:
if not e_message:
e_message = fixed_arg
else:
e_message = e_message + " : " + fixed_arg
return e_message
示例2: _send_to_kodi_json
def _send_to_kodi_json(self, command, host=None, username=None, password=None):
"""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 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 KODI host passed, aborting update', logger.DEBUG)
return False
command = command.encode('utf-8')
logger.log(u"KODI JSON command: " + command, logger.DEBUG)
url = 'http://%s/jsonrpc' % (host)
try:
req = urllib2.Request(url, command)
req.add_header("Content-type", "application/json")
# 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 KODI (with auth header) via url: " + ek.ss(url), logger.DEBUG)
else:
logger.log(u"Contacting KODI via url: " + ek.ss(url), logger.DEBUG)
try:
response = urllib2.urlopen(req)
except (httplib.BadStatusLine, urllib2.URLError), e:
logger.log(u"Error while trying to retrieve KODI API version for " + host + ": " + ex(e),
logger.WARNING)
return False
# parse the json result
try:
result = json.load(response)
response.close()
logger.log(u"KODI JSON response: " + str(result), logger.DEBUG)
return result # need to return response for parsing
except ValueError, e:
logger.log(u"Unable to decode JSON: " + str(response.read()), logger.WARNING)
return False
示例3: _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:
logger.log(u'No KODI host passed, aborting update', logger.DEBUG)
return False
for key in command:
if type(command[key]) == unicode:
command[key] = command[key].encode('utf-8')
enc_command = urllib.urlencode(command)
logger.log(u"KODI encoded API command: " + enc_command, logger.DEBUG)
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 KODI (with auth header) via url: " + ek.ss(url), logger.DEBUG)
else:
logger.log(u"Contacting KODI via url: " + ek.ss(url), logger.DEBUG)
response = urllib2.urlopen(req)
result = response.read().decode(sickbeard.SYS_ENCODING)
response.close()
logger.log(u"KODI HTTP response: " + result.replace('\n', ''), logger.DEBUG)
return result
except Exception as e:
logger.log(u"Warning: Couldn't contact KODI HTTP at " + ek.ss(url) + " " + str(e),
logger.WARNING)
return False
示例4: _write_image
def _write_image(self, image_data, image_path, obj = None):
"""
Saves the data in image_data to the location image_path. Returns True/False
to represent success or failure.
image_data: binary image data to write to file
image_path: file location to save the image to
"""
# don't bother overwriting it
if ek.ek(os.path.isfile, image_path):
logger.log(u"Image already exists, not downloading", logger.DEBUG)
return False
image_dir = ek.ek(os.path.dirname, image_path)
if not image_data:
logger.log(u"Unable to retrieve image to %s to save in %s, skipping" % ( ek.ss(obj.prettyName()), ek.ss(image_dir) ), logger.WARNING)
return False
try:
if not ek.ek(os.path.isdir, image_dir):
logger.log(u"Metadata dir didn't exist, creating it at " + image_dir, logger.DEBUG)
ek.ek(os.makedirs, image_dir)
helpers.chmodAsParent(image_dir)
outFile = ek.ek(open, image_path, 'wb')
outFile.write(image_data)
outFile.close()
helpers.chmodAsParent(image_path)
except IOError, e:
logger.log(
u"Unable to write image to " + image_path + " - are you sure the show folder is writable? " + ex(e),
logger.ERROR)
return False
示例5: submit_errors
def submit_errors(self):
if not (sickbeard.GIT_USERNAME and sickbeard.GIT_PASSWORD and len(classes.ErrorViewer.errors) > 0):
return
gh_org = sickbeard.GIT_ORG or 'SiCKRAGETV'
gh_repo = 'sickrage-issues'
gh = Github(login_or_token=sickbeard.GIT_USERNAME, password=sickbeard.GIT_PASSWORD, user_agent="SiCKRAGE")
try:
# read log file
log_data = None
if self.logFile and os.path.isfile(self.logFile):
with ek.ek(codecs.open, *[self.logFile, 'r', 'utf-8']) as f:
log_data = f.readlines()
log_data = [line for line in reversed(log_data)]
# parse and submit errors to issue tracker
for curError in sorted(classes.ErrorViewer.errors, key=lambda error: error.time, reverse=True)[:500]:
if not curError.title:
continue
gist = None
regex = "^(%s)\s*([A-Z]+)\s*(.+?)\s*\:\:\s*(.*)$" % curError.time
for i, x in enumerate(log_data):
x = ek.ss(x)
match = re.match(regex, x)
if match:
level = match.group(2)
if reverseNames[level] == ERROR:
paste_data = "".join(log_data[i:i+50])
if paste_data:
gist = gh.get_user().create_gist(True, {"sickrage.log": InputFileContent(paste_data)})
break
message = u"### INFO\n"
message += u"Python Version: **" + sys.version[:120] + "**\n"
message += u"Operating System: **" + platform.platform() + "**\n"
message += u"Branch: **" + sickbeard.BRANCH + "**\n"
message += u"Commit: SiCKRAGETV/[email protected]" + sickbeard.CUR_COMMIT_HASH + "\n"
if gist:
message += u"Link to Log: " + gist.html_url + "\n"
message += u"### ERROR\n"
message += u"```\n"
message += curError.message + "\n"
message += u"```\n"
message += u"---\n"
message += u"_STAFF NOTIFIED_: @SiCKRAGETV/owners @SiCKRAGETV/moderators"
issue = gh.get_organization(gh_org).get_repo(gh_repo).create_issue("[APP SUBMITTED]: " + str(curError.title), message)
if issue:
self.log('Your issue ticket #%s was submitted successfully!' % issue.number)
# clear error from error list
classes.ErrorViewer.errors.remove(curError)
return issue
except Exception as e:
self.log(sickbeard.exceptions.ex(e), ERROR)
示例6: _parseEp
def _parseEp(self, ep_name):
ep_name = ek.ss(ep_name)
sep = " - "
titles = ep_name.split(sep)
titles.sort(key=len, reverse=True)
logger.log("TITLES: %s" % titles, logger.DEBUG)
return titles
示例7: _logHistoryItem
def _logHistoryItem(action, showid, season, episode, quality, resource, provider, version=-1):
logDate = datetime.datetime.today().strftime(dateFormat)
resource = ek.ss(resource)
myDB = db.DBConnection()
myDB.action(
"INSERT INTO history (action, date, showid, season, episode, quality, resource, provider, version) VALUES (?,?,?,?,?,?,?,?,?)",
[action, logDate, showid, season, episode, quality, resource, provider, version])
示例8: createNZBString
def createNZBString(fileElements, xmlns):
rootElement = etree.Element("nzb")
if xmlns:
rootElement.set("xmlns", xmlns)
for curFile in fileElements:
rootElement.append(stripNS(curFile, xmlns))
return xml.etree.ElementTree.tostring(ek.ss(rootElement))
示例9: prepareFailedName
def prepareFailedName(release):
"""Standardizes release name for failed DB"""
fixed = urllib.unquote(release)
if fixed.endswith(".nzb"):
fixed = fixed.rpartition(".")[0]
fixed = re.sub("[\.\-\+\ ]", "_", fixed)
fixed = ek.ss(fixed)
return fixed
示例10: _addCacheEntry
def _addCacheEntry(self, name, url, parse_result=None, indexer_id=0):
# check if we passed in a parsed result or should we try and create one
if not parse_result:
# create showObj from indexer_id if available
showObj = None
if indexer_id:
showObj = helpers.findCertainShow(sickbeard.showList, indexer_id)
try:
myParser = NameParser(showObj=showObj, convert=True)
parse_result = myParser.parse(name)
except InvalidNameException:
logger.log(u"Unable to parse the filename " + name + " into a valid episode", logger.DEBUG)
return None
except InvalidShowException:
logger.log(u"Unable to parse the filename " + name + " into a valid show", logger.DEBUG)
return None
if not parse_result or not parse_result.series_name:
return None
# if we made it this far then lets add the parsed result to cache for usager later on
season = parse_result.season_number if parse_result.season_number else 1
episodes = parse_result.episode_numbers
if season and episodes:
# store episodes as a seperated string
episodeText = "|" + "|".join(map(str, episodes)) + "|"
# get the current timestamp
curTimestamp = int(time.mktime(datetime.datetime.today().timetuple()))
# get quality of release
quality = parse_result.quality
name = ek.ss(name)
# get release group
release_group = parse_result.release_group
# get version
version = parse_result.version
logger.log(u"Added RSS item: [" + name + "] to cache: [" + self.providerID + "]", logger.DEBUG)
return [
"INSERT OR IGNORE INTO [" + self.providerID + "] (name, season, episodes, indexerid, url, time, quality, release_group, version) VALUES (?,?,?,?,?,?,?,?,?)",
[name, season, episodeText, parse_result.show.indexerid, url, curTimestamp, quality, release_group, version]]
示例11: notify_download
def notify_download(self, ep_name, title="Completed:"):
"""
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)
"""
ep_name = ek.ss(ep_name)
if sickbeard.EMAIL_NOTIFY_ONDOWNLOAD:
show = self._parseEp(ep_name)
to = self._generate_recepients(show)
if len(to) == 0:
logger.log('Skipping email notify because there are no configured recepients', logger.WARNING)
else:
try:
msg = MIMEMultipart('alternative')
msg.attach(MIMEText(
"<body style='font-family:Helvetica, Arial, sans-serif;'><h3>SickRage Notification - Downloaded</h3>\n<p>Show: <b>" + re.search(
"(.+?) -.+", ep_name).group(1) + "</b></p>\n<p>Episode: <b>" + re.search(
".+ - (.+?-.+) -.+", ep_name).group(
1) + "</b></p>\n\n<footer style='margin-top: 2.5em; padding: .7em 0; color: #777; border-top: #BBB solid 1px;'>Powered by SickRage.</footer></body>",
'html'))
except:
try:
msg = MIMEText(ep_name)
except:
msg = MIMEText('Episode Downloaded')
msg['Subject'] = 'Downloaded: ' + ep_name
msg['From'] = sickbeard.EMAIL_FROM
msg['To'] = ','.join(to)
msg['Date'] = formatdate(localtime=True)
if self._sendmail(sickbeard.EMAIL_HOST, sickbeard.EMAIL_PORT, sickbeard.EMAIL_FROM, sickbeard.EMAIL_TLS,
sickbeard.EMAIL_USER, sickbeard.EMAIL_PASSWORD, to, msg):
logger.log("Download notification sent to [%s] for '%s'" % (to, ep_name), logger.DEBUG)
else:
logger.log("Download notification ERROR: %s" % self.last_err, logger.ERROR)
示例12: submit_errors
def submit_errors(self):
if not (sickbeard.GIT_USERNAME and sickbeard.GIT_PASSWORD and sickbeard.DEBUG and len(classes.ErrorViewer.errors) > 0):
self.log('Please set your GitHub username and password in the config and enable debug. Unable to submit issue ticket to GitHub!')
return
try:
from versionChecker import CheckVersion
checkversion = CheckVersion()
needs_update = checkversion.check_for_new_version()
commits_behind = checkversion.updater.get_num_commits_behind()
except:
self.log('Could not check if your SickRage is updated, unable to submit issue ticket to GitHub!')
return
if commits_behind is None or commits_behind > 0:
self.log('Please update SickRage, unable to submit issue ticket to GitHub with an outdated version!')
return
if self.submitter_running:
return 'RUNNING'
self.submitter_running = True
gh_org = sickbeard.GIT_ORG or 'SiCKRAGETV'
gh_repo = 'sickrage-issues'
gh = Github(login_or_token=sickbeard.GIT_USERNAME, password=sickbeard.GIT_PASSWORD, user_agent="SiCKRAGE")
try:
# read log file
log_data = None
if os.path.isfile(self.logFile):
with ek.ek(codecs.open, *[self.logFile, 'r', 'utf-8']) as f:
log_data = f.readlines()
for i in range (1 , int(sickbeard.LOG_NR)):
if os.path.isfile(self.logFile + "." + str(i)) and (len(log_data) <= 500):
with ek.ek(codecs.open, *[self.logFile + "." + str(i), 'r', 'utf-8']) as f:
log_data += f.readlines()
log_data = [line for line in reversed(log_data)]
# parse and submit errors to issue tracker
for curError in sorted(classes.ErrorViewer.errors, key=lambda error: error.time, reverse=True)[:500]:
try:
title_Error = str(curError.title)
if not len(title_Error) or title_Error == 'None':
title_Error = re.match("^[A-Z0-9\-\[\] :]+::\s*(.*)$", ek.ss(str(curError.message))).group(1)
# if len(title_Error) > (1024 - len(u"[APP SUBMITTED]: ")):
# 1000 just looks better than 1007 and adds some buffer
if len(title_Error) > 1000:
title_Error = title_Error[0:1000]
except Exception as e:
self.log("Unable to get error title : " + sickbeard.exceptions.ex(e), ERROR)
gist = None
regex = "^(%s)\s+([A-Z]+)\s+([0-9A-Z\-]+)\s*(.*)$" % curError.time
for i, x in enumerate(log_data):
x = ek.ss(x)
match = re.match(regex, x)
if match:
level = match.group(2)
if reverseNames[level] == ERROR:
paste_data = "".join(log_data[i:i+50])
if paste_data:
gist = gh.get_user().create_gist(True, {"sickrage.log": InputFileContent(paste_data)})
break
else:
gist = 'No ERROR found'
message = u"### INFO\n"
message += u"Python Version: **" + sys.version[:120].replace('\n','') + "**\n"
message += u"Operating System: **" + platform.platform() + "**\n"
if not 'Windows' in platform.platform():
try:
message += u"Locale: " + locale.getdefaultlocale()[1] + "\n"
except:
message += u"Locale: unknown" + "\n"
message += u"Branch: **" + sickbeard.BRANCH + "**\n"
message += u"Commit: SiCKRAGETV/[email protected]" + sickbeard.CUR_COMMIT_HASH + "\n"
if gist and gist != 'No ERROR found':
message += u"Link to Log: " + gist.html_url + "\n"
else:
message += u"No Log available with ERRORS: " + "\n"
message += u"### ERROR\n"
message += u"```\n"
message += curError.message + "\n"
message += u"```\n"
message += u"---\n"
message += u"_STAFF NOTIFIED_: @SiCKRAGETV/owners @SiCKRAGETV/moderators"
title_Error = u"[APP SUBMITTED]: " + title_Error
reports = gh.get_organization(gh_org).get_repo(gh_repo).get_issues(state="all")
issue_found = False
issue_id = 0
for report in reports:
if title_Error == report.title:
#.........这里部分代码省略.........
示例13: ex
logger.log(u"Error while trying to retrieve KODI API version for " + host + ": " + ex(e),
logger.WARNING)
return False
# parse the json result
try:
result = json.load(response)
response.close()
logger.log(u"KODI JSON response: " + str(result), logger.DEBUG)
return result # need to return response for parsing
except ValueError, e:
logger.log(u"Unable to decode JSON: " + str(response.read()), logger.WARNING)
return False
except IOError, e:
logger.log(u"Warning: Couldn't contact KODI JSON API at " + ek.ss(url) + " " + ex(e),
logger.WARNING)
return False
def _update_library_json(self, host=None, showName=None):
"""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