This repository has been archived by the owner on Jan 10, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
subget.py
executable file
·2241 lines (1680 loc) · 85.2 KB
/
subget.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 -*-
import getopt
import sys
import os
import glob
import time
import gettext
import locale
import xml.dom.minidom
import traceback
import shutil
from threading import Thread
winSubget = ""
if os.name == "nt":
winSubget = str(os.path.dirname(sys.path[0]+"/")).replace("subget.exe", "")
#winSTDOUT = open(winSubget+"/stdout.log", "w")
#winSTDERR = open(winSubget+"/stderr.log", "w")
#sys.stdout = winSTDOUT
#sys.stderr = winSTDERR
# windows native appearance
os.environ['PATH'] += ";gtk/lib;gtk/bin"
os.environ['GTK_PATH'] = winSubget+"/windows/runtime/lib/gtk-2.0"
os.environ['GTK2_RC_FILES'] = winSubget+"/windows/runtime/share/themes/MS-Windows/gtk-2.0/gtkrc"
try:
import subgetcore # libraries
from pango import FontDescription
import gtk, gobject
if os.name != "nt":
gtk.gdk.threads_init()
except Exception as e:
pass # load in shell mode only
# this will be used for Unix specific code
if os.name != "nt":
from distutils.sysconfig import get_python_lib
# detect Python version, maybe in future we will support Python 3
if sys.version_info[0] >= 3:
import configparser
import io as StringIO
else:
import StringIO
import ConfigParser as configparser
consoleMode=False
action="list"
class SubGet:
dialog=None
subtitlesList=list()
Config = dict()
Windows = dict() # active or non-active windows
Windows['preferences'] = False
plugins=dict()
pluginsList=list() # ordered list
queueCount = 0
locks = dict()
locks['reorder'] = False
disabledPlugins = list()
versioning = None
Hooking = None
finishedJobs = list()
gtkSettings = None
action = "list"
prefLang = "en"
def __init__(self):
# initialize hooking and logging
self.Hooking = subgetcore.Hooking()
self.Logging = subgetcore.Logging(self)
def getFile(self, kwargs, x=''):
""" Usage: /usr/bin/subget /usr/local/bin/subget - it will find first working path and return it """
for key in kwargs:
if os.path.isfile(key):
return key
return False
def getPath(self, path):
userPath = os.path.expanduser("~")+str(path)
if os.path.exists(userPath):
return userPath
else:
return self.subgetOSPath+str(path)
def doPluginsLoad(self, args):
global plugins
debugErrors = ""
# Windows NT
if os.name == "nt":
pluginsDir = self.subgetOSPath+"/subgetlib/"
sys.path.insert( 0, pluginsDir )
else: # Linux, FreeBSD and other Unix systems
pluginsDir = get_python_lib()+"/subgetlib/"
# fix for python bug which returns invalid path
if not os.path.isdir(pluginsDir):
pluginsDir = pluginsDir.replace("/usr/lib/", "/usr/local/lib/")
# list of disabled plugins
pluginsDisabled = self.configGetKey('plugins', 'disabled')
if pluginsDisabled:
self.disabledPlugins = pluginsDisabled.split(",")
file_list = glob.glob(pluginsDir+"*.py")
for Plugin in file_list:
Plugin = os.path.basename(Plugin)[:-3] # cut directory and .py
# skip the index
if Plugin == "__init__":
continue
try:
self.disabledPlugins.index(Plugin)
self.plugins[Plugin] = 'Disabled'
self.Logging.output("Disabling "+Plugin, "debug", False)
continue
except ValueError:
self.togglePlugin(False, Plugin, 'activate')
# plugin execution order
if "plugins" in self.Config:
if "order" in self.Config['plugins']:
order = self.Config['plugins']['order'].split(",")
for Item in order:
if Item in self.plugins:
# Python 2.6 compatibility
self.pluginsList.append(Item)
else:
self.reorderPlugins()
else:
self.reorderPlugins()
# add missing plugins
[self.pluginsList.append(k) for k in self.plugins if k not in self.pluginsList]
def reorderPlugins(self):
""" If plugins order is empty, try to create alphabetical order """
self.pluginsList = sorted(self.plugins)
# close the window and quit
def delete_event(self, widget, event, data=None):
gtk.main_quit()
return False
def sendCriticAlert(self, Message):
""" Send critical error message before exiting when in X11 session """
if os.path.isfile("/usr/bin/kdialog"):
os.system("/usr/bin/kdialog --error \""+Message+"\"")
elif os.path.isfile("/usr/bin/zenity"):
os.system("/usr/bin/zenity --info --text=\""+Message+"\"")
elif os.path.isfile("/usr/bin/xmessage"):
os.system("/usr/bin/xmessage -nearmouse \""+Message+"\"")
else:
print(Message)
def loadConfig(self):
""" Parsing configuration from ~/.subget/config """
if not os.path.isdir(os.path.expanduser("~/.subget/")):
try:
os.mkdir(os.path.expanduser("~/.subget/"))
except Exception:
print("Cannot create ~/.subget directory, please check your permissions")
configPath = os.path.expanduser("~/.subget/config")
if not os.path.isfile(configPath):
shutil.copyfile(self.subgetOSPath+"/usr/share/subget/config", configPath)
if os.path.isfile(configPath):
Parser = configparser.ConfigParser()
try:
Parser.read(configPath)
except Exception as e:
self.Logging.output("Error parsing configuration file from "+configPath+", error: "+str(e), "critical", True)
self.sendCriticAlert("Subget: Error parsing configuration file from "+configPath+", error: "+str(e))
sys.exit(os.EX_CONFIG)
# all configuration sections
Sections = Parser.sections()
for Section in Sections:
Options = Parser.options(Section)
self.Config[Section] = dict()
# and configuration variables inside of sections
for Option in Options:
self.Config[Section][Option] = Parser.get(Section, Option)
####################################
##### GNU Gettext translations #####
####################################
def translateString(self, string):
self.gettext(string).decode("utf-8")
def loadgettext(self):
if os.name == "nt":
incpath=winSubget+"/usr/share/subget/locale/"
elif os.path.isdir("usr/share/subget/locale/"):
incpath="usr/share/subget/locale/";
else:
incpath="/usr/share/subget/locale/";
langs = ['en_US', 'pl_PL', 'da_DK']
lc, encoding = locale.getdefaultlocale()
# handle "C" language as English United States
if lc == "C":
lc = "en_US"
if (lc):
langs = [lc]
else:
langs = ['en_US']
lc = "en_US"
print("Subget is loading in \""+lc+"\" language.")
#print("Translations: "+incpath)
gettext.bindtextdomain('subget', incpath)
t = gettext.translation('subget', incpath, langs, fallback=True)
self.translateString = t.gettext
###########################################
##### End of GNU Gettext translations #####
###########################################
def usage(self):
'Shows program usage and version, lists all options'
print(self._("subget for GNU/Linux. Simple Subtitle Downloader for shell and GUI.\nUsage: subget [long GNU option] [option] first-file, second-file, ...\n\n\n --help : this message\n --console, -c : show results in console, not in graphical user interface\n --language, -l : specify preffered language\n --quick, -q : grab first result and download\n --watch-with-subtitles, -w : don't run main window, just run player directly after successful subtitles download"))
print("")
def listLanguages(self):
""" List all supported languages """
images = os.listdir(self.subgetOSPath+"/usr/share/subget/icons/flags")
imagesStr = ""
for image in images:
if not ".xpm" in image or image == "unknown.xpm":
continue
imagesStr += image.replace(".xpm", "")+", "
print("Avaliable languages:")
print(" "+imagesStr[:-2])
def main(self):
""" Main function, getopt etc. """
global consoleMode, action, _
self.loadgettext()
self._ = self.translateString
if os.name == "nt":
self.subgetOSPath = winSubget+"/"
elif os.path.exists("usr/share/subget"):
self.Logging.output("Developer mode", "", False)
self.subgetOSPath = "."
else:
self.subgetOSPath = ""
try:
opts, args = getopt.getopt(sys.argv[1:], "hcqwl:", ["help", "console", "quick", "language=", "watch-with-subtitles", "list-languages"])
except getopt.GetoptError as err:
print(self._('Error')+": "+str(err)+", "+self._("Try --help for usage")+"\n\n")
self.usage()
sys.exit(2)
# replace with argparse/optparse
for o, a in opts:
if o in ('-h', '--help'):
self.usage()
exit(2)
if o in ('-c', '--console'):
consoleMode=True
if o in ('-q', '--quick'):
self.action="first-result"
if o in ('-w', '--watch-with-subtitles'):
self.action="watch"
consoleMode=True
if o in '--list-languages':
self.listLanguages()
sys.exit(0)
if o in ('-l', '--language'):
if os.path.isfile(self.subgetOSPath+"/usr/share/subget/icons/flags/"+a+".xpm"):
self.prefLang = a
else:
print("Undefined language type \""+a+"\", using default \"en\"")
self.loadConfig()
try:
level = int(self.configGetKey("logging", "level"))
self.Logging.loggingLevel = level
except Exception:
self.Logging.loggingLevel = 1
self.Logging.output("Logging level: "+str(self.Logging.loggingLevel), "debug", False)
self.Logging.output("Loading plugins...", "debug", False)
self.doPluginsLoad(args)
cwd = os.getcwd()
if cwd[:-1] != "/":
cwd += "/"
newarg = list()
for arg in args:
if os.path.isfile(cwd+arg):
newarg.append(cwd+arg)
else:
newarg.append(arg)
self.Hooking.executeHooks(self.Hooking.getAllHooks("onInstanceCheck"), [consoleMode, args, action])
try:
gtk
except NameError:
self.Logging.output("Cannot access GTK+, subget will run in shell mode only", "debug", False)
consoleMode = True
# Watch with subtitles
if self.action == "watch":
self.watchWithSubtitles(args)
return True
# shell interface
if consoleMode:
self.shellMode(args)
return True
# full featured GTK interface
self.graphicalMode(args)
########################################################
##### FAST DOWNLOAD, "WATCH WITH SUBTITLES" OPTION #####
########################################################
def textmodeDL(self, Plugin, File):
State = self.plugins[Plugin]
if type(State).__name__ != "module":
self.queueCount = (self.queueCount - 1)
return False
if self.plugins[Plugin].PluginInfo['API'] == 1:
Results = self.plugins[Plugin].download_list(File)
elif self.plugins[Plugin].PluginInfo['API'] == 2:
Results = self.plugins[Plugin].instance.download_list(File).output()
for Result in Results:
if not Result:
self.queueCount = (self.queueCount - 1)
return False
for Sub in Result:
try:
if Sub == "errInfo":
continue
self.subtitlesList.append({'language': Sub['lang'], 'name': Sub['title'], 'data': Sub['data'], 'extension': Plugin, 'file': Sub['file']})
except Exception as e:
self.Logging.output("[textModeDL] "+self._("Error trying to get list of subtitles from")+" "+Plugin+", "+str(e))
self.queueCount = (self.queueCount - 1)
def textmodeWait(self):
""" Wait util jobs not done, after that sort all results and download subtitles """
self.workingState(True)
Sleept = 0.0
while True:
time.sleep(0.2)
Sleept += 0.2
if self.queueCount <= 0:
break
if Sleept in [30.0, 60.0, 90.0, 120.0]:
self.Logging.output("[textModeWait] "+str(Sleept)+"s sleep", "debug", False)
# if waited too many time
if Sleept > 180:
self.Logging.output("[textmodeWait] "+self._("One of plugins cannot finish its job, cancelling."), "warning")
self.workingState(False)
return False
self.reorderTreeview(False) # Reorder list without using GTK
self.finishedJobs = dict()
prefferedLanguage = self.configGetKey('watch_with_subtitles', 'preferred_language')
# set default language to english
if not prefferedLanguage:
prefferedLanguage = 'en'
# search for matching subtitles
for Job in self.subtitlesList:
if not Job['data']['file'] in self.finishedJobs:
if Job['language'].lower() == prefferedLanguage.lower():
self.finishedJobs[Job['data']['file']] = Job
current = Thread(target=self.textmodeDLSub, args=(Job,))
current.setDaemon(False)
current.start()
# accept other langages than preffered
if not self.configGetKey('watch_with_subtitles', 'only_preferred_language') == "True":
for Job in self.subtitlesList:
if not Job['data']['file'] in self.finishedJobs:
self.finishedJobs[Job['data']['file']] = Job
current = Thread(target=self.textmodeDLSub, args=(Job,))
current.setDaemon(False)
current.start()
self.workingState(False)
def textmodeDLSub(self, Job):
self.Logging.output("[textmodeWait] " + self._("Downloading to") + " "+Job['data']['file']+".txt")
Result = self.plugins[Job['extension']].instance.download_by_data(Job['data'], Job['data']['file']+".txt")
return Result
def watchWithSubtitles(self, args):
""" Download first matching subtitles and launch video player.
Always returns True
"""
if not args:
self.Logging.output(self._("No files specified in watch with subtitles."), "", False)
self.sendCriticAlert(self._("No files specified in watch with subtitles."))
sys.exit(1)
# subtitlesList
self.queueCount = 0
# Upgraded to API v2
for plugin in self.plugins:
if self.isPlugin(plugin):
self.queueCount += 1
for Plugin in self.pluginsList:
if not self.isPlugin(Plugin):
continue
current = Thread(target=self.textmodeDL, args=(Plugin,args))
current.setDaemon(False)
current.start()
# Loop waiting for download to be done
current = Thread(target=self.textmodeWait)
current.setDaemon(False)
current.start()
# wait for threads to end jobs
current.join()
if len(args) == 1:
# get the first job using "for" and "break" after first result
if not self.configGetKey('watch_with_subtitles', 'download_only'):
Found = False
for File in self.finishedJobs:
Found = True
break
if not Found:
self.Logging.output(self._("No subtitles found for file") + " "+args[0], "warning")
self.sendCriticAlert(self._("No subtitles found for file") + " "+args[0])
try:
self.Hooking.executeHooks(self.Hooking.getAllHooks("onSubtitlesDownload"), [False, False, False, False])
except Exception as e:
self.Logging.output(self._("Error")+": "+self._("Cannot execute hook")+"; onSubtitlesDownload; "+str(e), "warning", True)
else:
try:
self.Hooking.executeHooks(self.Hooking.getAllHooks("onSubtitlesDownload"), [self.configGetKey('watch_with_subtitles', 'download_only'), File+".txt", File, True])
except Exception as e:
self.Logging.output(self._("Error")+": "+self._("Cannot execute hook")+"; onSubtitlesDownload; "+str(e), "warning", True)
else:
try:
self.Hooking.executeHooks(self.Hooking.getAllHooks("onSubtitlesDownload"), [False, False, False, True])
except Exception as e:
self.Logging.output(self._("Error")+": "+self._("Cannot execute hook")+"; onSubtitlesDownload; "+str(e), "warning", True)
return True
#################################################
##### END OF "WATCH WITH SUBTITLES" OPTION #####
#################################################
def addSubtitlesRow(self, language, release_name, server, download_data, extension, File,Append=True):
""" Adds parsed subtitles to list """
self.subtitlesList.append({'language': language, 'name': release_name, 'server': server, 'data': download_data, 'extension': extension, 'file': File})
if str(self.configGetKey('interface', 'preferred_language')) != "False" and str(self.configGetKey('interface', 'only_prefered')) != "False":
if language != self.configGetKey('interface', 'preferred_language'):
self.Logging.output("Skipping "+language+" language subtitles \""+release_name+"\"", "debug", False)
return False
pixbuf_path = self.getPath('/usr/share/subget/icons/flags/'+language+'.xpm')
if not os.path.isfile(pixbuf_path):
pixbuf_path = self.getPath('/usr/share/subget/icons/flags/unknown.xpm')
self.Logging.output(language+".xpm "+self._("icon does not exists, using unknown.xpm"), "warning", False)
try:
pixbuf = gtk.gdk.pixbuf_new_from_file(pixbuf_path)
except Exception:
self.Logging.output(pixbuf_path+" "+self._("icon file not found"), "warning", True)
return False
self.liststore.append([pixbuf, str(release_name), str(server), (len(self.subtitlesList)-1)])
def reorderTreeview(self, useGTK=True):
""" Sorting subtitles list by plugin priority """
if self.locks['reorder']:
return False
self.locks['reorder'] = True
self.workingState(True)
if "plugins" in self.Config:
if not self.dictGetKey(self.Config['plugins'], 'list_ordering'):
self.Logging.output(self._("Sorting disabled."), "debug", True)
return True
while not self.queueCount == 0:
time.sleep(0.2) # give some time to finish the jobs
#print("SLEEPING 200ms sec, becasue count is "+str(self.queueCount))
if self.queueCount == 0:
break
#print("QUEUE COUNT: "+str(self.queueCount))
if self.queueCount == 0:
self.workingState(False)
newList = list()
for Item in self.subtitlesList:
Item['priority'] = self.pluginsList.index(str(Item['extension']))
newList.append(Item)
sortedList = sorted(newList, key=lambda k: k['priority'])
self.subtitlesList = list()
if useGTK:
self.liststore.clear()
for Item in sortedList:
self.addSubtitlesRow(Item['language'], Item['name'], Item['server'], Item['data'], Item['extension'], Item['file'])
else:
for Item in sortedList:
self.subtitlesList.append({'language': Item['language'], 'name': Item['name'], 'server': Item['extension'], 'data': Item['data'], 'extension': Item['extension'], 'file': Item['file']})
self.locks['reorder'] = False
def GTKCheckForSubtitles(self, Plugin):
State = self.plugins[Plugin]
if type(State).__name__ != "module":
self.queueCount = (self.queueCount - 1)
return
if self.plugins[Plugin].PluginInfo['API'] == 1:
Results = self.plugins[Plugin].download_list(self.files)
elif self.plugins[Plugin].PluginInfo['API'] == 2:
Results = self.plugins[Plugin].instance.download_list(self.files).output()
if Results is None:
stack = StringIO.StringIO()
traceback.print_exc(file=stack)
self.Logging.output("[plugin:"+Plugin+"] "+self._("ERROR: Cannot import")+"\n"+str(stack.getvalue()), "warning", True)
else:
for Result in Results:
if not Result:
self.queueCount = (self.queueCount - 1)
return False
for Movie in Result:
try:
if not type(Movie).__name__ == "dict":
self.Logging.output("[plugin:"+Plugin+"] Error: got "+str(type(Movie).__name__)+", not a dictionary. Data="+str(Movie), "debug", True)
continue
if not "title" in Movie:
self.Logging.output("[plugin:"+Plugin+"] Error: no title found in results", "debug", True)
continue
self.addSubtitlesRow(Movie['lang'], Movie['title'], Movie['domain'], Movie['data'], Plugin, Movie['file'])
self.Logging.output("[plugin:"+Plugin+"] "+self._("found subtitles")+" - "+Movie['title'], "debug", True)
except AttributeError as e:
self.Logging.output("[plugin:"+Plugin+"] "+self._("no any subtitles found")+", "+str(e), "debug", True)
# mark job as done
self.queueCount = (self.queueCount - 1)
def dictGetKey(self, Array, Key):
""" Return key from dictionary, if not exists returns false """
if Key in Array:
if Array[Key] == "False":
return False
return Array[Key]
else:
return False
# displaying the flag
def cell_pixbuf_func(self, celllayout, cell, model, iter):
""" Flag rendering """
cell.set_property('pixbuf', model.get_value(iter, 0))
def gtkDebugDialog(self,message):
self.dialog = gtk.MessageDialog(parent = None,flags = gtk.DIALOG_DESTROY_WITH_PARENT,type = gtk.MESSAGE_INFO,buttons = gtk.BUTTONS_OK,message_format = message)
self.dialog.set_title("Debug informations")
self.dialog.connect('response', lambda dialog, response: self.destroyDialog())
self.dialog.show()
# DOWNLOAD DIALOG
def GTKDownloadSubtitles(self, a='', b=''):
""" Dialog with file name chooser to save subtitles to """
entry1,entry2 = self.treeview.get_selection().get_selected()
if entry2 is None:
if self.dialog is not None:
return
else:
self.dialog = gtk.MessageDialog(parent = None,flags = gtk.DIALOG_DESTROY_WITH_PARENT,type = gtk.MESSAGE_INFO,buttons = gtk.BUTTONS_OK,message_format = self._("No subtitles selected."))
self.dialog.set_title(self._("Information"))
self.dialog.connect('response', lambda dialog, response: self.destroyDialog())
self.dialog.show()
else:
SelectID = int(entry1.get_value(entry2, 3))
if len(self.subtitlesList) == int(SelectID) or len(self.subtitlesList) > int(SelectID):
chooser = gtk.FileChooserDialog(title=self._("Where to save the subtitles?"),action=gtk.FILE_CHOOSER_ACTION_SAVE,buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_SAVE,gtk.RESPONSE_OK))
chooser.set_current_folder(os.path.dirname(self.subtitlesList[SelectID]['file']))
txtFileName = self.subtitlesList[SelectID]['file']
if not ".txt" in txtFileName:
txtFileName = txtFileName+".txt"
chooser.set_current_name(os.path.basename(txtFileName))
response = chooser.run()
if response == gtk.RESPONSE_OK:
fileName = chooser.get_filename()
chooser.destroy()
self.GTKDownloadDialog(SelectID, fileName)
else:
chooser.destroy()
else:
self.Logging.output("[GTK:DownloadSubtitles] subtitle_ID="+str(SelectID)+" "+self._("not found in a list, its wired"), "warning", True)
def GTKDownloadDialog(self, SelectID, filename):
"""Download progress dialog, downloading and saving subtitles to file"""
Plugin = self.subtitlesList[SelectID]['extension']
State = self.plugins[Plugin]
if type(State).__name__ == "module":
w = gtk.Window(gtk.WINDOW_TOPLEVEL)
w.set_position(gtk.WIN_POS_CENTER)
w.set_resizable(False)
w.set_title(self._("Download subtitles"))
w.set_border_width(0)
w.set_size_request(300, 70)
fixed = gtk.Fixed()
# progress bar
self.pbar = gtk.ProgressBar()
self.pbar.set_size_request(180, 15)
self.pbar.set_pulse_step(0.01)
self.pbar.pulse()
w.timeout_handler_id = gtk.timeout_add(20, self.update_progress_bar)
self.pbar.show()
# label
label = gtk.Label(self._("Please wait, downloading subtitles..."))
fixed.put(label, 50,5)
fixed.put(self.pbar, 50,30)
w.add(fixed)
w.show_all()
if self.plugins[Plugin].PluginInfo['API'] == 1:
Results = self.plugins[Plugin].download_by_data(self.subtitlesList[SelectID]['data'], filename)
elif self.plugins[Plugin].PluginInfo['API'] == 2:
Results = self.plugins[Plugin].instance.download_by_data(self.subtitlesList[SelectID]['data'], filename)
if Results:
try:
self.Hooking.executeHooks(self.Hooking.getAllHooks("onSubtitlesDownload"), [False, Results, self.dictGetKey(self.subtitlesList[SelectID]['data'], 'file'), True])
except Exception as e:
self.Logging.output(self._("Error")+": "+self._("Cannot execute hook")+"; onSubtitlesDownload; "+str(e), "warning", True)
traceback.print_exc(file=sys.stdout)
else:
try:
self.Hooking.executeHooks(self.Hooking.getAllHooks("onSubtitlesDownload"), [False, False, False, False])
except Exception as e:
self.Logging.output(self._("Error")+": "+self._("Cannot execute hook")+"; onSubtitlesDownload; "+str(e), "warning", True)
w.destroy()
def update_progress_bar(self):
""" Progressbar updater, called asynchronously """
self.pbar.pulse()
return True
# DESTROY THE DIALOG
def destroyDialog(self):
""" Destroys all dialogs and popups """
self.dialog.destroy()
self.dialog = None
def gtkSelectVideo(self, arg):
""" Selecting multiple videos to search for subtitles """
chooser = gtk.FileChooserDialog(title=self._("Please select video files"),action=gtk.FILE_CHOOSER_ACTION_OPEN,buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK))
chooser.set_select_multiple(True)
response = chooser.run()
if response == gtk.RESPONSE_OK:
fileNames = chooser.get_filenames()
chooser.destroy()
for fileName in fileNames:
if not os.path.isfile(fileName) or not os.access(fileName, os.R_OK):
continue
self.files = [fileName, ]
#self.files = {fileName} # works on Python 2.7 only
#print self.files
self.TreeViewUpdate()
else:
chooser.destroy()
return True
def togglePlugin(self, x, Plugin, Action, liststore=None):
if Action == 'activate':
self.Logging.output("Activating "+Plugin, "debug", False)
# load the plugin
try:
exec("import subgetlib."+Plugin)
exec("self.plugins[Plugin] = subgetlib."+Plugin)
# old API v1
if self.plugins[Plugin].PluginInfo['API'] == 1:
self.plugins[Plugin].loadSubgetObject(self)
self.plugins[Plugin].subgetcore = subgetcore
# compability with new API v2
elif self.plugins[Plugin].PluginInfo['API'] == 2:
exec("self.plugins[Plugin] = subgetlib."+Plugin+"")
exec("self.plugins[Plugin].instance = subgetlib."+Plugin+".PluginMain(self)")
if "_pluginInit" in dir(self.plugins[Plugin].instance):
self.plugins[Plugin].instance._pluginInit()
if not "type" in self.plugins[Plugin].PluginInfo:
self.plugins[Plugin].PluginInfo['type'] = 'normal'
# refresh the list
if liststore is not None:
liststore.clear()
self.pluginsListing(liststore)
return True
except Exception as errno:
stack = StringIO.StringIO()
traceback.print_exc(file=stack)
self.plugins[Plugin] = str(errno)
self.Logging.output(self._("ERROR: Cannot import")+" "+Plugin+" ("+str(errno)+")\n"+str(stack.getvalue()), "warning", True)
return False
elif Action == 'deactivate':
self.Logging.output("Deactivating "+Plugin, "debug", False)
if self.plugins[Plugin] == 'disabled':
return True
try:
self.plugins[Plugin].instance._pluginDestroy()
del self.plugins[Plugin].instance
except Exception:
pass
self.plugins[Plugin] = 'Disabled'
# refresh the list
if liststore is not None:
liststore.clear()
self.pluginsListing(liststore)
return True
def pluginInfo(self, x, Plugin):
print("Feature not implemented.")
def osName(self):
if os.name == "nt":
return "Windows"
elif sys.platform[0:5] == "linux":
return "Linux"
elif sys.platform[0:7] == "freebsd":
return "FreeBSD"
else:
return "Unknown operating system"
def pluginTreeviewEvent(self, treeview, event, liststore):
if event.button == 3 or event.type == gtk.gdk._2BUTTON_PRESS:
x = int(event.x)
y = int(event.y)
time = event.time
pthinfo = treeview.get_path_at_pos(x, y)
if pthinfo is not None:
path, col, cellx, celly = pthinfo
treeview.grab_focus()
treeview.set_cursor( path, col, 0)
# items
Info = None
Plugin = liststore[pthinfo[0][0]][1]
if event.button == 3:
if event.type == gtk.gdk.BUTTON_PRESS:
menu = gtk.Menu()
if self.plugins[Plugin] == 'Disabled':
Deactivate = gtk.MenuItem(self._("Activate plugin"))
Deactivate.connect("activate", self.togglePlugin, Plugin, 'activate', liststore)
else:
Deactivate = gtk.MenuItem(self._("Deactivate plugin"))
Deactivate.connect("activate", self.togglePlugin, Plugin, 'deactivate', liststore)
if self.plugins[Plugin].PluginInfo['API'] > 1:
customMenu = self.plugins[Plugin].instance.customPluginContextMenu()
for option in customMenu:
try:
customItem = gtk.MenuItem(str(option[0]))
customItem.connect("activate", option[1], option[2])
menu.append(customItem)
except Exception as e:
self.Logging.output(self._("Cannot add custom menu")+". "+self._("plugin")+": "+Plugin+", "+self._("exception")+": "+str(e))
menu.append(Deactivate)
menu.show_all()
menu.popup( None, None, None, event.button, time)
elif event.type == gtk.gdk._2BUTTON_PRESS:
if self.plugins[Plugin] == 'Disabled':
self.togglePlugin(False, Plugin, "activate", liststore)
else:
self.togglePlugin(False, Plugin, "deactivate", liststore)
def pluginsListing(self, liststore):
for Plugin in self.pluginsList:
try:
API = self.plugins[Plugin].PluginInfo['API']
except Exception:
API = "?"
try:
Author = self.plugins[Plugin].PluginInfo['Authors']
except Exception:
Author = self._("Unknown")
try:
OS = self.plugins[Plugin].PluginInfo['Requirements']['OS']
if OS == "All":
OS = "Unix, Linux, Windows"
except Exception:
OS = self._("Unknown")
try:
Description = self.plugins[Plugin].PluginInfo['Description']
except Exception:
Description = ""
try:
Packages = self.plugins[Plugin].PluginInfo['Requirements']['Packages']
except Exception:
Packages = self._("Unknown")
if self.plugins[Plugin] == "Disabled":
pixbuf = gtk.gdk.pixbuf_new_from_file(self.subgetOSPath+'/usr/share/subget/icons/plugin-disabled.png')
liststore.append([pixbuf, Plugin, Description, OS, str(Author), str(API)])
continue
if not "PluginInfo" in dir(self.plugins[Plugin]):
pixbuf = gtk.gdk.pixbuf_new_from_file(self.subgetOSPath+'/usr/share/subget/icons/error.png')
liststore.append([pixbuf, Plugin, Description, OS, str(Author), str(API)])
continue
if self.plugins[Plugin].PluginInfo['type'] == 'extension':
pixbuf = gtk.gdk.pixbuf_new_from_file(self.subgetOSPath+'/usr/share/subget/icons/extension.png')
liststore.append([pixbuf, Plugin, Description, OS, str(Author), str(API)])
continue
if type(self.plugins[Plugin]).__name__ == "module":
pixbuf = gtk.gdk.pixbuf_new_from_file(self.subgetOSPath+'/usr/share/subget/icons/plugin.png')
liststore.append([pixbuf, Plugin, Description, OS, str(Author), str(API)])
else:
pixbuf = gtk.gdk.pixbuf_new_from_file(self.subgetOSPath+'/usr/share/subget/icons/error.png')
liststore.append([pixbuf, Plugin, Description, OS, str(Author), str(API)])
def gtkPluginMenu(self, arg):
""" GTK Widget with list of plugins """
if not self.dictGetKey(self.Windows, 'gtkPluginMenu'):
self.Windows['gtkPluginMenu'] = True
else:
return False
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_position(gtk.WIN_POS_CENTER)
window.set_title(self._("Plugins"))
window.set_resizable(True)
window.set_size_request(700, 350)
window.set_icon_from_file(self.subgetOSPath+"/usr/share/subget/icons/plugin.png")
window.connect("delete_event", self.closeWindow, window, 'gtkPluginMenu')
liststore = gtk.ListStore(gtk.gdk.Pixbuf, str, str, str, str, str)
treeview = gtk.TreeView(liststore)
# column list
tvcolumn = gtk.TreeViewColumn(self._("Plugin"))
descColumn = gtk.TreeViewColumn(self._("Description"))
tvcolumn1 = gtk.TreeViewColumn(self._("Operating system"))
tvcolumn2 = gtk.TreeViewColumn(self._("Authors"))
tvcolumn3 = gtk.TreeViewColumn(self._("API interface version"))
treeview.append_column(tvcolumn)
treeview.append_column(tvcolumn1)
treeview.append_column(descColumn)
treeview.append_column(tvcolumn2)
treeview.append_column(tvcolumn3)