Created
March 29, 2018 19:20
-
-
Save TRaSH-/dea2b2f9b0420e8982b9d61cb12ce000 to your computer and use it in GitHub Desktop.
AutoSubPostProcess for AutoSub
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import os, urllib, sys, datetime, codecs, subprocess, shutil, re, errno, json,urllib2, base64 | |
# Here goes the information about Kodi | |
KodiHost = 'xxx.xxx.xxx.xxx' | |
KodiPort = 'xx' | |
KodiUserName = 'kodi' | |
KodiPassword = '' | |
http_address = 'http://%s:%s/jsonrpc' % (KodiHost, KodiPort) | |
#----------------------------------------------------------------------------------------------------# | |
# Put her the Source and Destination folders you want to use # | |
# Do not use the same folder for both, because autosub will try to find a sub for the renamed video. # | |
# src_loc must be the root locatie where autosub is searching from("Serie Folder" in the config) # | |
#----------------------------------------------------------------------------------------------------# | |
src_loc = os.path.normpath('/mnt/share/tv-downloads') | |
dst_loc = os.path.normpath('/mnt/share/tv') | |
# This is the location of the history file | |
# The history file will be written in csv format so it can be red by excel. | |
HistoryLoc = os.path.normpath('/opt/autosub/AutoSubPostProcessHistory.csv') | |
# List of characters not allowed in a filename | |
not_allowed_table = dict.fromkeys(map(ord, '/\:*?"<>|'), None) | |
# Copy the arguments from AutoSub to variables for easy changing. | |
sub = sys.argv[1] | |
video = sys.argv[2] | |
Serie = sys.argv[4] | |
Season = sys.argv[5] | |
Episode = sys.argv[6] | |
# This is the class for acessing kodi | |
class XBMCJSON: | |
def __init__(self, server): | |
self.server = server | |
self.version = '2.0' | |
def __call__(self, **kwargs): | |
method = '.'.join(map(str, self.n)) | |
self.n = [] | |
return XBMCJSON.__dict__['Request'](self, method, kwargs) | |
def __getattr__(self,name): | |
if not self.__dict__.has_key('n'): | |
self.n=[] | |
self.n.append(name) | |
return self | |
def Request(self, method, kwargs): | |
data = [{}] | |
data[0]['method'] = method | |
data[0]['params'] = kwargs | |
data[0]['jsonrpc'] = self.version | |
data[0]['id'] = 1 | |
data = json.JSONEncoder().encode(data) | |
content_length = len(data) | |
content = { | |
'Content-Type': 'application/json', | |
'Content-Length': content_length, | |
} | |
request = urllib2.Request(self.server, data, content) | |
base64string = base64.encodestring('%s:%s' % (KodiUserName, KodiPassword)).replace('\n', '') | |
request.add_header("Authorization", "Basic %s" % base64string) | |
f = urllib2.urlopen(request) | |
response = f.read() | |
f.close() | |
response = json.JSONDecoder().decode(response) | |
try: | |
return response[0]['result'] | |
except: | |
return response[0]['error'] | |
# Here Starts the main program | |
# Compose the Name for the Season folder | |
SeasonDir = 'Season ' + Season | |
# Here we define the EpisodeNAme | |
EpisodeName = Serie + 'S' + Season + 'E' + Episode | |
# Opening for Append of the history file so we will know want the original filename was in case we have to search for a better subfile | |
# or something went wrong. The file will be written in CSV format so it can be used directly in excel. | |
if not os.path.isfile(HistoryLoc): | |
HistoryFile = codecs.open(HistoryLoc,encoding='cp1252',mode='a') | |
HistoryFile.write('"Datum/Tijd","Location","Title","Original Filename"\r\n') | |
else: | |
HistoryFile = codecs.open(HistoryLoc,encoding='cp1252',mode='a') | |
# Here we create the new location for the sub file | |
# First we find the Serie name. | |
# I decided to use the directoryname because that is created by sickbeard and is exactly equal to the seriename as used by sickbeard. | |
# So we get the name from the last directory of the full path | |
# In case of the serie "Marvel Agents of S.H.I.E.L.D." we have to add an extra dot to the name because a directory name cannot end with a dot and is removed when creating the direcory by sickbeard | |
# but sickbeard uses the name including the last dot. | |
Temp, Serie =os.path.split(video) | |
Temp, Serie = os.path.split(Temp) | |
Temp, Serie = os.path.split(Temp) | |
if "Marvel's Agents of S.H.I.E.L.D" in Serie: | |
Serie = Serie + '.' | |
# All info is gathered and we build the destination path for the file moving operation | |
# - Split the source in a path and a filename | |
# - Retrieve the file extension of the video file | |
# - Construct the new locations | |
# - Create a "Seizoen" subdirectory if not yet present | |
sub_name, srt_ext = os.path.splitext(sub) | |
sub_name, srt_ext2 = os.path.splitext(sub_name) | |
if srt_ext2.lower() == ".nl" or srt_ext2.lower() ==".nl" : | |
srt_ext = srt_ext2 + srt_ext | |
src_path, video_file = os.path.split(video) | |
video_name, video_ext = os.path.splitext(video_file) | |
SeasonPath = unicode(src_path.replace(src_loc, dst_loc,1)).encode('utf-8') | |
nfo_src = os.path.join(src_path, video_name + ".nfo") | |
jpg_src = os.path.join(src_path, video_name + "-thumb.jpg") | |
video_name = re.sub(' +','.',video_name) | |
nfo_dst = os.path.join(SeasonPath,video_name + ".nfo") | |
jpg_dst = os.path.join(SeasonPath,video_name + "-thumb.jpg") | |
Episode_Title = video_name + video_ext | |
video_dst = os.path.join(SeasonPath,Episode_Title) | |
sub_dst = video_dst.replace(video_ext,srt_ext) | |
if not os.path.isdir(SeasonPath): | |
try: | |
os.makedirs(SeasonPath) | |
except: | |
sys.stdout.write('- Could not create destination folder') | |
sys.stdout.flush() | |
sys.exit(1) | |
# Here we check whether the video file already exits. | |
# if so we return to autosub. | |
if os.path.isfile(video_dst): | |
sys.stdout.write( " - " + video_dst + " Already exists!") | |
sys.stdout.flush() | |
sys.exit(1) | |
# Move the video file | |
try: | |
shutil.move(video,video_dst) | |
open(video,'w').close() | |
# move the sub file | |
try: | |
shutil.move(sub,sub_dst) | |
open(sub,'w').close() | |
except: | |
sys.stdout.write(" - Unable to move the sub file") | |
sys.stdout.flush() | |
sys.exit(1) | |
except: | |
sys.stdout.write(" - Unable to move the video file") | |
sys.stdout.flush() | |
sys.exit(1) | |
# Move the .nfo file | |
try: | |
shutil.move(nfo_src,nfo_dst) | |
open(nfo_src,'w').close() | |
except: | |
sys.stdout.write(" - Unable to move the nfo file") | |
sys.stdout.flush() | |
# Move the jpg file | |
try: | |
shutil.move(jpg_src,jpg_dst) | |
open(jpg_src,'w').close() | |
except: | |
sys.stdout.write(" - Unable to move the jpg file") | |
sys.stdout.flush() | |
# Now we give kodi the command to rescan the library | |
#xbmc = XBMCJSON(http_address) | |
#xbmc.VideoLibrary.Scan() | |
LogTime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") | |
HistoryFile.write('"' + LogTime + '"' + ',"' + SeasonPath + '"' + ',"' + Episode_Title + '"'+ ',"' + video_file + '"\r\n') | |
HistoryFile.close() | |
sys.stdout.write(" - Postprocess routine finished succesfull") | |
sys.stdout.flush() | |
sys.exit(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment