-
Notifications
You must be signed in to change notification settings - Fork 22
/
theaterTrailers.py
executable file
·464 lines (410 loc) · 18.7 KB
/
theaterTrailers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
#!/usr/bin/python
from __future__ import unicode_literals
from datetime import datetime
import youtube_dl
import tmdbsimple as tmdb
import logging
import json
import shutil
import re
import os
import time
import requests
#Local Modules
from ConfigMapper.configMapper import ConfigSectionMap
# Global items
MovieDict = {}
MovieList = []
DirsDict = {}
ResultsDict = {}
search = tmdb.Search()
# Sets the directory TheaterTrailers is running from
TheaterTrailersHome = os.path.dirname(os.path.realpath(__file__))
# Sets the location of the trailers.conf file
configfile = os.path.join(TheaterTrailersHome, 'Config', 'trailers.conf')
# Config Variables
tmdb.API_KEY = ConfigSectionMap("main", configfile)['tmdb_api_key']
playlistEndVar = int(ConfigSectionMap("main", configfile)['playlistendvar'])
youtubePlaylist = ConfigSectionMap("main", configfile)['youtubeplaylist']
runCleanup = ConfigSectionMap("main", configfile)['runcleanup']
if ConfigSectionMap("main", configfile)['trailerlocation'] == "":
trailerLocation = os.path.join(TheaterTrailersHome, 'Trailers')
else:
trailerLocation = ConfigSectionMap("main", configfile)['trailerlocation']
redBand = ConfigSectionMap("main", configfile)['redband']
plexHost = ConfigSectionMap("main", configfile)['plexhost']
plexPort = ConfigSectionMap("main", configfile)['plexport']
plexToken = ConfigSectionMap("main", configfile)['plextoken']
loggingLevel = ConfigSectionMap("main", configfile)['logginglevel']
radarrHost = ConfigSectionMap("main", configfile)['radarrhost']
radarrPort = ConfigSectionMap("main", configfile)['radarrport']
radarrKey = ConfigSectionMap("main", configfile)['radarrkey']
pushToRadarr = ConfigSectionMap("main", configfile)['pushtoradarr']
pullFromRadarr = ConfigSectionMap("main", configfile)['pullfromradarr']
radarrRootFolderPath = ConfigSectionMap("main", configfile)['radarrrootfolderpath']
radarrURI = ConfigSectionMap("main", configfile)['radarruri']
cacheRefresh = int(ConfigSectionMap("main", configfile)['cacherefresh'])
if not os.path.exists(os.path.join(TheaterTrailersHome, "Cache")):
os.makedirs(os.path.join(TheaterTrailersHome, "Cache"))
cacheDir = os.path.join(TheaterTrailersHome, "Cache")
if not os.path.isfile(os.path.join(cacheDir, 'theaterTrailersCache.json')):
with open(os.path.join(cacheDir, 'theaterTrailersCache.json'), 'w') as touch:
pass
# Pause in seconds. TMDB has a rate limit of 40 requests per 10 seconds
pauseRate = .25
# Logging options
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
if not os.path.isdir(os.path.join(TheaterTrailersHome, 'Logs')):
os.makedirs(os.path.join(TheaterTrailersHome, 'Logs'))
if os.path.isfile(os.path.join(TheaterTrailersHome, 'theaterTrailers.log')):
shutil.move(os.path.join(TheaterTrailersHome, 'theaterTrailers.log'), os.path.join(TheaterTrailersHome, 'Logs', 'theaterTrailers.log'))
fh = logging.FileHandler(os.path.join(TheaterTrailersHome, 'Logs', 'theaterTrailers.log'))
fh.setLevel(logging.INFO)
fh.setFormatter(formatter)
logger.addHandler(fh)
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
ch.setFormatter(formatter)
logger.addHandler(ch)
# Sets the Current Date in ISO format
currentDate = time.strftime('%Y-%m-%d')
# Main detirmines the flow of the module
def main():
if runCleanup == 'True':
cleanup()
checkCashe()
infoDownloader(youtubePlaylist)
# Querries tmdb and updates the release date in the dictionary
for item in MovieList:
try:
if MovieDict['item']['Release Date'] in MovieDict:
continue
except KeyError as ke1:
with open(os.path.join(cacheDir, 'theaterTrailersCache.json'), 'r') as fp:
try:
DB_Dict = json.load(fp)
MovieDict[item]['Release Date'] = DB_Dict[keymaker(item)]['Release Date']
except (KeyError, ValueError) as e:
tmdbInfo(item)
tempList = search.results
tempList.reverse()
for s in tempList:
releaseDate = s['release_date']
movieTMDBID = s['id']
releaseDateList = releaseDate.split('-')
try:
if (int(releaseDateList[0]) - 1) <= int(MovieDict[item]['Trailer Release']) <= (int(releaseDateList[0]) + 1):
MovieDict[item]['Release Date'] = releaseDate
MovieDict[item]['TMDB ID'] = movieTMDBID
except ValueError as e:
logger.error("ValueError for {0} {1} 119".format(item, e))
pass
except KeyError as e:
logger.error("KeyError for {0} {1} 122".format(item, e))
try:
MovieDict[item]['Release Date'] = releaseDate
MovieDict[item]['TMDB ID'] = movieTMDBID
except ValueError as e:
logger.error("ValueError {0} 127".format(e))
pass
except AttributeError as ae1:
logger.error("AttributeError {0} 131".format(item))
continue
# Adds the movies to the cache
title = item.strip()
try:
yearVar = MovieDict[item]['Release Date'].split('-')
trailerYear = yearVar[0].strip()
updateCache(MovieDict[item]['url'], title, trailerYear)
except KeyError as error:
logger.warning("{0} is missing its release date".format(item))
def addToRadarr(movieTitle, yearVar, tmdbMovieKey, radarrRootFolderPath):
if radarrKey == "" or radarrHost == "" or radarrPort == "":
return
elif pushToRadarr == False:
return
else:
headers = {
'X-Api-Key': radarrKey
}
r = requests.post('http://{0}:{1}/{2}/api/movie/'.format(radarrHost, radarrPort, radarrURI), headers=headers, json={
"title": "{0} ({1})".format(movieTitle, yearVar),
"profileId": 6,
"titleSlug": "{0}-{1}".format(slugger(movieTitle), tmdbMovieKey),
"images": [],
"tmdbId": "{0}".format(tmdbMovieKey),
"rootFolderPath": "{0}".format(radarrRootFolderPath)
})
def checkCashe():
if os.path.exists(cacheDir):
if os.path.isfile(os.path.join(cacheDir, 'theaterTrailersCache.json')):
with open(os.path.join(cacheDir, 'theaterTrailersCache.json')) as fp:
try:
cacheDict = json.load(fp)
creationDate = datetime.strptime(cacheDict['Creation Date'] , '%Y-%m-%d').date()
Current_Date = datetime.strptime(currentDate, '%Y-%m-%d').date()
age = Current_Date - creationDate
age = age.days
logger.info('The cache is {0} days old'.format(age))
if(age==cacheRefresh):
logger.info('The cache will be refreshed')
os.remove(os.path.join(cacheDir, 'theaterTrailersCache.json'))
try:
checkVar = cacheDict[cacheDict.keys()[0]]['status']
checkVar = cacheDict[cacheDict.keys()[0]]['TMDB ID']
checkVar = cacheDict[cacheDict.keys()[0]]['url']
checkVar = cacheDict[cacheDict.keys()[0]]['Trailer Release']
checkVar = cacheDict[cacheDict.keys()[0]]['Movie Title']
checkVar = cacheDict[cacheDict.keys()[0]]['path']
checkVar = cacheDict[cacheDict.keys()[0]]['Release Date']
except KeyError as e:
logger.info('The cache is missing variables. Removing it.')
print e,
os.remove(os.path.join(cacheDir, 'theaterTrailersCache.json'))
except ValueError as e:
logger.info("ValueError {0}".format(e))
logger.info("Cache file empty")
else:
logger.info("making cache dir")
os.makedirs(cacheDir)
def checkDownloadDate(passedTitle):
try:
if currentDate < MovieDict[passedTitle]['Release Date']:
return True
except KeyError as ke2:
logger.error("KeyError {0} 192".format(ke2))
logger.error(MovieDict[passedTitle] + " has no release date")
def keymaker(string):
chars_to_remove = [" ", "?", ".", "!", "/", ":", ";", "'", "-", ","]
sc = set(chars_to_remove)
string = string.lower()
string = ''.join([c for c in string if c not in sc])
return string
def slugger(string):
string = string.replace(" ", "-")
chars_to_remove = ["?", ".", "!", "/", ":", ";", "'", ","]
sc = set(chars_to_remove)
string = string.lower()
string = ''.join([c for c in string if c not in sc])
return string
def updateCache(string, passedTitle, yearVar):
passedSmallTitle = keymaker(passedTitle)
with open(os.path.join(cacheDir, 'theaterTrailersCache.json'), 'r') as fp:
try:
jsonDict = json.load(fp)
try:
if jsonDict[passedSmallTitle]['url'] == string:
if jsonDict[passedSmallTitle]['status'] == 'Downloaded':
if checkFiles(passedTitle, yearVar):
logger.info('{0} from {1} is already downloaded'.format(passedTitle, string))
return
else:
logger.info('{0} from {1} was in the cache but did not exist'.format(passedTitle, string))
if yearVar == MovieDict[passedTitle]['Trailer Year']:
videoDownloader(string,passedTitle,yearVar)
else:
with open(os.path.join(cacheDir, 'theaterTrailersTempCache.json'), 'w') as temp1:
jsonDict[passedSmallTitle]['Trailer Year'] = MovieDict[passedTitle]['Trailer Year']
videoDownloader(string,passedTitle,MovieDict[passedTitle]['Trailer Year'])
json.dump(jsonDict, temp1, indent=4)
elif jsonDict[passedSmallTitle]['status'] == 'Released':
logger.info('{0} from {1} has been released'.format(passedTitle, string))
return
else:
logger.error('error with {0} from {1}'.format(passedTitle, string))
else:
logger.info('New trailer for {0}'.format(passedTitle))
with open(os.path.join(cacheDir, 'theaterTrailersTempCache.json'), 'w') as temp2:
jsonDict[passedSmallTitle]['url'] = string
if checkDownloadDate(passedTitle):
shutil.rmtree(jsonDict[passedSmallTitle]['path'])
videoDownloader(string, jsonDict[passedSmallTitle]['Movie Title'], yearVar)
jsonDict[passedSmallTitle]['status'] = 'Downloaded'
else:
jsonDict[passedSmallTitle]['status'] = 'Released'
json.dump(jsonDict, temp2, indent=4)
except KeyError as e:
logger.info('Creating New Entry')
with open(os.path.join(cacheDir, 'theaterTrailersTempCache.json'), 'w') as temp3:
jsonDict[passedSmallTitle] = MovieDict[passedTitle]
jsonDict[passedSmallTitle]['path'] = os.path.join(trailerLocation, '{0} ({1})'.format(passedTitle, yearVar))
if checkDownloadDate(passedTitle):
videoDownloader(string,passedTitle,yearVar)
jsonDict[passedSmallTitle]['status'] = 'Downloaded'
else:
jsonDict[passedSmallTitle]['status'] = 'Released'
json.dump(jsonDict, temp3, indent=4)
addToRadarr(passedTitle, yearVar, jsonDict[passedSmallTitle]['TMDB ID'], radarrRootFolderPath)
except ValueError as e:
logger.info('Creating Cache')
jsonDict = {}
jsonDict['Creation Date'] = currentDate
jsonDict[passedSmallTitle] = MovieDict[passedTitle]
jsonDict[passedSmallTitle]['path'] = os.path.join(trailerLocation, '{0} ({1})'.format(passedTitle, yearVar))
with open(os.path.join(cacheDir, 'theaterTrailersTempCache.json'), 'w') as temp4:
if checkDownloadDate(passedTitle):
videoDownloader(string, passedTitle, yearVar)
jsonDict[passedSmallTitle]['status'] = 'Downloaded'
else:
jsonDict[passedSmallTitle]['status'] = 'Released'
json.dump(jsonDict, temp4, indent=4)
addToRadarr(passedTitle, yearVar, jsonDict[passedSmallTitle]['TMDB ID'], radarrRootFolderPath)
if os.path.isfile(os.path.join(cacheDir, 'theaterTrailersTempCache.json')):
shutil.move(os.path.join(cacheDir, 'theaterTrailersTempCache.json'), os.path.join(cacheDir, 'theaterTrailersCache.json'))
# Downloads the video, names it and copies the resources to the folder
def videoDownloader(string, passedTitle, yearVar):
# Options for the video downloader
ydl1_opts = {
'outtmpl': os.path.join(TheaterTrailersHome, 'Trailers', '{0} ({1})'.format(passedTitle, yearVar), '{0} ({1}).mp4'.format(passedTitle, yearVar)),
'ignoreerrors': True,
'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best',
}
with youtube_dl.YoutubeDL(ydl1_opts) as ydl:
logger.info("downloading {0} from {1}".format(passedTitle, string))
ydl.download([string])
shutil.copy2(
os.path.join(trailerLocation, '{0} ({1})'.format(passedTitle, yearVar), '{0} ({1}).mp4'.format(passedTitle, yearVar)),
os.path.join(trailerLocation, '{0} ({1})'.format(passedTitle, yearVar), '{0} ({1})-trailer.mp4'.format(passedTitle, yearVar))
)
shutil.copy2(
os.path.join(TheaterTrailersHome, 'res', 'poster.jpg'),
os.path.join(trailerLocation, '{0} ({1})'.format(passedTitle, yearVar))
)
updatePlex()
# Downloads info for the videos from the playlist
def infoDownloader(playlist):
# Options for the info downloader
ydl_opts = {
'skip_download': True,
'ignoreerrors': True,
'playlistreverse': True,
'playliststart': 1,
'playlistend': playlistEndVar,
'quiet': False,
'matchtitle': '.*\\btrailer\\b.*',
'extract_flat': True,
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(playlist)
for x in info['entries']:
MovieVar = x['title'].encode('ascii',errors='ignore')
MovieVar = MovieVar.replace(':', '')
if 'Official' in MovieVar:
regexedTitle = re.search('^.*(?=(Official))', MovieVar)
elif 'Trailer' in MovieVar:
regexedTitle = re.search('.*?(?=Trailer)', MovieVar)
elif redBand == True:
if 'Red Band' in MovieVar:
regexedTitle = re.search('.*?(?=Red)', MovieVar)
else:
# Throws out edge cases
continue
trailerYear = re.search('(?<=\().*(?=\))', MovieVar)
TempDict = { 'url' : info['entries'][info['entries'].index(x)]['url']}
movieTitleUntrimmed = regexedTitle.group(0).strip()
movieTitle = fixTitle(movieTitleUntrimmed)
MovieDict[movieTitle] = TempDict
try:
MovieDict[movieTitle]['Trailer Release'] = trailerYear.group(0)
except AttributeError:
pass
MovieDict[movieTitle]['Movie Title'] = movieTitle
MovieList.append(movieTitle)
def fixTitle(movieTitle):
if "Red Band" in movieTitle:
movieTitle = ' '.join(movieTitle.split(' ')[:-2])
stopwords = ['Teaser','teaser']
querywords = movieTitle.split()
resultwords = [word for word in querywords if word.lower() not in stopwords]
result = ' '.join(resultwords)
return result
def updatePlex():
if plexHost == "" or plexPort == "" or plexToken == "":
return
else:
r = requests.get('http://{0}:{1}/library/sections/1/refresh?X-Plex-Token={2}'.format(plexHost, plexPort, plexToken))
if r.status_code != 200:
logger.warning("The plex server at {0}:{1} did not respond correctly to the request".format(plexHost, plexPort))
# Returns results from tmdb
def tmdbInfo(item):
response = search.movie(query=item)
logger.info("querying the movie db for {0}".format(item))
time.sleep(pauseRate)
return search.results
def checkFiles(title, year):
if os.path.isfile(os.path.join(trailerLocation, '{0} ({1})'.format(title, year), '{0} ({1}).mp4'.format(title, year))):
if not os.path.isfile(os.path.join(trailerLocation, '{0} ({1})'.format(title, year), '{0} ({1})-trailer.mp4'.format(title, year))):
shutil.copy2(
os.path.join(trailerLocation, '{0} ({1})'.format(title, year), '{0} ({1}).mp4'.format(title, year)),
os.path.join(trailerLocation, '{0} ({1})'.format(title, year), '{0} ({1})-trailer.mp4'.format(title, year))
)
updatePlex()
if not os.path.isfile(os.path.join(trailerLocation, '{0} ({1})'.format(title, year), 'poster.jpg')):
shutil.copy2(
os.path.join(TheaterTrailersHome, 'res', 'poster.jpg'),
os.path.join(trailerLocation, '{0} ({1})'.format(title, year))
)
updatePlex()
return True
if os.path.isfile(os.path.join(trailerLocation, '{0} ({1})'.format(title, year), '{0} ({1})-trailer.mp4'.format(title, year))):
if not os.path.isfile(os.path.join(trailerLocation, '{0} ({1})'.format(title, year), '{0} ({1}).mp4'.format(title, year))):
shutil.copy2(
os.path.join(trailerLocation, '{0} ({1})'.format(title, year), '{0} ({1})-trailer.mp4'.format(title, year)),
os.path.join(trailerLocation, '{0} ({1})'.format(title, year), '{0} ({1}).mp4'.format(title, year))
)
updatePlex()
if not os.path.isfile(os.path.join(trailerLocation, '{0} ({1})'.format(title, year), 'poster.jpg')):
shutil.copy2(
os.path.join(TheaterTrailersHome, 'res', 'poster.jpg'),
os.path.join(trailerLocation, '{0} ({1})'.format(title, year))
)
updatePlex()
return True
else:
return False
# Gets a list of the movies in the directory and removes old movies
def cleanup():
if not os.path.isdir(os.path.join(TheaterTrailersHome, 'Trailers')):
return
else:
if os.path.isfile(os.path.join(TheaterTrailersHome, 'Trailers', '.DS_Store')):
os.remove(os.path.join(TheaterTrailersHome, 'Trailers', '.DS_Store'))
dirsList = os.listdir(os.path.join(TheaterTrailersHome, 'Trailers'))
for item in dirsList:
dirsTitle = re.search('^.*(?=(\())', item)
dirsTitle = dirsTitle.group(0).strip()
dirsYear = re.search('(?<=\().*(?=\))', item)
dirsYear = dirsYear.group(0).strip()
filePath = os.path.join(cacheDir, 'theaterTrailersCache.json')
if (os.path.isfile(filePath)):
with open(filePath, 'r') as fp:
try:
data = json.load(fp)
releaseDate = data[keymaker(dirsTitle)]['Release Date']
if releaseDate <= currentDate:
logger.info("Removing {0}. Release date has passed".format(dirsTitle))
shutil.rmtree(os.path.join(TheaterTrailersHome, 'Trailers', '{0} ({1})'.format(dirsTitle, dirsYear)))
updatePlex()
except KeyError as ex:
logger.info(ex)
logger.info("Removing {0}".format(dirsTitle))
shutil.rmtree(os.path.join(TheaterTrailersHome, 'Trailers', '{0} ({1})'.format(dirsTitle, dirsYear)))
updatePlex()
except ValueError as Ve:
logger.warning("Vaule Error {0} 431".format(Ve))
noCacheCleanup(dirsTitle, dirsYear)
def noCacheCleanup(dirsTitle, dirsYear):
s = tmdbInfo(dirsTitle)
for s in search.results:
releaseDate = s['release_date']
releaseDateList = releaseDate.split('-')
if dirsYear == releaseDateList[0]:
if releaseDate <= currentDate:
logger.info("Removing {0}".format(dirsTitle))
shutil.rmtree(os.path.join(TheaterTrailersHome, 'Trailers', '{0} ({1})'.format(dirsTitle, dirsYear)))
updatePlex()
break
if __name__ == "__main__":
main()