Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
# Rename local file before upload.
base_dir = os.path.dirname(file_path)
new_path = os.path.join(base_dir, cloud_file)
os.rename(file_path, new_path)
# Sync first.
_sync()
# Create cloud dirs.
logger.info('Creating directories...')
current_dir = ''
for directory in cloud_dir.split('/'):
current_dir += '/{}'.format(directory)
subprocess.run('{} mkdir "{}"'.format(config.ACD_CLI_PATH, current_dir), shell=True)
# Upload!
logger.info('Uploading file...')
process = subprocess.run('{} upload -o --remove-source-files "{}" "{}"'.format(
config.ACD_CLI_PATH, new_path, cloud_dir), shell=True)
# Check results.
if process.returncode != 0:
logger.error('Bad return code ({}) for file: {}'.format(process.returncode, file_path))
else:
logger.info('Upload succeeded! Deleting original file...')
# If everything went smoothly, add the file name to the original names log.
if not is_subtitles:
open(config.ORIGINAL_NAMES_LOG, 'a', encoding='UTF-8').write(file_path + '\n')
# Sync again when done.
_sync()
else:
logger.info('Couldn\'t guess file info. Skipping...')
video_type = guess_results.get('type')
title = guess_results.get('title')
# Make sure every word starts with a capital letter.
if title:
title = title.title()
if video_type == 'episode' and title:
season = guess_results.get('season')
if season:
episode = guess_results.get('episode')
if episode:
cloud_dir = '{}/{}/Season {:02d}'.format(config.AMAZON_TV_PATH, title, season)
cloud_file = '{} - S{:02d}E{:02d}'.format(title, season, episode)
elif video_type == 'movie' and title:
year = guess_results.get('year')
if year:
cloud_dir = '{}/{} ({})'.format(config.AMAZON_MOVIE_PATH, title, year)
cloud_file = '{} ({})'.format(title, year)
if cloud_dir and cloud_file:
if language_extension:
cloud_file += language_extension
cloud_file += file_extension
logger.info('Cloud path: {}'.format(posixpath.join(cloud_dir, cloud_file)))
# Rename local file before upload.
base_dir = os.path.dirname(file_path)
new_path = os.path.join(base_dir, cloud_file)
os.rename(file_path, new_path)
# Sync first.
_sync()
# Create cloud dirs.
logger.info('Creating directories...')
current_dir = ''
for directory in cloud_dir.split('/'):
fixed_file_path = fixed_file_name + config.DEFAULT_VIDEO_EXTENSION
# Create cloud path based on guessit results.
cloud_dir = None
cloud_file = None
guess_results = guessit(os.path.basename(fixed_file_path))
video_type = guess_results.get('type')
title = guess_results.get('title')
# Make sure every word starts with a capital letter.
if title:
title = title.title()
if video_type == 'episode' and title:
season = guess_results.get('season')
if season:
episode = guess_results.get('episode')
if episode:
cloud_dir = '{}/{}/Season {:02d}'.format(config.AMAZON_TV_PATH, title, season)
cloud_file = '{} - S{:02d}E{:02d}'.format(title, season, episode)
elif video_type == 'movie' and title:
year = guess_results.get('year')
if year:
cloud_dir = '{}/{} ({})'.format(config.AMAZON_MOVIE_PATH, title, year)
cloud_file = '{} ({})'.format(title, year)
if cloud_dir and cloud_file:
if language_extension:
cloud_file += language_extension
cloud_file += file_extension
logger.info('Cloud path: {}'.format(posixpath.join(cloud_dir, cloud_file)))
# Rename local file before upload.
base_dir = os.path.dirname(file_path)
new_path = os.path.join(base_dir, cloud_file)
os.rename(file_path, new_path)
# Sync first.
:param torrent_name: The relevant torrent name.
:param file_path: The file path to process.
"""
filename = os.path.basename(file_path)
category_path = get_categorized_path(os.path.join(torrent_name, filename))
if category_path is not None:
destination_dir = os.path.join(category_path, torrent_name)
# Creates target directory (of category path).
_create_destination_path(destination_dir)
destination_path = os.path.join(destination_dir, filename)
try:
# Move\Copy all relevant files to their location (keep original files for uploading).
handler(file_path, destination_path)
logger.info('{} {} to {}'.format(handler.__name__, file_path, destination_path))
if os.name != 'nt':
subprocess.check_output(['chmod', config.EXTRACTION_FILES_MASK, '-R', destination_dir])
# Get subtitles.
subtitles_paths = None
if config.SHOULD_FIND_SUBTITLES:
subtitles_paths = find_file_subtitles(destination_path)
# Upload files to Amazon.
if config.SHOULD_UPLOAD:
upload_file(destination_path)
if subtitles_paths:
for subtitles_path in subtitles_paths:
upload_file(subtitles_path)
except OSError as ex:
logger.exception('Failed to {} {}: {}'.format(handler.__name__, file_path, ex))
def get_path_non_video(filename):
base_filename = os.path.basename(filename)
base_filename.lower()
extension = os.path.splitext(base_filename)[1]
if extension in MUSIC_EXTENSIONS:
return config.MUSIC_PATH
if extension in SOFTWARE_EXTENSIONS:
return config.APP_PATH
else:
return None
import sys
import logbook
from logbook import Logger
from pyexpander import config
file_handler = logbook.RotatingFileHandler(config.LOGFILE, level=logbook.DEBUG)
console_handler = logbook.StreamHandler(sys.stdout, level=logbook.INFO, bubble=True)
file_handler.push_application()
console_handler.push_application()
def get_logger(name):
"""
Return the logger for the given name.
:param name: The name of the logger.
:return: A logbook Logger.
"""
logger = Logger(name, level=logbook.DEBUG)
return logger
def _extract(archive_path, destination):
"""
Extract archive content to destination.
:param archive_path: The archive to extract.
:param destination: The destination to extract to.
"""
# 'e': extract to current working dir.
# '-y': assume yes to all (overwrite).
process_info = [find_executable(config.EXTRACTION_EXECUTABLE), 'e', '-y', archive_path]
logger.debug('Running {}'.format(process_info))
# Change current working directory since 7Zip only works with e flag.
output = subprocess.check_output(process_info, cwd=destination)
logger.debug('Output: {}'.format(output))
def cleanup_temp(directory):
"""
This function searches for the subdirectory created for extraction and deletes it.
:param directory: The directory to clean.
"""
logger.info('Cleaning up...')
listdir = os.listdir(directory)
if config.EXTRACTION_TEMP_DIR_NAME in listdir:
try:
logger.info('Going to delete {}'.format(os.path.join(directory, config.EXTRACTION_TEMP_DIR_NAME)))
shutil.rmtree(os.path.join(directory, config.EXTRACTION_TEMP_DIR_NAME))
except OSError:
logger.exception('Failed to delete directory {}!'.format(os.path.join(
directory, config.EXTRACTION_TEMP_DIR_NAME)))
def expand_torrent_main():
"""
This main function is designed to be called from commandline.
If an argument (either as the full path, or as a base dir and a file) is provided,
the script will try to expand it.
Else, we assume transmission is calling the script.
"""
logger.info("Py-expander started!")
try:
if len(sys.argv) == 3:
folder = sys.argv[1]
filename = sys.argv[2]
if folder == config.DEFAULT_PATH:
torrent_path = os.path.join(folder, filename)
logger.info("Input is a file: %s" % torrent_path)
else:
torrent_path = folder
logger.info("Input is a dir: %s" % torrent_path)
expand_torrent(torrent_path)
elif len(sys.argv) == 2:
expand_torrent(sys.argv[1])
else:
expand_torrent_from_transmission()
except:
logger.exception("Critical exception occurred: ")
raise
def get_path_video(filename):
guess = guessit.guess_file_info(filename)
if guess[u'type'] == u'episode':
series = guess.get(u'series', u'').title()
season = guess.get(u'season', u'')
return config.TV_PATH.format(series=series, season=season)
elif guess[u'type'] == u'movie':
title = guess.get(u'title', u'').title()
year = guess.get(u'year', u'')
return config.MOVIE_PATH.format(title=title, year=year)
else:
return None