forked from ChocolateApp/Chocolate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
5097 lines (4472 loc) · 204 KB
/
app.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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import base64
import configparser
import datetime
import io
import json
import os
import platform
import re
import subprocess
import warnings
import zipfile
import zlib
from sqlite3 import IntegrityError
from time import localtime, mktime, time
from uuid import uuid4
import git
import GPUtil
import pycountry
import PyPDF2
import rarfile
import requests
import sqlalchemy
from ask_lib import AskResult, ask
from deep_translator import GoogleTranslator
from flask import (abort, g, jsonify, make_response, redirect, request,
send_file, url_for)
from flask_login import UserMixin
from guessit import guessit
from Levenshtein import distance as lev
from PIL import Image
from pyarr import LidarrAPI, RadarrAPI, ReadarrAPI, SonarrAPI
from pypresence import Presence
from tmdbv3api import TV, Episode, Find, Movie, Person, TMDb
from tmdbv3api.as_obj import AsObj
from tmdbv3api.exceptions import TMDbException
from unidecode import unidecode
from videoprops import get_video_properties
from werkzeug.security import check_password_hash, generate_password_hash
from chocolate import create_app, db, loginManager
start_time = mktime(localtime())
with warnings.catch_warnings():
warnings.simplefilter("ignore", category = sqlalchemy.exc.SAWarning)
app = create_app()
dirPath = os.getcwd()
dirPath = os.path.dirname(__file__).replace("\\", "/")
langs_dict = GoogleTranslator().get_supported_languages(as_dict=True)
allAuthTokens = {}
def get_uuid():
return uuid4().hex
class Users(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(255), unique=True)
password = db.Column(db.String(255))
profilePicture = db.Column(db.String(255))
accountType = db.Column(db.String(255))
def __init__(self, name, password, profilePicture, accountType):
self.name = name
if password != None:
self.password = generate_password_hash(password)
else:
self.password = None
self.profilePicture = profilePicture
self.accountType = accountType
def __repr__(self) -> str:
return f'<Name {self.name}>'
def verify_password(self, pwd):
if self.password == None:
return True
return check_password_hash(self.password, pwd)
class Movies(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(255), primary_key=True)
realTitle = db.Column(db.String(255), primary_key=True)
cover = db.Column(db.String(255))
banner = db.Column(db.String(255))
slug = db.Column(db.String(255))
description = db.Column(db.String(2550))
note = db.Column(db.String(255))
date = db.Column(db.String(255))
genre = db.Column(db.String(255))
duration = db.Column(db.String(255))
cast = db.Column(db.String(255))
bandeAnnonceUrl = db.Column(db.String(255))
adult = db.Column(db.String(255))
libraryName=db.Column(db.String(255))
alternativesNames = db.Column(db.Text)
vues = db.Column(db.Text, default=str({}))
def __init__(self, id, title, realTitle, cover, banner, slug, description, note, date, genre, duration, cast, bandeAnnonceUrl, adult, libraryName, alternativesNames, vues):
self.id = id
self.title = title
self.realTitle = realTitle
self.cover = cover
self.banner = banner
self.slug = slug
self.description = description
self.note = note
self.date = date
self.genre = genre
self.duration = duration
self.cast = cast
self.bandeAnnonceUrl = bandeAnnonceUrl
self.adult = adult
self.libraryName = libraryName
self.alternativesNames = alternativesNames
self.vues = vues
def __repr__(self) -> str:
return f"<Movies {self.title}>"
class Series(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255), primary_key=True)
originalName = db.Column(db.String(255), primary_key=True)
genre = db.Column(db.String(255))
duration = db.Column(db.String(255))
description = db.Column(db.String(2550))
cast = db.Column(db.String(255))
bandeAnnonceUrl = db.Column(db.String(255))
serieCoverPath = db.Column(db.String(255))
banniere = db.Column(db.String(255))
note = db.Column(db.String(255))
date = db.Column(db.String(255))
serieModifiedTime = db.Column(db.Float)
libraryName=db.Column(db.String(255))
adult = db.Column(db.String(255))
def __init__(self, id, name, originalName, genre, duration, description, cast, bandeAnnonceUrl, serieCoverPath, banniere, note, date, serieModifiedTime, adult, libraryName):
self.id = id
self.name = name
self.originalName = originalName
self.genre = genre
self.duration = duration
self.description = description
self.cast = cast
self.bandeAnnonceUrl = bandeAnnonceUrl
self.serieCoverPath = serieCoverPath
self.banniere = banniere
self.note = note
self.date = date
self.serieModifiedTime = serieModifiedTime
self.libraryName = libraryName
self.adult = adult
def __repr__(self) -> str:
return f"<Series {self.name}>"
class Seasons(db.Model):
serie = db.Column(db.Integer, nullable=False)
seasonId = db.Column(db.Integer, primary_key=True)
seasonNumber = db.Column(db.Integer, primary_key=True)
release = db.Column(db.String(255))
episodesNumber = db.Column(db.String(255))
seasonName = db.Column(db.String(255))
seasonDescription = db.Column(db.Text)
seasonCoverPath = db.Column(db.String(255))
modifiedDate = db.Column(db.Float)
numberOfEpisodeInFolder = db.Column(db.Integer)
def __init__(self, serie, release, episodesNumber, seasonNumber, seasonId, seasonName, seasonDescription, seasonCoverPath, modifiedDate, numberOfEpisodeInFolder):
self.serie = serie
self.release = release
self.episodesNumber = episodesNumber
self.seasonNumber = seasonNumber
self.seasonId = seasonId
self.seasonName = seasonName
self.seasonDescription = seasonDescription
self.seasonCoverPath = seasonCoverPath
self.modifiedDate = modifiedDate
self.numberOfEpisodeInFolder = numberOfEpisodeInFolder
def __repr__(self) -> str:
return f"<Seasons {self.serie} {self.seasonNumber}>"
class Episodes(db.Model):
seasonId = db.Column(db.Integer, nullable=False)
episodeId = db.Column(db.Integer, primary_key=True)
episodeName = db.Column(db.String(255), primary_key=True)
episodeNumber = db.Column(db.Integer, primary_key=True)
episodeDescription = db.Column(db.Text)
episodeCoverPath = db.Column(db.String(255))
releaseDate = db.Column(db.String(255))
slug = db.Column(db.String(255))
introStart = db.Column(db.Float)
introEnd = db.Column(db.Float)
def __init__(self, episodeId, episodeName, seasonId, episodeNumber, episodeDescription, episodeCoverPath, releaseDate, slug, introStart, introEnd):
self.episodeId = episodeId
self.seasonId = seasonId
self.episodeName = episodeName
self.episodeNumber = episodeNumber
self.episodeDescription = episodeDescription
self.episodeCoverPath = episodeCoverPath
self.releaseDate = releaseDate
self.slug = slug
self.introStart = introStart
self.introEnd = introEnd
def __repr__(self) -> str:
return f"<Episodes {self.seasonId} {self.episodeNumber}>"
class Games(db.Model):
console = db.Column(db.String(255), nullable=False)
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(255), primary_key=True)
realTitle = db.Column(db.String(255), primary_key=True)
cover = db.Column(db.String(255))
description = db.Column(db.String(2550))
note = db.Column(db.String(255))
date = db.Column(db.String(255))
genre = db.Column(db.String(255))
slug = db.Column(db.String(255))
libraryName=db.Column(db.String(255))
def __init__(self, console, id, title, realTitle, cover, description, note, date, genre, slug, libraryName):
self.console = console
self.id = id
self.title = title
self.realTitle = realTitle
self.cover = cover
self.description = description
self.note = note
self.date = date
self.genre = genre
self.slug = slug
self.libraryName = libraryName
def __repr__(self) -> str:
return f"<Games {self.title}>"
class OthersVideos(db.Model):
videoHash = db.Column(db.String(255), primary_key=True)
title = db.Column(db.String(255), primary_key=True)
slug = db.Column(db.String(255))
banner = db.Column(db.String(255))
duration = db.Column(db.String(255))
libraryName = db.Column(db.String(255))
vues = db.Column(db.Text, default=str({}))
def __init__(self, videoHash, title, slug, banner, duration, libraryName, vues):
self.videoHash = videoHash
self.title = title
self.slug = slug
self.banner = banner
self.duration = duration
self.libraryName = libraryName
self.vues = vues
def __repr__(self) -> str:
return f"<OthersVideos {self.title}>"
class Books(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
title = db.Column(db.String(255))
slug = db.Column(db.String(255))
bookType = db.Column(db.String(255))
cover = db.Column(db.String(255))
libraryName = db.Column(db.String(255))
def __repr__(self) -> str:
return f"<Books {self.title}>"
class Language(db.Model):
language = db.Column(db.String(255), primary_key=True)
def __init__(self, language):
self.language = language
def __repr__(self) -> str:
return f"<Language {self.language}>"
class Actors(db.Model):
name = db.Column(db.String(255), primary_key=True)
actorId = db.Column(db.Integer, primary_key=True)
actorImage = db.Column(db.Text)
actorDescription = db.Column(db.String(2550))
actorBirthDate = db.Column(db.String(255))
actorBirthPlace = db.Column(db.String(255))
actorPrograms = db.Column(db.Text)
def __init__(self, name, actorId, actorImage, actorDescription, actorBirthDate, actorBirthPlace, actorPrograms):
self.name = name
self.actorId = actorId
self.actorImage = actorImage
self.actorDescription = actorDescription
self.actorBirthDate = actorBirthDate
self.actorBirthPlace = actorBirthPlace
self.actorPrograms = actorPrograms
def __repr__(self) -> str:
return f"<Actors {self.name}>"
class Libraries(db.Model):
libName = db.Column(db.String(255), primary_key=True)
libImage = db.Column(db.String(255))
libType = db.Column(db.String(255))
libFolder = db.Column(db.Text)
availableFor = db.Column(db.Text)
def __init__(self, libName, libImage, libType, libFolder, availableFor):
self.libName = libName
self.libImage = libImage
self.libType = libType
self.libFolder = libFolder
self.availableFor = availableFor
def __repr__(self) -> str:
return f"<Libraries {self.libName}>"
with app.app_context():
try:
db.create_all()
db.init_app(app)
except:
pass
@loginManager.user_loader
def load_user(id):
return Users.query.get(int(id))
dir = os.path.dirname(__file__)
config = configparser.ConfigParser()
config.read(os.path.join(dir, 'config.ini'))
if config["ChocolateSettings"]["language"] == "Empty":
config["ChocolateSettings"]["language"] = "EN"
chocolateVersion = config["ChocolateSettings"]["version"]
try:
repo = git.Repo(search_parent_directories=True)
lastCommitHash = repo.head.object.hexsha[:7]
except:
lastCommitHash = "xxxxxxx"
with app.app_context():
libraries = Libraries.query.filter_by(libType="games").all() is not None
if libraries:
clientID = config.get("APIKeys", "IGDBID")
clientSecret = config.get("APIKeys", "IGDBSECRET")
if clientID == "Empty" or clientSecret == "Empty":
print("Follow this tutorial to get your IGDB API Keys: https://api-docs.igdb.com/#account-creation")
tmdb = TMDb()
apiKeyTMDB = config["APIKeys"]["TMDB"]
if apiKeyTMDB == "Empty":
print("Follow this tutorial to get your TMDB API Key : https://developers.themoviedb.org/3/getting-started/introduction")
tmdb.api_key = config["APIKeys"]["TMDB"]
tmdb.language = config["ChocolateSettings"]["language"]
with open(os.path.join(dir, 'config.ini'), 'w') as configfile:
config.write(configfile)
def searchGame(game, console):
url = f"https://www.igdb.com/search_autocomplete_all?q={game.replace(' ', '%20')}"
return IGDBRequest(url,console)
def IGDBRequest(url, console):
customHeaders = {
'User-Agent': 'Mozilla/5.0 (X11; UwUntu; Linux x86_64; rv:100.0) Gecko/20100101 Firefox/100.0',
'Accept': '*/*',
'X-Requested-With': 'XMLHttpRequest',
'Origin': url,
'DNT': '1',
'Sec-Fetch-Dest': 'empty',
'Sec-Fetch-Mode': 'cors',
'Sec-Fetch-Site': 'same-origin',
'Referer': url,
'Connection': 'keep-alive',
'Pragma': 'no-cache',
'Cache-Control': 'no-cache',
}
response = requests.request("GET", url, headers=customHeaders)
if response.status_code == 403:
return None
elif response.json() != {}:
grantType = "client_credentials"
getAccessToken = f"https://id.twitch.tv/oauth2/token?client_id={clientID}&client_secret={clientSecret}&grant_type={grantType}"
token = requests.request("POST", getAccessToken)
token = token.json()
token = token["access_token"]
headers = {
"Accept": "application/json", "Authorization": f"Bearer {token}", "Client-ID": clientID
}
games = response.json()["game_suggest"]
for i in games:
game=i
gameId = game["id"]
url = f"https://api.igdb.com/v4/games"
body = f"fields name, cover.*, summary, total_rating, first_release_date, genres.*, platforms.*; where id = {gameId};"
response = requests.request("POST", url, headers=headers, data=body)
if len(response.json())==0:
break
game = response.json()[0]
if "platforms" in game:
gamePlatforms = game["platforms"]
try:
platforms = [i["abbreviation"] for i in gamePlatforms]
realConsoleName = {
"GB": "Game Boy", "GBA": "Game Boy Advance", "GBC": "Game Boy Color", "N64": "Nintendo 64", "NES": "Nintendo Entertainment System", "NDS": "Nintendo DS", "SNES": "Super Nintendo Entertainment System", "Sega Master System": "Sega Master System", "Sega Mega Drive": "Sega Mega Drive", "PS1": "PS1"
}
if realConsoleName[console] not in platforms and console not in platforms:
continue
if "total_rating" not in game:
game["total_rating"] = "Unknown"
if "genres" not in game:
game["genres"] = [{"name": "Unknown"}]
if "summary" not in game:
game["summary"] = "Unknown"
if "first_release_date" not in game:
game["first_release_date"] = "Unknown"
if "cover" not in game:
game["cover"] = {"url": "//images.igdb.com/igdb/image/upload/t_cover_big/nocover.png"}
game["summary"] = translate(game["summary"])
game["genres"][0]["name"] = translate(game["genres"][0]["name"])
genres = []
for genre in game["genres"]:
genres.append(genre["name"])
genres = ", ".join(genres)
gameData = {
"title": game["name"], "cover": game["cover"]["url"].replace("//", "https://"), "description": game["summary"], "note": game["total_rating"], "date": game["first_release_date"], "genre": genres, "id": game["id"]
}
return gameData
except:
continue
return None
def translate(string):
language = config["ChocolateSettings"]["language"]
if language == "EN":
return string
translated = GoogleTranslator(source='english', target=language.lower()).translate(string)
return translated
tmdb.language = config["ChocolateSettings"]["language"].lower()
tmdb.debug = True
movie = Movie()
show = TV()
errorMessage = True
client_id = "771837466020937728"
enabledRPC = config["ChocolateSettings"]["discordrpc"]
if enabledRPC == "true":
try:
RPC = Presence(client_id)
RPC.connect()
except Exception as e:
enabledRPC == "false"
config.set("ChocolateSettings", "discordrpc", "false")
with open(os.path.join(dir, 'config.ini'), "w") as conf:
config.write(conf)
searchedFilms = []
allMoviesNotSorted = []
searchedSeries = []
simpleDataSeries = {}
allSeriesNotSorted = []
allSeriesDict = {}
allSeriesDictTemp = {}
configLanguage = config["ChocolateSettings"]["language"]
with app.app_context():
languageDB = db.session.query(Language).first()
exists = db.session.query(Language).first() is not None
if not exists:
newLanguage = Language(language="EN")
db.session.add(newLanguage)
db.session.commit()
languageDB = db.session.query(Language).first()
if languageDB.language != configLanguage:
db.session.query(Movies).delete()
db.session.query(Series).delete()
db.session.query(Seasons).delete()
db.session.query(Episodes).delete()
languageDB.language = configLanguage
db.session.commit()
CHUNK_LENGTH = 5
CHUNK_LENGTH = int(CHUNK_LENGTH)
genreList = {
12: "Aventure",
14: "Fantastique",
16: "Animation",
18: "Drama",
27: "Horreur",
28: "Action",
35: "Comédie",
36: "Histoire",
37: "Western",
53: "Thriller",
80: "Crime",
99: "Documentaire",
878: "Science-fiction",
9648: "Mystère",
10402: "Musique",
10749: "Romance",
10751: "Famille",
10752: "War",
10759: "Action & Adventure",
10762: "Kids",
10763: "News",
10764: "Reality",
10765: "Sci-Fi & Fantasy",
10766: "Soap",
10767: "Talk",
10768: "War & Politics",
10769: "Western",
10770: "TV Movie",
}
genresUsed = []
moviesGenre = []
movieExtension = ""
websitesTrailers = {
"YouTube": "https://www.youtube.com/embed/",
"Dailymotion": "https://www.dailymotion.com/video/",
"Vimeo": "https://vimeo.com/",
}
def getMovies(libraryName):
movie = Movie()
allMoviesNotSorted = []
path = Libraries.query.filter_by(libName=libraryName).first().libFolder
filmFileList = []
try:
movies = os.listdir(path)
except:
return
for movieFile in movies:
if not movieFile.endswith((".rar", ".zip", ".part")):
filmFileList.append(movieFile)
if not is_connected():
return
movies = Movies.query.filter_by(libraryName=libraryName).all()
moviesPath = os.listdir(path)
for movie in movies:
slug = movie.slug
#print(f"Movie {movie.realTitle} slug: {slug}\n")
possibleDirSlug = slug.split("/")[0:-1]
possibleDirSlug = "/".join(possibleDirSlug)
if slug not in moviesPath and possibleDirSlug == "":
db.session.delete(movie)
db.session.commit()
elif slug not in moviesPath and possibleDirSlug != "":
path = f"{path}\{possibleDirSlug}\{slug}"
dirPath = f"{path}\{possibleDirSlug}"
exist = os.path.exists(path)
existDir = os.path.exists(dirPath)
if not exist or not existDir:
db.session.delete(movie)
db.session.commit()
filmFileList.sort()
dirPath = os.getcwd()
dirPath = os.path.dirname(__file__).replace("\\", "/")
for searchedFilm in filmFileList:
if not isinstance(searchedFilm, str):
continue
if True:
movieTitle = searchedFilm
if os.path.isdir(os.path.join(path, movieTitle)):
try:
movieTitle = os.listdir(os.path.join(path, movieTitle))[0]
except Exception as e:
print(f"Error with movie {movieTitle} in subfolder: {e}")
originalMovieTitle = movieTitle
size = len(movieTitle)
movieTitle, extension = os.path.splitext(movieTitle)
index = filmFileList.index(searchedFilm) + 1
percentage = index * 100 / len(filmFileList)
loadingFirstPart = ("•" * int(percentage * 0.2))[:-1]
loadingFirstPart = f"{loadingFirstPart}➤"
loadingSecondPart = "•" * (20 - int(percentage * 0.2))
loading = f"{str(int(percentage)).rjust(3)}% | [\33[32m{loadingFirstPart} \33[31m{loadingSecondPart}\33[0m] | {movieTitle} | {index}/{len(filmFileList)} "
print("\033[?25l", end="")
print(loading, end="\r", flush=True)
slug = searchedFilm
exists = Movies.query.filter_by(slug=slug).first() is not None
if not exists:
try:
search = movie.search(movieTitle, adult=True)
except Exception as e:
search = movie.search(movieTitle)
if not search:
guessedData = guessit(movieTitle)
if "year" in guessedData:
try:
search = movie.search(guessedData["title"], year=guessedData["year"], adult=True)
except:
search = movie.search(guessedData["title"], year=guessedData["year"])
else:
try:
search = movie.search(guessedData["title"], adult=True)
except:
search = movie.search(guessedData["title"])
if not search:
allMoviesNotSorted.append(originalMovieTitle)
continue
bestMatch = search[0]
if config["ChocolateSettings"]["askwhichmovie"] == "false" or len(search)==1:
for i in range(len(search)):
if (lev(movieTitle, search[i].title) < lev(movieTitle, bestMatch.title)
and bestMatch.title not in filmFileList):
bestMatch = search[i]
elif (lev(movieTitle, search[i].title) == lev(movieTitle, bestMatch.title)
and bestMatch.title not in filmFileList):
bestMatch = bestMatch
if (lev(movieTitle, bestMatch.title) == 0
and bestMatch.title not in filmFileList):
break
res = bestMatch
try:
name = res.title
except AttributeError as e:
name = res.original_title
movieId = res.id
details = movie.details(movieId)
start = ""
if os.path.isdir(os.path.join(path, searchedFilm)):
start = f"{searchedFilm}/"
movieCoverPath = f"https://image.tmdb.org/t/p/original{res.poster_path}"
banniere = f"https://image.tmdb.org/t/p/original{res.backdrop_path}"
realTitle, extension = os.path.splitext(originalMovieTitle)
with open(f"{dirPath}/static/img/mediaImages/{movieId}_Cover.png", "wb") as f:
f.write(requests.get(movieCoverPath).content)
try:
img = Image.open(f"{dirPath}/static/img/mediaImages/{movieId}_Cover.png")
img.save(f"{dirPath}/static/img/mediaImages/{movieId}_Cover.webp", "webp")
os.remove(f"{dirPath}/static/img/mediaImages/{movieId}_Cover.png")
movieCoverPath = f"/static/img/mediaImages/{movieId}_Cover.webp"
except:
try:
os.rename(f"{dirPath}/static/img/mediaImages/{movieId}_Cover.png", f"{dirPath}/static/img/mediaImages/{movieId}_Cover.webp")
movieCoverPath = "/static/img/broken.webp"
except:
os.remove(f"{dirPath}/static/img/mediaImages/{movieId}_Cover.webp")
os.rename(f"{dirPath}/static/img/mediaImages/{movieId}_Cover.png", f"{dirPath}/static/img/mediaImages/{movieId}_Cover.webp")
movieCoverPath = f"/static/img/mediaImages/{movieId}_Cover.webp"
with open(f"{dirPath}/static/img/mediaImages/{movieId}_Banner.png", "wb") as f:
f.write(requests.get(banniere).content)
if res.backdrop_path == None:
banniere = f"https://image.tmdb.org/t/p/original{details.backdrop_path}"
if banniere != "https://image.tmdb.org/t/p/originalNone":
with open(f"{dirPath}/static/img/mediaImages/{movieId}_Banner.png", "wb") as f:
f.write(requests.get(banniere).content)
else:
banniere = "/static/img/broken.webp"
try:
img = Image.open(f"{dirPath}/static/img/mediaImages/{movieId}_Banner.png")
img.save(f"{dirPath}/static/img/mediaImages/{movieId}_Banner.webp", "webp")
os.remove(f"{dirPath}/static/img/mediaImages/{movieId}_Banner.png")
banniere = f"/static/img/mediaImages/{movieId}_Banner.webp"
except:
banniere = "/static/img/brokenBanner.webp"
description = res.overview
note = res.vote_average
try:
date = res.release_date
except AttributeError as e:
date = "Unknown"
casts = details.casts.cast[:5]
theCast = []
for cast in casts:
characterName = cast.character
actorId = cast.id
actorImage = f"https://www.themoviedb.org/t/p/w600_and_h900_bestv2{cast.profile_path}"
if not os.path.exists(f"{dirPath}/static/img/mediaImages/Actor_{actorId}.webp"):
with open(f"{dirPath}/static/img/mediaImages/Actor_{actorId}.png", "wb") as f:
f.write(requests.get(actorImage).content)
try:
img = Image.open(f"{dirPath}/static/img/mediaImages/Actor_{actorId}.png")
img = img.save(f"{dirPath}/static/img/mediaImages/Actor_{actorId}.webp", "webp")
os.remove(f"{dirPath}/static/img/mediaImages/Actor_{actorId}.png")
except Exception as e:
os.rename(f"{dirPath}/static/img/mediaImages/Actor_{actorId}.png", f"{dirPath}/static/img/mediaImages/Actor_{actorId}.webp")
actorImage = f"/static/img/mediaImages/Actor_{actorId}.webp"
actor = [cast.name, characterName, actorImage, cast.id]
if actor not in theCast:
theCast.append(actor)
else:
break
person = Person()
p = person.details(cast.id)
exists = Actors.query.filter_by(actorId=cast.id).first() is not None
if not exists:
actor = Actors(name=cast.name, actorImage=actorImage, actorDescription=p.biography, actorBirthDate=p.birthday, actorBirthPlace=p.place_of_birth, actorPrograms=f"{movieId}", actorId=cast.id)
db.session.add(actor)
db.session.commit()
else:
actor = Actors.query.filter_by(actorId=cast.id).first()
actor.actorPrograms = f"{actor.actorPrograms} {movieId}"
db.session.commit()
theCast = theCast
try:
date = datetime.datetime.strptime(date, "%Y-%m-%d").strftime("%d/%m/%Y")
except ValueError as e:
date = "Unknown"
except UnboundLocalError:
date = "Unknown"
genre = res.genre_ids
video_path = f"{path}\{start}{originalMovieTitle}"
try:
length = length_video(video_path)
length = str(datetime.timedelta(seconds=length))
length = length.split(":")
except Exception as e:
length = []
if len(length) == 3:
hours = length[0]
minutes = length[1]
seconds = str(round(float(length[2])))
if int(seconds) < 10:
seconds = f"0{seconds}"
length = f"{hours}:{minutes}:{seconds}"
elif len(length) == 2:
minutes = length[0]
seconds = str(round(float(length[1])))
if int(seconds) < 10:
seconds = f"0{seconds}"
length = f"{minutes}:{seconds}"
elif len(length) == 1:
seconds = str(round(float(length[0])))
if int(seconds) < 10:
seconds = f"0{seconds}"
length = f"00:{seconds}"
else:
length = "0"
duration = length
for genreId in genre:
if genreList[genreId] not in genresUsed:
genresUsed.append(genreList[genreId])
if genreList[genreId] not in moviesGenre:
moviesGenre.append(genreList[genreId])
movieGenre = []
for genreId in genre:
movieGenre.append(genreList[genreId])
bandeAnnonce = details.videos.results
bandeAnnonceUrl = ""
if len(bandeAnnonce) > 0:
for video in bandeAnnonce:
bandeAnnonceType = video.type
bandeAnnonceHost = video.site
bandeAnnonceKey = video.key
if bandeAnnonceType == "Trailer":
try:
bandeAnnonceUrl = (
websitesTrailers[bandeAnnonceHost] + bandeAnnonceKey
)
break
except KeyError as e:
bandeAnnonceUrl = "Unknown"
print(e)
alternativesNames = []
actualTitle = movieTitle
characters = [" ", "-", "_", ":", ".", ",", "!", "'", "`", "\""]
empty = ""
for character in characters:
for character2 in characters:
if character != character2:
stringTest = actualTitle.replace(character, character2)
alternativesNames.append(stringTest)
stringTest = actualTitle.replace(character2, character)
alternativesNames.append(stringTest)
stringTest = actualTitle.replace(character, empty)
alternativesNames.append(stringTest)
stringTest = actualTitle.replace(character2, empty)
alternativesNames.append(stringTest)
officialAlternativeNames = movie.alternative_titles(movie_id=movieId).titles
if officialAlternativeNames is not None:
for officialAlternativeName in officialAlternativeNames:
alternativesNames.append(officialAlternativeName.title)
alternativesNames = list(dict.fromkeys(alternativesNames))
alternativesNames = ",".join(alternativesNames)
slug = f"{start}{originalMovieTitle}"
filmData = Movies(movieId, movieTitle, name, movieCoverPath, banniere, slug, description, note, date, json.dumps(movieGenre), str(duration), json.dumps(theCast), bandeAnnonceUrl, str(res["adult"]), libraryName=libraryName, alternativesNames=alternativesNames, vues=str({}))
db.session.add(filmData)
db.session.commit()
elif searchedFilm.endswith("/") == False:
allMoviesNotSorted.append(searchedFilm)
movies = Movies.query.filter_by(libraryName=libraryName).all()
moviesPath = os.listdir(path)
for movie in movies:
slug = movie.slug
#print(f"Movie {movie.realTitle} slug: {slug}\n")
possibleDirSlug = slug.split("/")[0:-1]
possibleDirSlug = "/".join(possibleDirSlug)
if slug not in moviesPath and possibleDirSlug == "":
db.session.delete(movie)
db.session.commit()
elif slug not in moviesPath and possibleDirSlug != "":
path = f"{path}\{possibleDirSlug}\{slug}"
dirPath = f"{path}\{possibleDirSlug}"
exist = os.path.exists(path)
existDir = os.path.exists(dirPath)
if not exist or not existDir:
db.session.delete(movie)
db.session.commit()
class EpisodeGroup():
def __init__(self, **entries):
if "success" in entries and entries["success"] is False:
raise TMDbException(entries["status_message"])
for key, value in entries.items():
if isinstance(value, list):
value = [EpisodeGroup(**item) if isinstance(item, dict) else item for item in value]
elif isinstance(value, dict):
value = EpisodeGroup(**value)
setattr(self, key, value)
def getEpisodeGroupe(apikey, serieId, language="EN"):
details = show.details(serieId)
seasonsInfo = details.seasons
serieTitle = details.name
url = f"https://api.themoviedb.org/3/tv/{serieId}/episode_groups?api_key={apikey}&language={language}"
r = requests.get(url)
data = r.json()
if data["results"]:
#print(f"Found {len(data['results'])} episode groups for {serieTitle}")
for episodeGroup in data["results"]:
index = data["results"].index(episodeGroup) + 1
name = episodeGroup["name"]
episodeCount = episodeGroup["episode_count"]
description = episodeGroup["description"]
#print(f"{index}: Found {episodeCount} episodes for {name} ({description})")
#print("0: Use the default episode group")
selectedEpisodeGroup = int(input("Which episode group do you want to use ? "))
if selectedEpisodeGroup > 0:
theEpisodeGroup = data["results"]
episode_group_data_url = f"https://api.themoviedb.org/3/tv/episode_group/{theEpisodeGroup['id']}?api_key={apikey}&language={language}"
r = requests.get(episode_group_data_url)
data = r.json()
seasons = data["groups"]
for season in seasons:
seasonId = season["id"]
seasonName = season["name"]
episodesNumber = len(season["episodes"])
releaseDate = season["episodes"][0]["air_date"]
seasonNumber = season["order"]
seasonDescription = season.overview
seasonPoster = "/static/img/broken.png"
#get the season from seasonId
seasonsInfo = [season for season in seasonsInfo if season.id == seasonId]
if seasonsInfo:
seasonsInfo = EpisodeGroup(id=seasonId, name=seasonName, episode_count=episodesNumber, air_date=releaseDate, season_number=seasonNumber, overview=seasonDescription, poster_path=seasonPoster)
else:
seasonsInfo = seasonsInfo
def getSeries(libraryName):
allSeriesPath = Libraries.query.filter_by(libName=libraryName).first().libFolder
try:
allSeries = [name for name in os.listdir(allSeriesPath) if os.path.isdir(os.path.join(allSeriesPath, name)) and name.endswith((".rar", ".zip", ".part")) == False]
except:
return
allSeasonsAppelations = ["S"]
allEpisodesAppelations = ["E"]
allSeriesDictTemp = {}
for series in allSeries:
uglySeasonAppelations = ["Saison", "Season", series.replace(" ", ".")]
seasons = os.listdir(os.path.join(allSeriesPath, series))
serieSeasons = {}
for season in seasons:
path = os.path.join(allSeriesPath, series)
if (not (season.startswith(tuple(allSeasonsAppelations)) and season.endswith(("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"))) or season.startswith(tuple(uglySeasonAppelations))):
allSeasons = os.listdir(f"{path}")
for allSeason in allSeasons:
if ((allSeason.startswith(tuple(allSeasonsAppelations)) == False and allSeason.endswith(("0", "1", "2", "3", "4", "5", "6", "7", "8", "9")) == False) or season.startswith(tuple(uglySeasonAppelations))):
if os.path.isdir(f"{path}/{allSeason}") and not (allSeason.startswith(tuple(allSeasonsAppelations)) and allSeason.endswith(("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"))):
#print(f"For {uglySeasonAppelations[2]} : {allSeason}")
reponse = ask(f"I found that folder, can I rename it from {allSeason} to S{allSeasons.index(allSeason)+1}", AskResult.YES)
if reponse:
try:
os.rename(f"{path}/{allSeason}", f"{path}/S{allSeasons.index(allSeason)+1}")
except Exception as e:
print(f"Something went wrong : {e}")
episodesPath = f"{path}\{season}"
try:
seasonNumber = season.split(" ")[1]
except Exception as e:
seasonNumber = season.replace("S", "")
if os.path.isdir(episodesPath):
episodes = os.listdir(episodesPath)
seasonEpisodes = {}
oldIndex = 0
for episode in episodes:
episodeName, episodeExtension = os.path.splitext(episode)
if os.path.isfile(f"{episodesPath}/{episode}"):
if episodeName.startswith(
tuple(allEpisodesAppelations)
) and episodeName.endswith(
("0", "1", "2", "3", "4", "5", "6", "7", "8", "9")
):
oldIndex = episodes.index(episode)
seasonEpisodes[oldIndex + 1] = f"{path}/{season}/{episode}"
serieSeasons[seasonNumber] = seasonEpisodes
serieData = {}
serieData["seasons"] = serieSeasons
allSeriesDictTemp[series] = serieData
allSeriesName = []
alreadyAddedSeries = []
allSeries = allSeriesDictTemp
for series in allSeries:
allSeriesName.append(series)
if not is_connected():
return
show = TV()
for serie in allSeriesName:
if not isinstance(serie, str):
#print(f"Error : {serie} is not a string")
continue
index = allSeriesName.index(serie) + 1
percentage = index * 100 / len(allSeriesName)
loadingFirstPart = ("•" * int(percentage * 0.2))[:-1]
loadingFirstPart = f"{loadingFirstPart}➤"
loadingSecondPart = "•" * (20 - int(percentage * 0.2))
loading = f"{str(int(percentage)).rjust(3)}% | [\33[32m{loadingFirstPart} \33[31m{loadingSecondPart}\33[0m] | {serie} | {index}/{len(allSeriesName)} "
print("\033[?25l", end="")
print(loading, end="\r", flush=True)
serieTitle = serie
originalSerieTitle = serieTitle
try:
serieModifiedTime = os.path.getmtime(f"{allSeriesPath}/{originalSerieTitle}")
except FileNotFoundError:
print(f"Cant find {originalSerieTitle}")
continue
try:
search = show.search(serieTitle)
except TMDbException as e:
allSeriesNotSorted.append(serieTitle)
break
if not search:
allSeriesNotSorted.append(serieTitle)
continue
askForGoodSerie = config["ChocolateSettings"]["askWhichSerie"]
bestMatch = search[0]
if askForGoodSerie == "false" or len(search)==1: