Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- # version 1
- """
- This script is meant to be run on a seedbox with deluge. It will extract .rars and transfer the
- content to your home computer or NAS running Sonarr/Radarr where the fill will be imported.
- This script has been tested with:
- - Linux (tested with Ubuntu 16.04)
- - unzip and unrar are required: `sudo apt-get install unzip unrar lftp python3 python3-pip`
- - Modules required: pip3 install requests glob2
- - Deluge with Label and Execute plugins
- - Sonarr and Radarr on a different machine
- Usage on a different environment may require additional tweaks. MAKE SURE THE
- EXECUTABLE BIT IS SET ON THIS FILE.
- Known bugs: Apparently Sonarr/Radarr talk directly with deluge and overwrite whatever API call
- is being made by the script, so files will only be copied instead of moved on import. Remember to
- clean up your /import/complete/ folder!
- """
- from collections import namedtuple
- import glob2
- import os
- import requests
- import shutil
- from syslog import syslog
- import sys
- import time
- # -- Configs
- commands = {'zip': 'unzip -u', 'rar': 'unrar -o- e'}
- extraction_root = '/home/deluge/sync/'
- lockfile = '/home/deluge/deluge.lock'
- deluge = namedtuple('DelugeConfig', 'url password session_id')
- deluge.url = 'https://localhost:8112/json'
- deluge.password = 'password'
- sonarr = namedtuple('SonarrConfig', 'url api_key label')
- sonarr.url = 'https://remote.server:9898/api'
- sonarr.api_key = '123456789'
- sonarr.label = 'sonarr'
- radarr = namedtuple('RadarrConfig', 'url api_key label')
- radarr.url = 'https://remote.server:7878/api'
- radarr.api_key = '123456789'
- radarr.label = 'radarr'
- lftpcom = 'lftp -c "open -u username,password -p 22 sftp://remote.server; set sftp:auto-confirm yes; set ssl:verify-certificate false; mirror -c --ignore-time -R -P 5 ' + extraction_dir + ' /incoming/; mv /incoming/' + torrent.name + '/ /incoming/complete/"'
- # -- Arguments
- torrent = namedtuple('Torrent', 'id name path dir label')
- torrent.id = sys.argv[1]
- torrent.name = sys.argv[2]
- torrent.path = sys.argv[3]
- torrent.dir = os.path.join(torrent.path, torrent.name)
- torrent.label = ''
- syslog(torrent.name + ' - Preparing torrent for extraction: ' + torrent.dir)
- def update_rights(path, group, mode=0o664):
- shutil.chown(path, group=group)
- os.chmod(path, mode)
- # -- Fetch torrent label
- syslog(torrent.name + ' - Authenticating into deluge.')
- auth_headers = {'content-type': 'application/json', 'accept': 'application/json'}
- auth_data = {'method': 'auth.login', 'params': [deluge.password], 'id': 1}
- response = requests.post(deluge.url, json=auth_data, headers=auth_headers, verify=False)
- if response.status_code != 200 and not response.json()['result']:
- sys.exit('Unable to authenticate to deluge')
- deluge.session_id = response.cookies['_session_id']
- syslog(torrent.name + ' - Got deluge session ID ' + deluge.session_id)
- syslog(torrent.name + ' - Fetching torrent label from deluge.')
- info_headers = {'content-type': 'application/json', 'accept': 'application/json'}
- info_cookies = dict(_session_id=deluge.session_id)
- info_data = {'method': 'web.get_torrent_status', 'params': [torrent.id, ['label']], 'id': 1}
- response = requests.post(deluge.url, json=info_data, headers=info_headers, cookies=info_cookies, verify=False)
- if response.status_code != 200:
- sys.exit('Unable to fetch torrent label')
- torrent.label = response.json()['result']['label']
- syslog(torrent.name + ' - Got torrent label: ' + torrent.label)
- pvr = next((x for x in (sonarr, radarr) if x.label == torrent.label), None)
- if not pvr:
- syslog(torrent.name + ' - Not a Sonarr/Radarr tracked download. Skipping extraction.')
- sys.exit(0)
- ### Wait til lockfile is gone, then create lockfile
- syslog(torrent.name + ' - Checking for lock file ...')
- locked = False
- while os.path.exists(lockfile):
- if locked == False:
- syslog(torrent.name + ' - Another torrent is currently being processed. Sleeping ...')
- locked = True
- time.sleep(10)
- print('Another torrent is currently being processed. Sleeping ...')
- if not os.path.exists(lockfile):
- lf = open(lockfile, 'w')
- lf.write(torrent.name)
- lf.close()
- syslog(torrent.name + ' - Created lock file.')
- if not os.path.exists(lockfile):
- sys.exit(torrent.name + ' - Cannot create lock file')
- # -- Extract files
- extraction_dir = os.path.join(extraction_root, torrent.name)
- extracted = False
- if not os.path.isdir(extraction_dir):
- os.makedirs(extraction_dir)
- os.chdir(torrent.dir)
- for ext, command in commands.items():
- for file in glob2.glob('**/*.' + ext): ######### will mess up if only subs are rar'd and movie is not...
- file_path = os.path.join(torrent.dir, file)
- syslog(torrent.name + ' - Extracting ' + file_path + ' to ' + extraction_dir)
- # TODO: How to handle extraction errors (ie: CRC errors)?
- os.system(command + ' "' + file + '" "' + extraction_dir + '"')
- extracted = True
- if not extracted:
- syslog(torrent.name + ' - Nothing to extract. Creating symlinks.')
- shutil.rmtree(extraction_dir, ignore_errors=True)
- if os.path.islink(extraction_dir):
- os.unlink(extraction_dir)
- os.symlink(torrent.dir, extraction_dir)
- # -- Copy extra files (srt, nfo, ...)
- #syslog(torrent.name + ' - Fetching extra file types to copy.')
- #
- #extras_headers = {'accept': 'application/json', 'X-Api-Key': pvr.api_key}
- #response = requests.get(pvr.url + '/config/mediamanagement', headers=extras_headers)
- #
- #extra_file_types = response.json()['extraFileExtensions']
- #
- #syslog(torrent.name + ' - Copying extra files: ' + extra_file_types)
- #for ext in extra_file_types.split(','):
- # for file in glob2.glob('*.' + ext):
- # shutil.copy2(file, extraction_dir)
- ### TRANSFER FILES
- syslog(torrent.name + ' - Starting file transfer ...')
- os.system(lftpcom)
- syslog(torrent.name + ' - Transfer complete.')
- # -- Notify Sonarr/Radarr
- notify_headers = {'content-type': 'application/json', 'accept': 'application/json', 'X-Api-Key': pvr.api_key}
- notify_data = {'name': 'DownloadedEpisodesScan', 'importMode': 'Move', 'downloadClientId': torrent.id.upper(),
- 'path': extraction_dir}
- syslog(torrent.name + ' - Asking PVR API to scan extracted files.')
- response = requests.post(pvr.url + '/command', json=notify_data, headers=notify_headers)
- if not response.status_code >= 200 and response.status_code < 300:
- syslog(torrent.name + ' - Could not notify Sonarr/Radarr of extracted file.')
- ### DELETE FILES
- shutil.rmtree(extraction_dir, ignore_errors=True)
- if os.path.islink(extraction_dir):
- os.unlink(extraction_dir)
- os.remove(lockfile)
- syslog(torrent.name + ' - Processing complete.')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement