-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpymediaident.py
1766 lines (1526 loc) · 51.8 KB
/
pymediaident.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Documentation, License etc.
EsTass 2018
https://github.com/EsTass/pymediaident
@package pymediaident
'''
#IMPORTS
'''
import sys
import os
import unicodedata
import ntpath
import re
import datetime
import array
import subprocess
import json
import datetime
import unicodedata
#IMDBpy IMDB https://imdbpy.sourceforge.io/
from imdb import IMDb
#python_filmaffinity https://github.com/sergiormb/python_filmaffinity
import python_filmaffinity
#omdb https://pypi.python.org/pypi/omdb
import omdb
#tvdb_api https://github.com/dbr/tvdb_api/
import tvdb_api
'''
#IMPORTS with install
import pip
import sys
import os
import unicodedata
import ntpath
import re
import datetime
import array
import subprocess
import json
import datetime
import random
def install( package ):
#pip <10
#pip.main(['install', package])
#pip 10
try:
# install pkg
subprocess.check_call(["python", '-m', 'pip', 'install', package])
except Exception:
print( 'pip cant install: ' + str( package ) )
print( 'Need admin rights on first launch to install dependecies. Failed in: ' + str( package ) )
exit()
# upgrade pkg
#subprocess.check_call(["python", '-m', 'pip', 'install',"--upgrade", package])
#imdb
try:
from imdb import IMDb
except ImportError:
install( 'IMDbPY' )
from imdb import IMDb
#python_filmaffinity
try:
import python_filmaffinity
except ImportError:
install( 'python_filmaffinity' )
import python_filmaffinity
#omdb
try:
import omdb
except ImportError:
install( 'omdb' )
import omdb
#tvdb_api
try:
import tvdb_api
except ImportError:
install( 'tvdb_api' )
import tvdb_api
#SEARCHERS
#TODO googler
#TODO ddgr
#ducker
try:
import ducker
except ImportError:
install( 'ducker' )
#CONFIGS
VERSION='0.6'
#VERBOSE MODE -v
G_DEBUG=False
#remove extension from filename
remove_extension = [ '.avi', '.mp4', '.mpeg', '.mkv', '.mpeg4', '.ogm' ]
G_MEDIAEXCLUDEEXT = [ 'part','part.met','!qb','tmp','temp' ]
#min filesize for media file (50mb)
G_MEDIAMINSIZE = 50 * 1024 * 1024
# web data from. imdb|filmaffinity
G_GETDATAFROM_LIST=[ 'imdb', 'filmaffinity', 'omdb', 'thetvdb', 'test' ]
G_GETDATAFROM='imdb'
G_GETDATAFROM_KEY=''
# forced id for imdb|filmaffinity data
G_GETDATAFROM_ID=''
# inet searcher
#ddgr ducker googler
CMDSEARCHLIST = [ 'googler', 'ddgr', 'ducker' ]
CMDSEARCH = ''
#lang
G_LANG='en'
#country
G_COUNTRY='USA'
G_COUNTRY_DEF='USA'
#Max actors
ACTORS_MAX=20
#Rename
G_RENAME=False
#FORMATS
#%title%
#%year%
#%director%
#%season%
#%chapter%
#%chaptertitle%
#%genre%
#Rename Format MOVIE
G_RENAME_FORMAT_MOVIE='%title% (%year%, %director%)'
#Rename Format SERIE
G_RENAME_FORMAT_SERIE='%title% %season%x%chapter%(%year%, %director%)'
#Move
G_MOVE=False
#harlink
G_HARDLINK=False
#JSon Format
G_JSON=False
#Not print info
G_NOINFO=False
#dryrun
G_DRYRUN=False
#interactive mode
G_INTERACTIVE=False
#interactive mode set result
G_INTERACTIVE_SET=False
#Force search string
G_FSEARCHSTRING=False
#barwords txt file
G_BADWORDSFILE=False
#OPTIONS
MSG_OPTIONS = '''
OPTIONS
-h : help
-v : verbose mode
-f FILETOIDENT : path to file to ident
-fp FOLDER : path to folder to scan media files and ident
-fps 50 : min file size to folder scan to use as media file
-fpee ext1,ext2 : scan folder exclude extensions ('part','part.met','!qb','tmp','temp')
-es 'googler|ddgr|ducker' : external search
-s imdb|filmaffinity|omdb|thetvdb : get data from
-sid XXX : forced id for imdb|filmaffinity|omdb|thetvdb
-apikey XXX : apikey for omdb|thetvdb
-l en|es|mx|ar|cl|co... : languaje
-c USA : country for release date
-r : rename
-rfm "%title% (%year%, %director%)" : rename format movie
-rfs "%title% %season%x%chapter%(%year%, %director%)" : rename format series
-m "/path/%title%": move file to folder with format name
-hl "/path/%title%": hardlink file to folder with format name
--json : return onlyjson data
-dr : dryrun, force not changes
-i : interactive mode, select search result to assign
-if X: force select X position of interactive mode
-fs "Search String" : force search string for file
-bwf badwordsfile.txt : bad words for clean filenames (1 word each line)
Formats for -rfm -rfs -m -hl
%title%
%year%
%director%
%season%
%chapter%
%chaptertitle%
%genre%
'''
MSG_APPINFO='pymediaident v'+VERSION+' 2018 https://github.com/EsTass/pymediaident'
G_BADWORDS=[ \
'torrent', \
'xvid', \
'divx', \
'mp4', \
'acc', \
'mp3', \
'x264', \
'x265', \
'microhd', \
'micro-hd', \
'tsscreener', \
'tvscreener', \
'hdscreener', \
'ts-screener', \
'tv-screener', \
'hd-screener', \
'screener', \
'dvdline', \
'dvd-line', \
'dvdrip', \
'dvd-rip', \
'dvd', \
'dvbrip', \
'dvb-rip', \
'dvbline', \
'dvb-line', \
'dvb', \
'fullbluray', \
'bluray', \
'blray', \
'bd-rip', \
'bdline', \
'bd-line', \
'bdrip', \
'bdremux', \
'vp8', \
'vp9', \
'1080p', \
'720p', \
'2ch', \
'5ch', \
'7ch', \
'8ch', \
'4K ', \
'3d ', \
]
#FUNCTIONS
def getFilesMedia(path):
global G_MEDIAMINSIZE
global G_DEBUG
debug=G_DEBUG
result = []
printE('Get Files in folder:', path)
path=encodeUTF8(path)
path = os.path.abspath(path)
if os.path.exists( path ):
if debug: printE( 'Folder exist: ', path )
for folder, subfolders, files in os.walk(path):
if debug: printE( 'Files in folder: ', path, len(files) )
for file in files:
filePath = os.path.join(folder, file)
if debug: printE( 'Check File: ', filePath )
try:
if G_MEDIAMINSIZE<=os.path.getsize(filePath) \
and os.path.basename(__file__) != file \
and checkFileExtensions(file)==False:
result.append(filePath)
else:
if debug: printE( 'Check File FAIL: ', filePath )
except:
if debug: printE( 'Check File ERROR: ', filePath, result )
pass
printE('Files finded:', len(result))
return result
def checkFileExtensions(file):
global G_MEDIAEXCLUDEEXT
result=False
global G_DEBUG
debug=G_DEBUG
if debug: printE('Check file extension:', file)
for e in G_MEDIAEXCLUDEEXT:
e=encodeUTF8(e)
if file.endswith( e ):
if debug: printE('Check file extension ENDSWITH:', file, e)
result=True
break
return result
def getBadWordsFile(file):
global G_BADWORDS
result=False
num=0
global G_DEBUG
debug=G_DEBUG
if os.path.isfile(file):
printE('Loading BadWordsFile:', file)
try:
with open(file, 'r') as f:
data = f.read().splitlines()
if data:
for word in data:
if debug: printE('BadWord+:',word)
G_BADWORDS.append(word)
num+=1
printE('BadWords Loaded:',str(num))
except:
pass
if debug: exit()
return result
def cleanFileName(file):
global G_BADWORDS
global G_DEBUG
debug=G_DEBUG
if isinstance(file,str):
FILENAMECLEAN=file
FILENAME=file
else:
#FILENAMECLEAN=file.decode('UTF-8', 'surrogateescape')
#FILENAME=file.decode('UTF-8', 'surrogateescape')
FILENAMECLEAN=str(encodeUTF8(file),'UTF-8')
FILENAME=str(encodeUTF8(file),'UTF-8')
if debug: printE( 'START Clean Filename: ', FILENAME )
#EXTRACT YEAR
#YEAR=re.search(r"\d{4}", FILENAME).group(1)
YEARS=re.findall('(\d{4})', FILENAME)
YEAR=''
for y in YEARS:
if int(y) > 1900 and int(y) < (datetime.date.today().year + 2):
if debug: printE( 'YEAR: ', y )
YEAR=y
break
#EXTRACT CHAPTER
CHAPTER=False
SEASON=False
CSREMOVE=False
SEASON, CHAPTER, CSREMOVE = extractChapter( FILENAME )
if SEASON != False:
if debug: printE( 'Season: ', SEASON )
if debug: printE( 'Chapter: ', CHAPTER )
if debug: printE( 'Detected: ', CSREMOVE )
else:
if debug: printE( 'No Series data (sxc): ', FILENAME )
#CLEAN FILENAME
FILENAMECLEAN=FILENAME
#SxC cut string
if CSREMOVE != False:
ft=FILENAMECLEAN.split(CSREMOVE)
if ft and len(ft[0]) > 5:
FILENAMECLEAN=ft[0]
if debug: printE( 'File Cut SEASONxCHPATER: ', FILENAMECLEAN )
#REMOVE SEASONxCHAPTER
if CSREMOVE != False:
FILENAMECLEAN=FILENAMECLEAN.replace(CSREMOVE,'')
if debug: printE( 'File Clean SEASONxCHPATER: ', FILENAMECLEAN )
#REMOVE YEAR
FILENAMECLEAN=FILENAMECLEAN.replace(YEAR,'')
if debug: printE( 'File Clean YEAR: ', FILENAMECLEAN )
#()
FILENAMECLEAN=re.sub('\(.*?\)', '', FILENAMECLEAN)
if debug: printE( 'File Clean (): ', FILENAMECLEAN )
#[]
FILENAMECLEAN=re.sub('\[.*?\]', '', FILENAMECLEAN)
if debug: printE( 'File Clean []: ', FILENAMECLEAN )
'''
#domains A
filter=r'(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$'
f=re.sub(filter, '', FILENAMECLEAN, re.IGNORECASE)
if len(f) > 5:
FILENAMECLEAN=f
if debug: printE( 'File Clean Domains A: ', FILENAMECLEAN )
'''
#domains B
filter=r'[a-zA-Z0-9]+\.(com|net|org)'
f=re.sub(filter, '', FILENAMECLEAN, re.IGNORECASE)
if len(f) > 5:
FILENAMECLEAN=f
if debug: printE( 'File Clean Domains B: ', FILENAMECLEAN )
#remove extensions
for rext in remove_extension:
FILENAMECLEAN=FILENAMECLEAN.replace(rext, ' ')
if debug: printE( 'File Clean extensions: ', FILENAMECLEAN )
#remove bad words
for bd in G_BADWORDS:
pattern = re.compile(bd, re.IGNORECASE)
FILENAMECLEAN=pattern.sub(bd,FILENAMECLEAN)
if debug: printE( 'File Clean bad words: ', FILENAMECLEAN )
#remove all non alfanumeric chars
#FILENAMECLEAN=re.sub(r'[^a-zA-Z0-9]', ' ',FILENAMECLEAN, flags=re.UNICODE)
FILENAMECLEAN=re.sub(r'[\_\-\:\,\.=\?\¿\$\"\!]', ' ',FILENAMECLEAN, flags=re.UNICODE)
if debug: printE( 'File Clean All except chars: ', FILENAMECLEAN )
#extra .
FILENAMECLEAN=re.sub('\.+','.',FILENAMECLEAN)
if debug: printE( 'File Clean .: ', FILENAMECLEAN )
#extra spaces
FILENAMECLEAN=re.sub(' +',' ',FILENAMECLEAN)
if debug: printE( 'File Clean spaces: ', FILENAMECLEAN )
#remoev ,
FILENAMECLEAN=re.sub(',+',',',FILENAMECLEAN)
if debug: printE( 'File Clean ,: ', FILENAMECLEAN )
#trim
FILENAMECLEAN=FILENAMECLEAN.strip()
if debug: printE( 'END Clean Filename: ', FILENAMECLEAN )
return YEAR,CHAPTER,SEASON,CSREMOVE,FILENAMECLEAN
def getParam( param ):
global G_DEBUG
result=False
debug=G_DEBUG
#PARAMS
ARG = sys.argv
ARG = list(map(os.fsencode, sys.argv))
if debug: printE( 'Number of arguments:', len(sys.argv), 'arguments.' )
if debug: printE( 'Argument List:', str(sys.argv) )
next=False
for a in ARG:
try:
#, 'surrogateescape'
b=a.decode('UTF-8', 'surrogateescape')
b=str(encodeUTF8(b),'UTF-8')
a=b
except:
pass
if debug: printE( 'Check ARG:', a )
if next:
result=a
break
elif a == param:
if debug: printE( '+ARG:', str(a),param )
if debug: result=a.replace(param,'')
result=u''
next=True
return result
def getSearcher():
result = ''
global CMDSEARCHLIST
valids = []
for s in CMDSEARCHLIST:
if is_tool(s):
valids.append(s)
break
result=random.choice(valids)
printE('External search set to:', result)
return result
def is_tool(name):
"""Check whether `name` is on PATH and marked as executable."""
# from whichcraft import which
from shutil import which
return which(name) is not None
def printE(msg1, msg2='',msg3='',msg4='',msg5=''):
global G_NOINFO
if G_NOINFO == False:
try:
a=str(encodeUTF8(msg1),'UTF-8')
b=str(encodeUTF8(msg2),'UTF-8')
c=encodeUTF8(msg3)
d=encodeUTF8(msg4)
e=encodeUTF8(msg5)
print(a,b,c,d,e)
except:
print(msg1,msg2,msg3,msg4,msg5)
def encodeUTF8( s ):
result=s
if isinstance(s,str) and len(s) > 0:
try:
result=s.encode( "utf-8", errors="ignore")
except:
pass
return result
def extractChapter( filename ):
season = False
chapter = False
sremove = False
#Chapter 0000
filter = '(\d{3,4})'
c=re.findall(filter, filename)
for y in c:
if int(y) > 99 and int(y) < 1910:
printE( 'SeasonXChapter A: ', y )
sremove=y
season=int(int(y)/100)
chapter=int(int(y)-(season*100))
break
if season == False:
#Chapter SxC
filter = '(\d{1,2}x\d{1,2})'
sep = 'x'
c=re.findall(filter, filename)
for y in c:
s, ch = y.split( sep )
if int(s) >= 1 and int(ch) > 0:
printE( 'SeasonxChapter B: ', s, ch )
sremove=s+sep+ch
season=int(s)
chapter=int(ch)
break
if season == False:
#Chapter SXC
filter = '(\d{1,2}X\d{1,2})'
sep = 'X'
c=re.findall(filter, filename)
for y in c:
s, ch = y.split( sep )
if int(s) >= 1 and int(ch) > 0:
printE( 'SeasonXChapter C: ', s, ch )
sremove=s+sep+ch
season=int(s)
chapter=int(ch)
break
return season, chapter, sremove
def nameFormat(format,MEDIAINFO):
result=''
global G_DEBUG
debug=G_DEBUG
#FORMATS
#%title%
#%year%
#%director%
#%season%
#%chapter%
#%genre%
if debug: printE(' Formatting:', format)
format=format.replace('%title%', MEDIAINFO['title'])
if debug: printE(' Formatting:', format)
format=format.replace('%year%', MEDIAINFO['year'])
if debug: printE(' Formatting:', format)
format=format.replace('%director%', MEDIAINFO['director'])
if debug: printE(' Formatting:', format)
format=format.replace('%season%', MEDIAINFO['season'].zfill(2))
if debug: printE(' Formatting:', format)
format=format.replace('%chapter%', MEDIAINFO['chapter'].zfill(2))
if debug: printE(' Formatting:', format)
format=format.replace('%genre%', MEDIAINFO['genres'].split(',')[0])
if debug: printE(' Formatting:', format)
format=format.replace('%chaptertitle%', MEDIAINFO['chaptertitle'])
if debug: printE(' Formatting:', format)
result=format
return result
def interactiveShow(searchdata, defselection=False):
result=False
x=0
urls={}
for d in searchdata:
checkexist=interactiveExist(d['url'],urls)
#printE('CheckExist:',str(checkexist))
if checkexist==False:
printE( '===ITEM: ' + str(x) )
printE( 'Element: ', d[ 'title' ], d[ 'url' ] )
printE( 'Abstract: ' + d[ 'abstract' ] )
urls[x]=(d[ 'url' ])
x+=1
if defselection!=False and defselection in urls.keys():
printE( 'Forced Selected: ' + urls[defselection] )
result=urls[defselection]
else:
while result==False or result.isdigit() == False or int(result) < 0 or int(result) > (x-1):
result=input( 'Select item[0-'+str(x-1)+'][x:exit]: ' )
if result == 'x':
printE('Exit')
exit(0)
if int(result) in urls.keys():
printE( 'Selected: ' + urls[int(result)] )
result=urls[int(result)]
else:
printE( 'Invalid Selected, first: ' + urls[0] )
result=urls[0]
return result
def interactiveExist(url, urls):
result=False
global G_DEBUG
debug=G_DEBUG
a=extractIMDBID(url)
if a:
if debug: printE('Check IMDB:', a, str(urls))
if a in str(urls):
result=True
if debug: printE('Check IMDB FINDED:', a, str(urls))
if result==False:
a=extractFilmAffinityID(url)
if a:
if debug: printE('Check FilmAffinity:', a, str(urls))
a='film'+a
if a in str(urls):
if debug: printE('Check FilmAffinity FINDED:', a, str(urls))
result=True
if result==False:
a=extractTheTVDBID(url)
if a:
if debug: printE('Check TheTVDB:', a, str(urls))
a=''+a
if a in str(urls):
if debug: printE('Check TheTVDB FINDED:', a, str(urls))
result=True
return result
#INET SEARCH
def searchTitle( title, extra='imdb.com' ):
global CMDSEARCH
global CMDSEARCHLIST
global G_INTERACTIVE
result = []
inlist=[]
cmdapp=CMDSEARCH
if G_INTERACTIVE:
nn=input('Search for ['+str(title)+']:')
if nn and len(nn)>0:
title=nn
inlist.append(cmdapp)
#cmd = cmdapp + ' -w imdb.com --json "' + str( title ) + '"'
#cmd = cmdapp + ' --json "' + str( title ) + ' ' + extra + '"'
#cmd = cmdapp + ' --json "' + str( encodeUTF8( title ) ) + ' ' + extra + '"'
#cmd = cmdapp + ' --json "' + str( encodeUTF8( title ), 'UTF-8' ) + ' ' + extra + '"'
#cmd = cmdapp + ' --json "' + str( encodeUTF8( title ), 'ascii', 'ignore' ) + ' ' + extra + '"'
cmd = cmdapp + ' --json "' + str(remove_accents(title)) + ' site:' + str(extra) + '" 2> /dev/null '
data=searchExtCMD(cmd)
if data == False or len(data) == 0:
for s in CMDSEARCHLIST:
if s not in inlist:
cmdapp=s
inlist.append(cmdapp)
#cmd = cmdapp + ' -w imdb.com --json "' + str( title ) + '"'
cmd = cmdapp + ' --json "' + str( remove_accents(title) ) + ' site:' + extra + '" 2> /dev/null '
data=searchExtCMD(cmd)
if data != False and len(data) > 0:
break
if isinstance(data, list) and len(data) > 0:
result = data
printE( "Links: ", len(data))
else:
printE( "Error NO Links: ", data)
return result
def remove_accents(input_str):
try:
nfkd_form = unicodedata.normalize('NFKD', input_str)
return u"".join([c for c in nfkd_form if not unicodedata.combining(c)])
except:
return input_str
def searchExtCMD( cmd ):
data=False
try:
printE( "Search cmd: ", cmd)
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
(output, err) = p.communicate()
#printE( "Search Output: ", output )
p_status = p.wait()
#printE( "Return code : ", p_status )
#get json data
data = json.loads(output)
except:
data=False
pass
return data
#IMDB
def extractIMDBID( url ):
result = False
#IMDBid tt0000000
filter = '(tt\d{7})'
c=re.findall(filter, url)
for y in c:
#printE( 'IMDBid: ', y )
result=y
break
return result
def getIMDBData( id ):
result = False
id =id.replace( 'tt', '' )
printE( 'Get Data IMDB: ', id )
ia = IMDb()
result = ia.get_movie( id )
#ia.update(result, 'all')
ia.update(result, 'release dates')
return result
def imdb_getReleaseDate(data):
result = ''
defdate = ''
global G_COUNTRY
if isinstance(data, list):
for s in data:
country, datenow = s.split('::')
printE( 'Release date check: ', country, datenow )
if defdate == '':
try:
defdate = datetime.datetime.strptime(datenow, "%d %B %Y").strftime('%Y-%m-%d')
except:
pass
printE( 'Release date first defdate: ', defdate )
elif country == G_COUNTRY:
try:
result = datetime.datetime.strptime(datenow, "%d %B %Y").strftime('%Y-%m-%d')
except:
pass
printE( 'Release date finded: ', result )
break
elif country == G_COUNTRY_DEF:
try:
defdate = datetime.datetime.strptime(datenow, "%d %B %Y").strftime('%Y-%m-%d')
except:
pass
printE( 'Release date defdate: ', defdate )
if result == '':
result = defdate
return result
def imdb_getPlot(data):
result = ''
if isinstance(data, list):
for s in data:
d=s.split('::')
if len(d) == 1:
plot=d[0]
else:
plot=s
if len(d) == 2:
username=d[1]
else:
username=''
#printE( 'Plot search: ', plot, username )
if len(plot) > len(result):
result=plot
return result
def imdb_getPlotShort(data):
result = ''
if isinstance(data, list):
for s in data:
d=s.split('::')
if len(d) == 1:
plot=d[0]
else:
plot=s
if len(d) == 2:
username=d[1]
else:
username=''
#printE( 'Plot Short search: ', plot, username )
if len(result) == 0:
result=plot
elif len(result) > len(plot):
result=plot
return result
#FILMAFFINITY
def extractFilmAffinityID( url ):
result = False
#FilmAffinity /film605498.html
filter = '(film\d{6}.html)'
c=re.findall(filter, url)
for y in c:
y=y.replace('film','').replace('.html','')
if y.isdigit():
#printE( 'FilmAffinityID: ', y )
result=y
break
return result
#OMDB
def omdb_getReleaseDate(date):
result=False
if result==False:
try:
result=str(datetime.datetime.strptime(date, "%d %b %Y").strftime('%Y-%m-%d'))
except:
pass
if result==False:
try:
result=str(datetime.datetime.strptime(date, "%d %B %Y").strftime('%Y-%m-%d'))
except:
pass
if result==False:
try:
result=str(datetime.datetime.strptime(date, "%d-%m-%Y").strftime('%Y-%m-%d'))
except:
pass
if result==False:
try:
result=str(datetime.datetime.strptime(date, "%Y-%m-%d").strftime('%Y-%m-%d'))
except:
pass
return result
#TheTVDB
def extractTheTVDBID( url ):
result = False
#TheTVDB .thetvdb.com/?id=311902&tab=series
filter = '(id=\d{3,8}&)'
c=re.findall(filter, url)
for y in c:
result=y.replace('id=','').replace('&','')
printE( 'TheTVDB: ', result )
break
return result
def tvdbid_extradata(title,season,chapter):
result=False
printE('Extradata TheTVDB', title, season, chapter)
t = tvdb_api.Tvdb(language=G_LANG)
try:
data = t[title]
#printE('TheTVDB result: ',data.data.keys())
#printE('Episode title TheTVDB result: ',data.data)
if len(data.data.keys())>0:
printE('Extradata TheTVDB result: ',data['seriesName'])
result={}
result['releasedate']=omdb_getReleaseDate(data['firstAired'])
result['chaptertitle']=data[season][chapter]['episodeName']
except:
pass
return result
#END FUNCTIONS
#PARAMS
ARG = sys.argv
#printE( 'Number of arguments:', len(sys.argv), 'arguments.' )
#printE( 'Argument List:', str(sys.argv) )
#ASSING PARAMS
#--json
p=getParam('--json')
if p != False:
#printE('JSon response. ')
G_JSON=True
G_NOINFO=True
#BASE INFO
printE( '' )
printE( MSG_APPINFO )
printE( '' )
#-h or no params
if len(ARG) < 2 or getParam('-h') != False:
G_NOINFO=False
printE( 'Usage:' )
printE( ' pymediaident.py [options] filetoscan' )
printE( MSG_OPTIONS )
printE( '' )
FILE=False
exit(0)
#-v
p=getParam('-v')
if p != False:
printE('VERBOSE MODE')
G_DEBUG=True
#-es
p=getParam('-es')
if p in CMDSEARCHLIST:
printE('External search from:', p)
CMDSEARCH=p
else:
p=getSearcher()
printE('Default External search from:', p)
CMDSEARCH=p
#-s
p=getParam('-s')
if p in G_GETDATAFROM_LIST:
printE('Assing webdata from:', p)
G_GETDATAFROM=p
#-sid
p=getParam('-sid')
if p and len(p) > 0:
printE('ID for scrapper from:', p)
G_GETDATAFROM_ID=p
#-apikey
p=getParam('-apikey')
if p and len(p) > 0:
printE('Apikey for:', G_GETDATAFROM)
G_GETDATAFROM_KEY=p
#-l
p=getParam('-l')
if p and len( p ) == 2:
printE('Assing languaje to:', p)
G_LANG=p
#-c
p=getParam('-c')
if p!=False:
printE('Assing country to:', str(p))
G_COUNTRY=str(p)
#-rfm
p=getParam('-rfm')
if p != False:
printE('Movies Format: ', p)
G_RENAME_FORMAT_MOVIE=p
#-rfs
p=getParam('-rfs')
if p != False:
printE('Series Format: ', p)
G_RENAME_FORMAT_SERIE=p