本文整理汇总了Python中sickrage.helper.common.sanitize_filename函数的典型用法代码示例。如果您正苦于以下问题:Python sanitize_filename函数的具体用法?Python sanitize_filename怎么用?Python sanitize_filename使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了sanitize_filename函数的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _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
示例2: test_sanitize_filename
def test_sanitize_filename(self):
"""
Test sanitize filename
"""
test_cases = {
None: '',
42: '',
'': '',
'filename': 'filename',
'fi\\le/na*me': 'fi-le-na-me',
'fi:le"na<me': 'filename',
'fi>le|na?me': 'filename',
' . file\u2122name. .': 'file-u2122name', # pylint: disable=anomalous-unicode-escape-in-string
}
unicode_test_cases = {
u'': u'',
u'filename': u'filename',
u'fi\\le/na*me': u'fi-le-na-me',
u'fi:le"na<me': u'filename',
u'fi>le|na?me': u'filename',
u' . file\u2122name. .': u'filename',
}
for tests in test_cases, unicode_test_cases:
for (filename, result) in tests.iteritems():
self.assertEqual(sanitize_filename(filename), result)
示例3: addDefaultShow
def addDefaultShow(indexer, indexer_id, name, status):
"""
Adds a new show with the default settings
"""
if not Show.find(sickbeard.showList, int(indexer_id)):
logger.log(u"Adding show " + str(indexer_id))
root_dirs = sickbeard.ROOT_DIRS.split('|')
try:
location = root_dirs[int(root_dirs[0]) + 1]
except Exception:
location = None
if location:
showPath = ek(os.path.join, location, sanitize_filename(name))
dir_exists = helpers.makeDir(showPath)
if not dir_exists:
logger.log(u"Unable to create the folder %s , can't add the show" % showPath, logger.WARNING)
return
else:
helpers.chmodAsParent(showPath)
sickbeard.showQueueScheduler.action.addShow(int(indexer), int(indexer_id), showPath,
default_status=status,
quality=int(sickbeard.QUALITY_DEFAULT),
flatten_folders=int(sickbeard.FLATTEN_FOLDERS_DEFAULT),
paused=sickbeard.TRAKT_START_PAUSED,
default_status_after=status)
else:
logger.log(u"There was an error creating the show, no root directory setting found", logger.WARNING)
return
示例4: _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
示例5: 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)
示例6: test_sanitize_filename
def test_sanitize_filename(self):
"""
Test sanitize filename
"""
test_cases = {
None: '',
42: '',
b'': '',
b'filename': 'filename',
b'fi\\le/na*me': 'fi-le-na-me',
b'fi:le"na<me': 'filename',
b'fi>le|na?me': 'filename',
b' . file\u2122name. .': 'filename',
}
unicode_test_cases = {
'': '',
'filename': 'filename',
'fi\\le/na*me': 'fi-le-na-me',
'fi:le"na<me': 'filename',
'fi>le|na?me': 'filename',
' . file™name. .': 'filename',
}
for tests in test_cases, unicode_test_cases:
for (filename, result) in six.iteritems(tests):
self.assertEqual(sanitize_filename(filename), result)
示例7: test_sanitize_filename
def test_sanitize_filename(self):
tests = {
None: '',
42: '',
'': '',
u'': u'',
'filename': 'filename',
u'filename': u'filename',
'fi\\le/na*me': 'fi-le-na-me',
u'fi\\le/na*me': u'fi-le-na-me',
'fi:le"na<me': 'filename',
u'fi:le"na<me': u'filename',
'fi>le|na?me': 'filename',
u'fi>le|na?me': u'filename',
' . file\u2122name. .': 'file-u2122name',
u' . file\u2122name. .': u'filename',
}
for (filename, result) in tests.iteritems():
self.assertEqual(sanitize_filename(filename), result)
示例8: _make_url
def _make_url(self, result):
if not result:
return '', ''
filename = u''
urls = [result.url]
if result.url.startswith('magnet'):
torrent_hash = self.hash_from_magnet(result.url)
if not torrent_hash:
return urls, filename
try:
torrent_name = re.findall('dn=([^&]+)', result.url)[0]
except Exception:
torrent_name = 'NO_DOWNLOAD_NAME'
urls = [x.format(torrent_hash=torrent_hash, torrent_name=torrent_name) for x in self.bt_cache_urls]
filename = ek(join, self._get_storage_dir(), sanitize_filename(result.name) + '.' + self.provider_type)
return urls, filename
示例9: run
def run(self):
ShowQueueItem.run(self)
logger.log(u"Starting to add show {0}".format("by ShowDir: {0}".format(self.showDir) if self.showDir else "by Indexer Id: {0}".format(self.indexer_id)))
# make sure the Indexer IDs are valid
try:
lINDEXER_API_PARMS = sickbeard.indexerApi(self.indexer).api_params.copy()
if self.lang:
lINDEXER_API_PARMS['language'] = self.lang
logger.log(u"" + str(sickbeard.indexerApi(self.indexer).name) + ": " + repr(lINDEXER_API_PARMS))
t = sickbeard.indexerApi(self.indexer).indexer(**lINDEXER_API_PARMS)
s = t[self.indexer_id]
# Let's try to create the show Dir if it's not provided. This way we force the show dir to build build using the
# Indexers provided series name
if not self.showDir and self.root_dir:
show_name = get_showname_from_indexer(self.indexer, self.indexer_id, self.lang)
if show_name:
self.showDir = ek(os.path.join, self.root_dir, sanitize_filename(show_name))
dir_exists = makeDir(self.showDir)
if not dir_exists:
logger.log(u"Unable to create the folder {0}, can't add the show".format(self.showDir))
return
chmodAsParent(self.showDir)
else:
logger.log(u"Unable to get a show {0}, can't add the show".format(self.showDir))
return
# this usually only happens if they have an NFO in their show dir which gave us a Indexer ID that has no proper english version of the show
if getattr(s, 'seriesname', None) is None:
logger.log(u"Show in {} has no name on {}, probably searched with the wrong language.".format
(self.showDir, sickbeard.indexerApi(self.indexer).name), logger.ERROR)
ui.notifications.error("Unable to add show",
"Show in " + self.showDir + " has no name on " + str(sickbeard.indexerApi(
self.indexer).name) + ", probably the wrong language. Delete .nfo and add manually in the correct language.")
self._finishEarly()
return
# if the show has no episodes/seasons
if not s:
logger.log(u"Show " + str(s['seriesname']) + " is on " + str(
sickbeard.indexerApi(self.indexer).name) + " but contains no season/episode data.")
ui.notifications.error("Unable to add show",
"Show " + str(s['seriesname']) + " is on " + str(sickbeard.indexerApi(
self.indexer).name) + " but contains no season/episode data.")
self._finishEarly()
return
except Exception as e:
logger.log(u"%s Error while loading information from indexer %s. Error: %r" % (self.indexer_id, sickbeard.indexerApi(self.indexer).name, ex(e)), logger.ERROR)
# logger.log(u"Show name with ID %s doesn't exist on %s anymore. If you are using trakt, it will be removed from your TRAKT watchlist. If you are adding manually, try removing the nfo and adding again" %
# (self.indexer_id, sickbeard.indexerApi(self.indexer).name), logger.WARNING)
ui.notifications.error(
"Unable to add show",
"Unable to look up the show in %s on %s using ID %s, not using the NFO. Delete .nfo and try adding manually again." %
(self.showDir, sickbeard.indexerApi(self.indexer).name, self.indexer_id)
)
if sickbeard.USE_TRAKT:
trakt_id = sickbeard.indexerApi(self.indexer).config['trakt_id']
trakt_api = TraktAPI(sickbeard.SSL_VERIFY, sickbeard.TRAKT_TIMEOUT)
title = self.showDir.split("/")[-1]
data = {
'shows': [
{
'title': title,
'ids': {}
}
]
}
if trakt_id == 'tvdb_id':
data['shows'][0]['ids']['tvdb'] = self.indexer_id
else:
data['shows'][0]['ids']['tvrage'] = self.indexer_id
trakt_api.traktRequest("sync/watchlist/remove", data, method='POST')
self._finishEarly()
return
try:
newShow = TVShow(self.indexer, self.indexer_id, self.lang)
newShow.load_from_indexer()
self.show = newShow
# set up initial values
self.show.location = self.showDir
self.show.subtitles = self.subtitles if self.subtitles is not None else sickbeard.SUBTITLES_DEFAULT
self.show.quality = self.quality if self.quality else sickbeard.QUALITY_DEFAULT
self.show.flatten_folders = self.flatten_folders if self.flatten_folders is not None else sickbeard.FLATTEN_FOLDERS_DEFAULT
self.show.anime = self.anime if self.anime is not None else sickbeard.ANIME_DEFAULT
self.show.scene = self.scene if self.scene is not None else sickbeard.SCENE_DEFAULT
#.........这里部分代码省略.........
示例10: run
def run(self): # pylint: disable=too-many-branches, too-many-statements, too-many-return-statements
super(QueueItemAdd, self).run()
if self.showDir:
try:
assert isinstance(self.showDir, six.text_type)
except AssertionError:
logger.log(traceback.format_exc(), logger.WARNING)
self._finish_early()
return
logger.log('Starting to add show {0}'.format('by ShowDir: {0}'.format(self.showDir) if self.showDir else 'by Indexer Id: {0}'.format(self.indexer_id)))
# make sure the Indexer IDs are valid
try:
lINDEXER_API_PARMS = sickbeard.indexerApi(self.indexer).api_params.copy()
lINDEXER_API_PARMS['language'] = self.lang or sickbeard.INDEXER_DEFAULT_LANGUAGE
logger.log('{0}: {1!r}'.format(sickbeard.indexerApi(self.indexer).name, lINDEXER_API_PARMS))
t = sickbeard.indexerApi(self.indexer).indexer(**lINDEXER_API_PARMS)
s = t[self.indexer_id]
# Let's try to create the show Dir if it's not provided. This way we force the show dir to build build using the
# Indexers provided series name
if self.root_dir and not self.showDir:
show_name = get_showname_from_indexer(self.indexer, self.indexer_id, self.lang)
if not show_name:
logger.log('Unable to get a show {0}, can\'t add the show'.format(self.showDir))
self._finish_early()
return
self.showDir = ek(os.path.join, self.root_dir, sanitize_filename(show_name))
dir_exists = makeDir(self.showDir)
if not dir_exists:
logger.log('Unable to create the folder {0}, can\'t add the show'.format(self.showDir))
self._finish_early()
return
chmodAsParent(self.showDir)
# this usually only happens if they have an NFO in their show dir which gave us a Indexer ID that has no proper english version of the show
if getattr(s, 'seriesname', None) is None:
error_string = 'Show in {0} has no name on {1}, probably searched with the wrong language. Delete .nfo and add manually in the correct language.'.format(
self.showDir, sickbeard.indexerApi(self.indexer).name)
logger.log(error_string, logger.WARNING)
ui.notifications.error('Unable to add show', error_string)
self._finish_early()
return
# if the show has no episodes/seasons
if not s:
error_string = 'Show {0} is on {1} but contains no season/episode data.'.format(
s[b'seriesname'], sickbeard.indexerApi(self.indexer).name)
logger.log(error_string)
ui.notifications.error('Unable to add show', error_string)
self._finish_early()
return
except Exception as error:
error_string = 'Unable to look up the show in {0} on {1} using ID {2}, not using the NFO. Delete .nfo and try adding manually again.'.format(
self.showDir, sickbeard.indexerApi(self.indexer).name, self.indexer_id)
logger.log('{0}: {1}'.format(error_string, error), logger.ERROR)
ui.notifications.error(
'Unable to add show', error_string)
if sickbeard.USE_TRAKT:
trakt_id = sickbeard.indexerApi(self.indexer).config[b'trakt_id']
trakt_api = TraktAPI(sickbeard.SSL_VERIFY, sickbeard.TRAKT_TIMEOUT)
title = self.showDir.split('/')[-1]
data = {
'shows': [
{
'title': title,
'ids': {}
}
]
}
if trakt_id == 'tvdb_id':
data[b'shows'][0][b'ids'][b'tvdb'] = self.indexer_id
else:
data[b'shows'][0][b'ids'][b'tvrage'] = self.indexer_id
trakt_api.traktRequest('sync/watchlist/remove', data, method='POST')
self._finish_early()
return
try:
try:
newShow = TVShow(self.indexer, self.indexer_id, self.lang)
except MultipleShowObjectsException as error:
# If we have the show in our list, but the location is wrong, lets fix it and refresh!
#.........这里部分代码省略.........
示例11: sanitizeFileName
def sanitizeFileName(name):
return sanitize_filename(name)
示例12: addNewShow
def addNewShow(self, whichSeries=None, indexerLang=None, rootDir=None, defaultStatus=None,
quality_preset=None, anyQualities=None, bestQualities=None, flatten_folders=None, subtitles=None,
fullShowPath=None, other_shows=None, skipShow=None, providedIndexer=None, anime=None,
scene=None, blacklist=None, whitelist=None, defaultStatusAfter=None):
"""
Receive tvdb id, dir, and other options and create a show from them. If extra show dirs are
provided then it forwards back to newShow, if not it goes to /home.
"""
provided_indexer = providedIndexer
allowed_qualities = anyQualities
preferred_qualities = bestQualities
indexer_lang = sickbeard.INDEXER_DEFAULT_LANGUAGE if not indexerLang else indexerLang
# grab our list of other dirs if given
if not other_shows:
other_shows = []
elif not isinstance(other_shows, list):
other_shows = [other_shows]
def finishAddShow():
# if there are no extra shows then go home
if not other_shows:
return self.redirect('/home/')
# peel off the next one
next_show_dir = other_shows[0]
rest_of_show_dirs = other_shows[1:]
# go to add the next show
return self.newShow(next_show_dir, rest_of_show_dirs)
# if we're skipping then behave accordingly
if skipShow:
return finishAddShow()
# sanity check on our inputs
if (not rootDir and not fullShowPath) or not whichSeries:
return 'Missing params, no Indexer ID or folder:{series!r} and {root!r}/{path!r}'.format(
series=whichSeries, root=rootDir, path=fullShowPath)
# figure out what show we're adding and where
series_pieces = whichSeries.split('|')
if (whichSeries and rootDir) or (whichSeries and fullShowPath and len(series_pieces) > 1):
if len(series_pieces) < 6:
logger.log(u'Unable to add show due to show selection. Not anough arguments: %s' % (repr(series_pieces)),
logger.ERROR)
ui.notifications.error('Unknown error. Unable to add show due to problem with show selection.')
return self.redirect('/addShows/existingShows/')
indexer = int(series_pieces[1])
indexer_id = int(series_pieces[3])
# Show name was sent in UTF-8 in the form
show_name = series_pieces[4].decode('utf-8')
else:
# if no indexer was provided use the default indexer set in General settings
if not provided_indexer:
provided_indexer = sickbeard.INDEXER_DEFAULT
indexer = int(provided_indexer)
indexer_id = int(whichSeries)
show_name = ek(os.path.basename, ek(os.path.normpath, fullShowPath))
# use the whole path if it's given, or else append the show name to the root dir to get the full show path
if fullShowPath:
show_dir = ek(os.path.normpath, fullShowPath)
else:
show_dir = ek(os.path.join, rootDir, sanitize_filename(show_name))
# blanket policy - if the dir exists you should have used 'add existing show' numbnuts
if ek(os.path.isdir, show_dir) and not fullShowPath:
ui.notifications.error('Unable to add show', 'Folder {path} exists already'.format(path=show_dir))
return self.redirect('/addShows/existingShows/')
# don't create show dir if config says not to
if sickbeard.ADD_SHOWS_WO_DIR:
logger.log(u'Skipping initial creation of {path} due to config.ini setting'.format
(path=show_dir))
else:
dir_exists = helpers.makeDir(show_dir)
if not dir_exists:
logger.log(u'Unable to create the folder {path}, can\'t add the show'.format
(path=show_dir), logger.ERROR)
ui.notifications.error('Unable to add show',
'Unable to create the folder {path}, can\'t add the show'.format(path=show_dir))
# Don't redirect to default page because user wants to see the new show
return self.redirect('/home/')
else:
helpers.chmodAsParent(show_dir)
# prepare the inputs for passing along
scene = config.checkbox_to_value(scene)
anime = config.checkbox_to_value(anime)
flatten_folders = config.checkbox_to_value(flatten_folders)
subtitles = config.checkbox_to_value(subtitles)
if whitelist:
whitelist = short_group_names(whitelist)
if blacklist:
blacklist = short_group_names(blacklist)
#.........这里部分代码省略.........