-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathltv-downloader.py
1915 lines (1531 loc) · 74.1 KB
/
ltv-downloader.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 python
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals # at top of module
#### User Configurations ####
## Fill yours - This is REQUIRED by the LTV website.
ltv_username = 'USERNAME'
ltv_password = 'PASS'
# Folder to scan when no arguments are passed
default_folder = '.'
# Ordered, from: pt, br, en
preferred_languages = ['pt','br','en']
# Rename downloaded subtitles to the same name of the video file, and append language code
rename_subtitle = True
append_language = True
# Download one subtitle file for each of the prefered languages
download_each_lang = False
# Remove old subtitle languages when a prefered becomes available
clean_old_language = False
# Append a confidence/quality number to then end of the subtitle file. Allows "upgrading" with the same language
# Most players ignore this last number and correctly identify the srt file. If not, make this False
append_confidence = False
# Stop if #-Lang is already present: 1-PT, 2-PT/BR, 3-EN/PT/BR etc
stopSearchWhenExistsLang = 1
# Keeps a subtitle with the same name of the video (hard)linking to the best available subtitle.
# Occupies no space, but only useful for some old playeres that don't support language codes in subtitle files
hardlink_without_lang_to_best_sub = False
# Set this to 80 or 90 if you just want to download the best languague and subtitle
confidence_threshold = 50
# Recursivity also becomes active after a '-r' argument
recursive_folders = False
# Append or update IMDB rating at the end of movie folders
# Folders must have the movie name followed by the year inside parenthesis, otherwise they are ignored
# eg: "Milk (2008)" becomes: "Milk (2008) [7.7]"
append_iMDBRating = True
# Rename and clean videos and accompanying files from this garbage-tags
fix_ETTV_subfolder = True
# Rename and clean videos and accompanying files from this garbage-tags
clean_original_filename = True
clean_name_from = ['VTV','www.torentz.3xforum.ro','MyTV','RARBG','rartv','eztv','ettv']
Debug = 0
####### End of regular user configurations #######
## Set this flag using -f as parameter, to force search and replace all subtitles.
## This option is implied when only one argument is passed (single file dragged & dropped)
ForceSearch=False
OnlyIMDBRating = False
## LegendasTV timeout and number of threads to use. Increasing them too high may affect the website performance, please be careful
ltv_timeout = 15
thread_count = 5
#### Known Arrays
# No need to change those, but feel free to add/remove some
valid_subtitle_extensions = ['srt','txt','aas','ssa','sub','smi']
valid_video_extensions = ['avi','mkv','mp4','wmv','mov','mpg','mpeg','3gp','flv']
valid_extension_modifiers = ['!ut','part','rar','zip']
known_release_groups = ['YTS','LOL','killers','ASAP','dimension','ETRG','rarbg','fum','ift','2HD','FoV','FQM','DONE','vision','fleet'
,'Yify','MrLss','fever','p0w4','TLA','refill','notv','reward','bia','maxspeed','FiHTV','BATV','SickBeard','sfm']
# garbage is ignored from filenames
garbage = ['Unrated', 'DC', 'Dual', 'VTV', 'ag', 'esubs', 'eng', 'subbed', 'artsubs', 'sample', 'ExtraTorrentRG', 'StyLish', 'Release', 'Internal', '2CH' ]
# undesired wordslowers the confidence weight if detected
undesired = ['.HI.', '.Impaired.', '.Comentários.', '.Comentarios.' ]
# video_quality, video_size and release_groups should agree between movie file and subtitles, otherwise weight is reduced
video_quality = ['HDTV', 'PDTV', 'XviD', 'DivX', 'x264', 'aac', 'dd51', 'webdl', 'webrip', 'BluRay', 'blueray', 'BRip', 'BRRip', 'BDRip', 'DVDrip', 'DVD', 'AC3', 'DTS', 'TS', 'R5', 'R6', 'DVDScr', 'PROPER', 'REPACK' ]
video_size = ['480', '540', '720', '1080']
####### Dragons ahead !! #######
Done = False
import os, sys, traceback
import json, re
import shutil, stat, glob, filecmp, tempfile
import signal, platform
import threading, time, random
from zipfile import ZipFile
if(platform.system().lower().find("windows") > -1):
if Debug > 2:
print('Windows system detected')
import msvcrt
getch = msvcrt.getch
def winHardLink(source, link_name):
import ctypes
ch1 = ctypes.windll.kernel32.CreateHardLinkW
ch1.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32)
ch1.restype = ctypes.c_ubyte
if not ch1(link_name, source, 0):
raise ctypes.WinError()
os.link = winHardLink
def winSymLink(source, link_name):
import ctypes
csl = ctypes.windll.kernel32.CreateSymbolicLinkW
csl.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32)
csl.restype = ctypes.c_ubyte
flags = 0
if source is not None and os.path.isdir(source):
flags = 1
if not csl(link_name, source, flags):
raise ctypes.WinError()
os.symlink = winSymLink
else:
if Debug > 2:
print('Unix system detected')
import sys, tty
#fd = sys.stdin.fileno()
#if not os.isatty(sys.stdin.fileno()):
# # Cron Mode
tty.setraw(sys.stdin.fileno())
getch = sys.stdin.read(1)
REQUIREMENTS = [ 'future', 'requests' , 'beautifulsoup4', 'rarfile' ]
try:
from future.utils import iteritems
import requests
from bs4 import BeautifulSoup
from rarfile import RarFile
from queue import Queue, Empty
except (Exception) as e:
print('! Missing requirements. '+str(type(e)))
import os, pip
pip_args = [ ]
# pip_args = [ '-vvv' ]
if 'http_proxy' in os.environ:
proxy = os.environ['http_proxy']
if proxy:
pip_args.append('--proxy')
pip_args.append(proxy)
pip_args.append('install')
for req in REQUIREMENTS:
pip_args.append( req )
print('Installing: ' + str(REQUIREMENTS))
pip.main(pip_args)
# pip.main(initial_args = pip_args)
# try to import again
try:
from future.utils import iteritems
import requests
from bs4 import BeautifulSoup
from rarfile import RarFile
from queue import Queue, Empty
print('Sucessfully installed the required libraries\n')
except (Exception) as e:
print('\nPython modules needed: ' + str(REQUIREMENTS))
print('We failled to install them automatically: '+str(type(e)))
print('! Traceback:')
traceback.print_exc(file=sys.stdout)
print()
print('\nTry running this with Admin Priviliges, or')
print('Run in a command prompt Admin Priviliges:\n')
print('pip install requests beautifulsoup4 rarfile')
print('\nPress any key to exit...')
if Debug > -1:
junk = getch()
sys.exit('Unmet dependencies: requests beautifulsoup4 rarfile')
def signal_handler(signal, frame):
global videosQ, Done
Done=True
videosQ.queue.clear()
print('Cleared List. Terminating in 5s')
time.sleep(5)
sys.exit('User ordered a termination')
signal.signal(signal.SIGINT, signal_handler)
lock = threading.Lock()
local = threading.local()
local.output = ''
local.wanted_languages = []
if ltv_username is "USERNAME":
print('\nPlease edit ltv-downloader.py file and configure with your LTV\'s Username and Password...')
junk = getch()
sys.exit()
def SameFile(file1, file2):
try:
return filecmp.cmp(file1, file2)
# return os.stat(file1) == os.stat(file2)
except:
return False
os.path.samefile = SameFile
def UpdateFile(src, dst):
if src == dst:
return True
exc = ""
for x in [1, 2, 3]:
try:
if not os.path.isfile(src):
return False
if not os.path.isfile(dst):
os.rename(src, dst)
return True
if os.path.samefile(src, dst):
os.remove(src)
return True
if os.path.getsize(src) < 1500 and os.path.getsize(dst) >= 1500:
os.remove(src)
return True
if os.path.getsize(dst) < 1500 and os.path.getsize(src) >= 1500:
os.remove(dst)
os.rename(src, dst)
return True
if os.path.getmtime(src) < os.path.getmtime(dst):
os.remove(src)
return True
if os.path.getmtime(dst) < os.path.getmtime(src):
os.remove(dst)
os.rename(src, dst)
return True
if os.path.getsize(src) < os.path.getsize(dst):
os.remove(src)
return True
if os.path.getsize(dst) < os.path.getsize(src):
os.remove(dst)
os.rename(src, dst)
return True
os.remove(dst)
os.rename(src, dst)
return True
except (Exception) as e:
exc = e
time.sleep(0.1)
pass
print('\nSomething went wrong renaming files: '+str(type(exc))+'\n'+src+'\nto:\n'+dst)
return False
def stringify(input):
if isinstance(input, dict):
return {stringify(key):stringify(value) for key,value in input.items()}
elif isinstance(input, list):
return [stringify(element) for element in input]
elif isinstance(input, str):
return input.encode('ascii', 'replace').decode('utf8')
else:
return input
## Takes car of everything related to the Website
class LegendasTV:
def __init__(self, ltv_username, ltv_password, download_dir=None):
if not download_dir:
download_dir = tempfile.gettempdir()
self.download_path = os.path.abspath(download_dir)
self.base_url = 'http://legendas.tv'
self.username = ltv_username
self.password = ltv_password
self.login_url = self.base_url+'/login'
self.logout_url = self.base_url+'/users/logout'
#self.searh_url = self.base_url+'/busca/'
self.searh_url = self.base_url+'/util/carrega_legendas_busca/'
self.download_url = self.base_url+'/downloadarquivo/'
self.session = requests.Session()
self.session.auth = (ltv_username, ltv_password)
self.session.headers.update({'User-Agent': 'LegendasTV-Downloader at GitHub'})
self.session.mount("http://", requests.adapters.HTTPAdapter(max_retries=3))
## Login in legendas.tv
def login(self):
login_data= {'data[User][username]':self.username,'data[User][password]':self.password, '_method':'POST'}
try:
r = self.session.post(self.login_url, data=login_data, timeout=ltv_timeout)
r.raise_for_status()
except (Exception) as e:
if Debug > -1:
print('! Error, loging in! '+str(type(e)))
return False
if "rio ou senha inv" in r.text:
if Debug > -1:
print('! Error, wrong login user/pass!')
return False
return True
## Logout
def logout(self):
try:
r = self.session.get(self.logout_url, timeout=ltv_timeout)
r.raise_for_status()
except (Exception) as e:
if Debug > -1:
print('! Error, loging out! '+str(type(e)))
return False
return True
## Search and select best subtitle
def search(self, originalShow):
if Debug > 2:
local.output+='------- Searching -------\n'
if Debug > 2:
local.output+='ShowName='+str(originalShow['ShowName'])+'\n'
local.output+='Year='+str(originalShow['Year'])+'\n'
local.output+='Season='+str(originalShow['Season'])+'\n'
local.output+='Episode='+str(originalShow['Episode'])+'\n'
local.output+='Group='+str(originalShow['Group'])+'\n'
local.output+='Quality='+str(originalShow['Quality'])+'\n'
local.output+='Size='+str(originalShow['Size'])+'\n'
local.output+='Undesired='+str(originalShow['Undesired'])+'\n'
local.output+='Unknown='+str(originalShow['Unknown'])+'\n'
local.output+='\n'
list_possibilities = []
for iTry in 1,2,3:
if len(list_possibilities) > 0:
break
vsearch_array = []
if originalShow['Season'] and originalShow['Episode']:
if iTry == 1:
if len(originalShow['Episode'])>1:
vsearch_array.append(' '.join(originalShow['ShowName'])+' '+"S{:02d}E".format(originalShow['Season'][0]) + "E".join('{:02d}'.format(a) for a in originalShow['Episode']))
vsearch_array.append(' '.join(originalShow['ShowName'])+' '+"S{:02d}E{:02d}".format(originalShow['Season'][0], originalShow['Episode'][0]))
if iTry == 2:
if len(originalShow['Episode'])>1:
vsearch_array.append(' '.join(originalShow['ShowName'])+' '+"{:0d}x".format(originalShow['Season'][0]) + "x".join('{:02d}'.format(a) for a in originalShow['Episode']))
vsearch_array.append(' '.join(originalShow['ShowName'])+' '+"{:0d}x{:02d}".format(originalShow['Season'][0], originalShow['Episode'][0]))
if iTry == 3:
vsearch_array.append(' '.join(originalShow['ShowName'])+' '+"{:0d}{:02d}".format(originalShow['Season'][0], originalShow['Episode'][0]))
##vsearch_array.append(' '.join(originalShow['ShowName'])+' '+"{:0d} {:02d}".format(originalShow['Season'][0], originalShow['Episode'][0]))
else:
if iTry == 1:
if originalShow['Group'] and originalShow['Year']:
vsearch_array.append(' '.join(originalShow['ShowName'])+' '+originalShow['Group'][0]+' '+originalShow['Year'][0])
if iTry == 2:
if originalShow['Year']:
vsearch_array.append(' '.join(originalShow['ShowName'])+' '+originalShow['Year'][0])
if originalShow['Group']:
vsearch_array.append(' '.join(originalShow['ShowName'])+' '+originalShow['Group'][0])
if iTry == 3:
vsearch_array.append(' '.join(originalShow['ShowName']))
## Search 6 pages and build a list of possibilities
for vsearch in vsearch_array:
# vsearch = urllib.parse.quote(vsearch)
for vsearch_prefix in ['/-/-', '/-/-/2', '/-/-/3', '/-/-/4', '/-/-/5', '/-/-/6']:
newPossibilities = 0
if Debug < 2:
local.output+='. '
else:
local.output+="\nSearching for subtitles with: "+vsearch+" , "+vsearch_prefix+'\n'
url = self.searh_url + vsearch + vsearch_prefix
try:
r = self.session.get(url, timeout=ltv_timeout)
r.raise_for_status()
except (Exception) as e:
if Debug > -1:
local.output+='! Error Searching 3 times! '+str(type(e))+'\n'
local.output+=url+'\n'
with lock:
statistics['Failed'] += 1
return False
soup = BeautifulSoup(r.text, "html.parser")
div_results = soup.find('div',{'class':'gallery clearfix list_element'})
if div_results:
div_results = div_results.findAll('article',recursive=False)
if not div_results:
if Debug > 2:
local.output+='No results\n'
break
for span_article in div_results:
span_results = span_article.findAll('div',recursive=False)
if not span_results:
if Debug > 2:
local.output+='No results\n'
continue
for span in span_results:
try:
td = span.find('a').get('href')
subName = span.find('a').contents[0]
flag = span.find('img').get('src')
except:
if Debug > 1:
local.output+="! Error parsing result list: "+span.prettify()+'\n'
continue
if not td:
if Debug > 2:
local.output+='#### Something went wrong ####\n'
continue
# Parse the link
tmpregex = re.search('/download/([^/\\\]+)/([^/\\\]+)/([^/\\\]+)',td)
if not tmpregex or tmpregex.lastindex<3:
local.output+='#### Error parsing link:'+td+' ####\n'
continue
# Get the download ID
download_id = tmpregex.group(1)
release = tmpregex.group(3)
if not download_id or not release:
if Debug > 2:
local.output+='Couldn\'t get download_id and Release\n'
continue
if download_id in [x['id'] for x in list_possibilities]:
## Already listed this
continue
## Get the language
tmpregex = re.search('/[a-zA-Z0-9]*/(?:icon|flag)_([a-zA-Z0-9]+)\.(gif|jpg|jpeg|png)',flag)
if not tmpregex or tmpregex.lastindex<2:
local.output+='#### Error parsing flag: '+flag+' ####\n'
continue
language = tmpregex.group(1)
possibility = {}
possibility.clear()
newPossibilities += 1
possibility['%'] = 100
possibility['id'] = download_id
possibility['release'] = release.lower()
possibility['sub_name'] = subName.lower()
if 'pt' in language:
possibility['language'] = 'pt'
elif 'braz' in language:
possibility['language'] = 'br'
elif 'usa' in language:
possibility['language'] = 'en'
else:
if Debug > 2:
local.output+='Couldn\'t get Language\n'
continue
# Filter wanted_languages
if possibility['language'] not in preferred_languages:
if Debug > 2:
local.output+='0!!, Wrong language: '+possibility['language']+', from: '+str(preferred_languages)+'\n'
continue
#downloads = td.contents[5]
#possibility['downloads'] = downloads.lower()
#comments = td.contents[7]
#possibility['comments'] = comments.lower()
#rating = td.contents[8].contents[1]
#possibility['rating'] = rating.lower()
#uploader = td.parent.find('a').contents[0]
#possibility['uploader'] = uploader
#date = span.findAll('td')[2].contents[0]
#possibility['date'] = date.lower()
if Debug > 2:
local.output+='\nFOUND!: '+possibility['language']+' - '+possibility['release']+'\n'
releaseShow = parseFileName(possibility['release'])
subnameShow = parseFileName(possibility['sub_name'])
releaseShow['ShowName'] = list(set(releaseShow['ShowName'] + subnameShow['ShowName']))
releaseShow['Year'] = list(set(releaseShow['Year'] + subnameShow['Year']))
releaseShow['Season'] = list(set(releaseShow['Season'] + subnameShow['Season']))
releaseShow['Episode'] = list(set(releaseShow['Episode'] + subnameShow['Episode']))
releaseShow['Group'] = list(set(releaseShow['Group'] + subnameShow['Group']))
releaseShow['Quality'] = list(set(releaseShow['Quality'] + subnameShow['Quality']))
releaseShow['Size'] = list(set(releaseShow['Size'] + subnameShow['Size']))
releaseShow['Undesired'] = list(set(releaseShow['Undesired'] + subnameShow['Undesired']))
releaseShow['Unknown'] = list(set(releaseShow['Unknown'] + subnameShow['Unknown']))
possibility['%'] = calculateSimilarity(originalShow, releaseShow)
if not download_each_lang:
langindex = preferred_languages.index(possibility['language'])
if Debug > 2:
local.output+='-'+str(langindex*21)+', Language '+possibility['language']+' at pos '+str(langindex)+'\n'
possibility['%'] -= 21*langindex
list_possibilities.append(possibility)
if Debug > 2:
local.output+='Got results: '+str(newPossibilities)+'\n'
## If this result page was not full, don't read the next one
if newPossibilities < 20:
break
if not list_possibilities:
if Debug > 2:
local.output+='No subtitles found\n'
with lock:
statistics['NoSubs'] += 1
return False
if Debug > 2:
local.output+='------------------\n'
final_list = sorted(list_possibilities, key=lambda k: k['%'], reverse=True)
for idx, possibility in enumerate(final_list):
if Debug > 1:
local.output+='Chance '+str(idx)+', '+str(possibility['%'])+'%, '+possibility['language']+', '+possibility['release'] + ' | ' + possibility['sub_name'] +'\n'
if final_list[0]['language'] not in local.wanted_languages:
if Debug > 2:
local.output+='\n-- Best subtitle already present --\n\n'
with lock:
statistics['NoBest'] += 1
return False
return final_list[0]
## Downloads a subtitle given it's ID
def download(self, subtitle):
download_id = subtitle['id']
if download_id:
url_request = self.download_url+download_id
if Debug == 0:
local.output+='Download'
if Debug > 2:
local.output+='\n------- Downloading -------\n'
local.output+='Downloading '+subtitle['language']+', '+subtitle['release']+'\n'
try:
r = self.session.get(url_request, timeout=ltv_timeout*4)
# print("\nurl:\n"+str(r.url))
# print("\nrequested headers:\n"+str(r.request.headers))
# print("\nheaders:\n"+str(r.headers))
# print("\ncookies:\n"+str(r.cookies))
r.raise_for_status()
except (Exception) as e:
if Debug > 1:
local.output+='! Error downloading! '+str(type(e))+'\n'
return False
legenda = r.content
localName = ""
if 'Content-Disposition' in r.headers and "filename=" in r.headers['Content-Disposition']:
# If the response has Content-Disposition, we take file name from it
localName = r.headers['Content-Disposition'].split('filename=')[1]
if localName[0] == '"' or localName[0] == "'":
localName = localName[1:-1]
if len(localName)>4:
self.archivename= os.path.join(self.download_path, str(localName))
else:
self.archivename = os.path.join(self.download_path, str(download_id))
if r.url.endswith('.rar') or ('Content-Type' in r.headers and 'rar' in r.headers['Content-Type']):
self.archivename += '.rar'
elif r.url.endswith('.zip') or ('Content-Type' in r.headers and 'zip' in r.headers['Content-Type']):
self.archivename += '.zip'
elif r.url.endswith('.srt') or ('Content-Type' in r.headers and 'srt' in r.headers['Content-Type']):
if Debug > -1:
local.output+='Downloaded an .SRT. Are you logged in?\n'
return False
else:
if Debug > 2:
local.output+='No download MIME TYPE. Not forcing extension\n'
if Debug > 2:
local.output+=' Downloaded :'+self.archivename+'\n'
f = open(self.archivename, 'wb')
f.write(legenda)
#pickle.dump(legenda, f)
f.close()
if Debug > 2:
local.output+='Subtitle downloaded with sucess!\n'
return True
## Choose the likeliest and extracts it
def extract_sub(self, dirpath, originalFilename, originalShow, language):
global lock
if Debug > 2:
local.output+='\n------- Extracting -------\n'
if Debug > 3:
local.output+='File: '+self.archivename+'\n'
if Debug > 2:
local.output+="Extracting a "
try:
archive = ZipFile(self.archivename)
if Debug > 2:
local.output+='zip file...\n'
except:
try:
archive = RarFile(self.archivename)
if Debug > 2:
local.output+='rar file...\n'
except:
if self.archivename.endswith(tuple(valid_subtitle_extensions)):
if Debug > -1:
local.output+='\n! Error! Downloaded file was not an archive: '+self.archivename+'\n'
else:
if Debug > -1:
local.output+='\n! Error! Opening archive: '+self.archivename+'\n'
local.output+='UNRAR must be available on console\n'
if os.path.getsize(self.archivename) < 1500:
fp = open(self.archivename, "r")
content = fp.read()
fp.close()
if Debug > -1:
local.output+='\n! Small file, content: '+content+'\n'
with lock:
statistics['Failed'] += 1
return False
language_compensation = 0
if not download_each_lang:
langindex = -1
langindex = local.wanted_languages.index(language)
if langindex>=0:
language_compensation = 21*langindex
else:
local.output+='No language? '+language+'\n'
files = archive.infolist()
if Debug > 2:
local.output+='Files in Archive: ' + str(files)+'\n'
srts = []
current_maxpoints = -100
best_rarfile = []
for current_rarfile in files:
testname = current_rarfile.filename.lower()
testname = os.path.basename(str(testname))
if not testname.endswith(tuple(valid_subtitle_extensions)+('rar', 'zip')):
if Debug > 2:
local.output+='Non Sub file: ' + str(current_rarfile)+'\n'
continue
if Debug > 2:
local.output+='\n--- Analyzing: '+str(testname)+'\n'
compressedShow = parseFileName(testname)
points = calculateSimilarity(originalShow, compressedShow)
points = points - language_compensation
if Debug > 2:
local.output+='Adding subtitle file with '+str(points)+'% : '+str(testname)+'\n'
if current_maxpoints<points:
current_maxpoints = points
best_rarfile = current_rarfile
if Debug > 2:
local.output+='-------\n'
if not best_rarfile or current_maxpoints<-99:
if Debug > -1:
local.output+='! Error: No valid subs found on archive\n'
with lock:
statistics['Failed'] += 1
return False
extract = []
extract.append(best_rarfile)
# maximum=confidence_threshold
# for idx, [p, n] in enumerate(srts):
# print "Result %d, %d%%: %s" % (idx, p, n.filename)
# if p >= maximum:
# maximum = p
# extract.append(n)
## Extracting
for fileinfo in extract:
dest_filename = os.path.basename(fileinfo.filename) # This prevents from extracting from sub-folders
# fileinfo.filename = os.path.basename(fileinfo.filename) # This prevents from extracting from sub-folders
if Debug > 2:
local.output+='Extracted '+dest_filename+' with ' +str(current_maxpoints+language_compensation)+'%\n'
if dest_filename.endswith(('rar', 'zip')):
if Debug > 2:
local.output+='Recursive extract, RAR was inside: '+fileinfo.filename+'\n'
archive.extract(fileinfo, self.download_path)
self.archivename = os.path.join(self.download_path, fileinfo.filename)
if not ltv.extract_sub(dirpath, originalFilename, group, size, quality, language):
return False
continue
if len(extract) == 1 and rename_subtitle:
dest_filename = os.path.splitext(originalFilename)[0] + os.path.splitext(dest_filename)[1]
if append_language:
dest_filename = os.path.splitext(dest_filename)[0]+'.'+language+os.path.splitext(dest_filename)[1]
if append_confidence:
dest_filename = os.path.splitext(dest_filename)[0]+'.'+str(current_maxpoints+language_compensation)+os.path.splitext(dest_filename)[1]
if Debug > 2:
local.output+='Extracting subtitle as: '+dest_filename+'\n'
dest_fullFilename = os.path.join(dirpath, dest_filename)
try:
fileContents = archive.read(fileinfo)
f = open(dest_fullFilename, 'wb')
f.write(fileContents)
f.close()
if Debug > 2:
local.output+='Subtitle saved with sucess in: '+dirpath+'!\n'
with lock:
statistics['DL'] += 1
if not local.wanted_languages == preferred_languages:
statistics['Upg'] += 1
if language == local.wanted_languages[0]:
statistics['Best'] += 1
else:
statistics['NoBest'] += 1
if language == 'pt':
statistics['PT'] += 1
elif language == 'br':
statistics['BR'] += 1
elif language == 'en':
statistics['EN'] += 1
except (Exception) as e:
with lock:
statistics['Failed'] += 1
if Debug > 0:
local.output+='! Error, decrompressing! '+str(type(e))+'\n'
elif Debug > -1:
local.output+='! Error, decrompressing!\n'
if clean_old_language:
tmp = os.path.splitext(os.path.join(dirpath, originalFilename))[0] + '.??.s*'
for tmp2 in glob.glob(re.sub(r'(?<!\[)\]', '[]]', re.sub(r'\[', '[[]', tmp))):
if Debug > 2:
local.output+='Found: '+tmp2+'\n'
if os.path.samefile(dest_fullFilename, tmp2):
continue
if Debug > 2:
local.output+='Deleted old language: '+os.path.basename(tmp2)+'\n'
os.remove(tmp2)
## Create hard/SymLink with the same name as the video, for legacy players
if hardlink_without_lang_to_best_sub and ( not rename_subtitle or append_language):
createLinkSameName(Folder=dirpath, Movie=originalFilename, Destination=dest_filename)
return True
def moveMedia(src, dst):
dstFolder = os.path.dirname(dst)
scrFileName = os.path.splitext(os.path.basename(src))[0]
dstFileName = os.path.splitext(os.path.basename(dst))[0]
# Moving main video file
if UpdateFile(src, dst):
if Debug > 1:
local.output+='Moved ' + os.path.basename(src) + ' to: '+os.path.basename(dstFolder)+'\n'
else:
if Debug > 1:
local.output+='! Error renaming. File in use? '+filename+'\n'
return False
# Moving related subtitles
sub_pattern = re.sub(r'(?<!\[)\]', '[]]', re.sub(r'\[', '[[]', os.path.splitext(src)[0]+'.*'))
for tmpFile in glob.glob(sub_pattern):
if not os.path.splitext(tmpFile)[1][1:] in valid_subtitle_extensions:
if Debug > 2:
local.output+='Not a valid extension: '+os.path.splitext(tmpFile)[1][1:]+'\n'
continue
if Debug > 1:
local.output+='File found to move: '+tmpFile+'\n'
newFile = os.path.basename(tmpFile).replace(scrFileName, dstFileName)
newFullPath = os.path.join(dstFolder, newFile)
if Debug > 1:
local.output+='Renaming to: '+newFile+'\n'
if not UpdateFile(tmpFile, newFullPath):
if Debug > -1:
local.output+='! Error recovering subtitle from ETTV folder! '+tmpFile+'\n'
else:
if Debug > -1:
local.output+='Recovered 1 subtitle from ETTV folder: '+newFile+'\n'
return True
def checkAndDeleteFolder(src):
# Search for subtitles or media files
for files in os.listdir(src):
if Debug > 2:
local.output+='File found: '+files+' with ext: '+os.path.splitext(files)[1][1:]+'\n'
if files in ['RARBG.COM.mp4','RARBG.mp4']:
continue
if os.path.splitext(files)[1][1:] in [x for x in valid_subtitle_extensions if x != 'txt']:
return False
if os.path.splitext(files)[1][1:] in valid_video_extensions:
return False
if os.path.splitext(files)[1][1:] in valid_extension_modifiers:
return False
# os.remove(os.path.join(src,files))
if Debug > 1:
local.output+='Parent folder is empty. Removed!\n'
def del_rw(action, name, exc):
os.chmod(name, stat.S_IWRITE)
local.output+='Had to fix permissions to delete file: '+name+'\n'
os.remove(name)
os.removedirs(name)
shutil.rmtree(src, onerror=del_rw)
# os.rmdir(src)
return True
# Remove garbage from filenames
def cleanAndRenameFile(Folder, filename):
# Generate Regex
regex = '(' + '|'.join(clean_name_from)+')'
if not re.search('[^a-zA-Z0-9\-]+'+regex+'[^a-zA-Z0-9\-]', filename, re.I):
return filename
statementClean = re.compile('[^a-zA-Z0-9\-]+'+regex+'[\]\)\}]?', re.I)
newname = statementClean.sub('', filename)
fullFilename = os.path.join(Folder, filename)
fullNewname = os.path.join(Folder, newname)
# Sanity check
if fullFilename == fullNewname:
if Debug > 2:
local.output+='Error cleaning original name\n'
return filename
# Cleaning video file
if UpdateFile(fullFilename, fullNewname):
if Debug > -1:
local.output+='Renamed to: '+newname+'\n'
else:
if Debug > 2:
local.output+='! Error renaming. File in use? '+filename+'\n'
return filename
# Cleaning related subtitles and other files with different extensions
sub_pattern = re.sub(r'(?<!\[)\]', '[]]', re.sub(r'\[', '[[]', os.path.splitext(fullFilename)[0]+'.*'))
for tmpFile in glob.glob(sub_pattern):
tmpNew = statementClean.sub('', tmpFile)
if tmpNew != tmpFile:
if UpdateFile(tmpFile, tmpNew):
if Debug > -1:
local.output+='Renamed sub to: '+tmpNew+'\n'
else:
if Debug > -1:
local.output+='! Error renaming subtitles: '+tmpFile+'\n'
return newname
# Fix ETTV folders
def cleanAndMoveFromSubfolder(origFolder, origFilename):
shouldMove = False
# Generate Regex
regex = '(' + '|'.join(clean_name_from)+')'
statementClean = re.compile('[^a-zA-Z0-9\-]+'+regex+'[\]\)\}]?', re.I)
origAbsoluteFile = os.path.join(origFolder, origFilename)
parentFolder = os.path.basename(origFolder)
grandParentFolder = os.path.dirname(origFolder)
if not os.path.lexists(grandParentFolder):
return (origFolder, origFilename)
cleanParentFolder = statementClean.sub('', parentFolder)
cleanFilename = statementClean.sub('', origFilename)
fileExt = os.path.splitext(cleanFilename)[1]
## If file and folder have the same full name, move
if cleanParentFolder == os.path.splitext(cleanFilename)[0]:
if moveMedia(origAbsoluteFile, os.path.join(grandParentFolder, cleanFilename)):
deleted = checkAndDeleteFolder(origFolder)
if Debug > -1:
if deleted:
local.output+='ETTV subfolder fixed: '+cleanFilename+'\n'
else:
local.output+='ETTV subfolder fixed, but not yet empty!: '+cleanFilename+'\n'
return (grandParentFolder, cleanFilename)
else:
if Debug > -1:
local.output+='ETTV subfolder detected, but failed to fix\n'
return (origFolder, origFilename)
## If parent has a tv showname, parse its info
if re.match(".+[^a-zA-Z0-9]S\d\dE\d\d(E\d\d)?[^a-zA-Z0-9].+", cleanParentFolder):
if Debug > 1:
local.output+='Father has a TV Show name...'
try:
name=re.sub("(.+[^a-zA-Z0-9])S\d\dE\d\d(E\d\d)?[^a-zA-Z0-9].+", '\\1', cleanParentFolder) # Including ending \. (dot)
season=int(re.sub(".+[^a-zA-Z0-9]S(\d\d)E\d\d(E\d\d)?[^a-zA-Z0-9].+", '\\1', cleanParentFolder))
episode=int(re.sub(".+[^a-zA-Z0-9]S\d\dE(\d\d)(E\d\d)?[^a-zA-Z0-9].+", '\\1', cleanParentFolder))
except (Exception) as e:
if Debug > -1:
local.output+='Very strange error happened, parsing ETTV folder. Report to programmer please!\n'
return (origFolder, origFilename)
# Check if son-movie is the corresponding episode
if ( cleanFilename.lower().startswith((name.lower()+"{:0d}{:02d}").format(int(season), int(episode))) or
cleanFilename.lower().startswith((name.lower()+"s{:02d}e{:02d}").format(int(season), int(episode))) ):
destFileName = cleanParentFolder+fileExt
if Debug > 1:
local.output+='Son has the same!!\nMoving to: ' + os.path.join(os.path.basename(grandParentFolder), destFileName) + '\n'