forked from Tribler/tribler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlist_details.py
2458 lines (1981 loc) · 96.9 KB
/
list_details.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
# Written by Niels Zeilemaker, Egbert Bouman
import os
import sys
import re
from time import time
import logging
import copy
import wx
from StringIO import StringIO
from Tribler.Core.osutils import startfile
from Tribler.Core.simpledefs import (DLSTATUS_ALLOCATING_DISKSPACE, DLSTATUS_WAITING4HASHCHECK, DLSTATUS_HASHCHECKING,
DLSTATUS_DOWNLOADING, DLSTATUS_SEEDING, DLSTATUS_STOPPED,
DLSTATUS_STOPPED_ON_ERROR, DLSTATUS_METADATA, UPLOAD, DOWNLOAD, NTFY_TORRENTS,
NTFY_VIDEO_ENDED, DLMODE_VOD)
from Tribler.Core.CacheDB.sqlitecachedb import forceDBThread
from Tribler.Core.Video.utils import videoextdefaults
from Tribler.Core.Video.VideoUtility import limit_resolution
from Tribler.community.channel.community import ChannelCommunity
from Tribler.Main.Utility.GuiDBTuples import Torrent, ChannelTorrent, CollectedTorrent, Channel, Playlist
from Tribler.Main.Utility.GuiDBHandler import GUI_PRI_DISPERSY, startWorker
from Tribler.Main.vwxGUI import (warnWxThread, forceWxThread, GRADIENT_LGREY, GRADIENT_DGREY,
DEFAULT_BACKGROUND, FILTER_GREY, SEPARATOR_GREY,
DOWNLOADING_COLOUR, SEEDING_COLOUR, TRIBLER_RED, LIST_LIGHTBLUE, format_time)
from Tribler.Main.vwxGUI.GuiUtility import GUIUtility
from Tribler.Main.vwxGUI.GuiImageManager import GuiImageManager
from Tribler.Main.vwxGUI.widgets import (LinkStaticText, EditText, SelectableListCtrl, _set_font,
BetterText as StaticText, MaxBetterText, NotebookPanel, SimpleNotebook,
ProgressButton, FancyPanel, TransparentText, LinkText, StaticBitmaps,
TransparentStaticBitmap, Graph, ProgressBar)
from Tribler.Main.Utility.utility import eta_value, size_format, speed_format
from Tribler.community.tunnel import CIRCUIT_ID_PORT, CIRCUIT_TYPE_RENDEZVOUS, CIRCUIT_TYPE_RP
class AbstractDetails(FancyPanel):
@warnWxThread
def _create_tab(self, notebook, tabname, header=None, spacer=0, border=0):
panel = wx.lib.scrolledpanel.ScrolledPanel(notebook)
def OnChange():
panel.Layout()
panel.SetupScrolling(rate_y=5, scroll_x=False)
panel.OnChange = OnChange
themeColour = notebook.GetThemeBackgroundColour()
if themeColour.IsOk():
panel.SetBackgroundColour(themeColour)
notebook.AddPage(panel, tabname)
vSizer = wx.BoxSizer(wx.VERTICAL)
panel.SetSizer(vSizer)
if border:
vSizer2 = wx.BoxSizer(wx.VERTICAL)
vSizer.Add(vSizer2, 1, wx.EXPAND | wx.ALL, border)
vSizer = vSizer2
if header:
header = self._add_header(panel, vSizer, header, spacer)
panel.SetLabel = header.SetLabel
return panel, vSizer
@warnWxThread
def _add_header(self, panel, sizer, header, spacer=0):
header = wx.StaticText(panel, -1, header)
_set_font(header, fontweight=wx.FONTWEIGHT_BOLD)
sizer.Add(header, 0, wx.LEFT | wx.BOTTOM, spacer)
return header
@warnWxThread
def _add_row(self, parent, sizer, name, value, spacer=0, flags=wx.EXPAND):
nametext = name
if name is not None:
nametext = wx.StaticText(parent, -1, name)
_set_font(nametext, fontweight=wx.FONTWEIGHT_BOLD)
sizer.Add(nametext, 0, wx.LEFT, spacer)
if value is not None:
if isinstance(value, basestring):
try:
value = MaxBetterText(parent, unicode(value), maxLines=3, name=name)
except:
value = MaxBetterText(parent, value.decode('utf-8', 'ignore'), maxLines=3, name=name)
value.SetMinSize((1, -1))
sizer.Add(value, 0, flags | wx.LEFT, spacer)
return nametext, value
@warnWxThread
def _add_subheader(self, parent, sizer, title, subtitle):
title = wx.StaticText(parent, -1, title)
_set_font(title, fontweight=wx.FONTWEIGHT_BOLD)
vSizer = wx.BoxSizer(wx.VERTICAL)
vSizer.Add(title)
vSizer.Add(wx.StaticText(parent, -1, subtitle))
sizer.Add(vSizer)
return vSizer
class TorrentDetails(AbstractDetails):
FINISHED = 6
FINISHED_INACTIVE = 5
INCOMPLETE = 4
INCOMPLETE_INACTIVE = 3
VOD = 2
INACTIVE = 1
@warnWxThread
def __init__(self, parent):
self._logger = logging.getLogger(self.__class__.__name__)
FancyPanel.__init__(self, parent)
self.Hide()
self.guiutility = GUIUtility.getInstance()
self.utility = self.guiutility.utility
self.parent = parent
self.torrent = Torrent('0', '0', '', 0, 0, 0, 0, 0, None, False)
self.torrent.torrent_db = self.guiutility.channelsearch_manager.torrent_db
self.torrent.channelcast_db = self.guiutility.channelsearch_manager.channelcast_db
self.state = -1
self.timeouttimer = None
self.SetBackgroundColour(GRADIENT_LGREY, GRADIENT_DGREY)
self.vSizer = wx.BoxSizer(wx.VERTICAL)
self.notebook = SimpleNotebook(self, style=wx.NB_NOPAGETHEME, name="TorrentDetailsNotebook")
self.notebook.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnChange)
self.vSizer.Add(self.notebook, 1, wx.EXPAND)
self.SetSizer(self.vSizer)
self.Layout()
self.createMessagePanel()
self.notebook.SetMessagePanel(self.messagePanel)
self.doMark = self.guiutility.frame.selectedchannellist.OnMarkTorrent
self.doSave = self.guiutility.frame.selectedchannellist.OnSaveTorrent
self.canEdit = False
self.canComment = False
self.canMark = False
self.showInfohash = False
self.markWindow = None
self.markings = None
self.myMark = None
self.isEditable = {}
self.tracker_checks = {}
self.createAllTabs()
self.Show()
self.DownloadStarted = lambda: None
@forceWxThread
def setTorrent(self, torrent):
if torrent:
if self.timeouttimer:
self.timeouttimer.Stop()
self.timeouttimer = None
# Intermediate update
self.messageText.SetLabel(
'Loading details, please wait.\nTribler first needs to fetch the torrent file before this information can be accessed.')
self.messageGauge.Show(False)
self.messageButton.Show(False)
self.messagePanel.Layout()
self.torrent = torrent
self.showTorrent(self.torrent)
self.guiutility.library_manager.add_download_state_callback(self.OnRefresh)
if self.guiutility.utility.session.has_collected_torrent(self.torrent.infohash):
self.guiutility.torrentsearch_manager.loadTorrent(self.torrent, callback=self.showTorrent)
else:
def doGui(delayedResult):
requesttype = delayedResult.get()
if requesttype:
self.messageText.SetLabel(
'Loading details, please wait. The torrent file is requested %s.\nTribler first needs to fetch the torrent file before this information can be accessed.' % requesttype)
self.messageGauge.Show(True)
self.messageGauge.Pulse()
self.messagePanel.Layout()
self.timeouttimer = wx.CallLater(
10000, timeout) if not self.guiutility.frame.librarylist.IsShownOnScreen() else None
def timeout():
# Avoid WxPyDeadObject exception
if not self:
return
self.messageText.SetLabel(
"Failed loading torrent.\nPlease click retry or wait to allow other peers to respond.")
self.messageGauge.Show(False)
self.messageButton.Show(True)
self.messagePanel.Layout()
startWorker(doGui, self.guiutility.torrentsearch_manager.loadTorrent,
wargs=(self.torrent,), wkwargs={'callback': self.showTorrent})
@forceWxThread
def showTorrent(self, torrent, showTab=None):
if self.torrent.infohash != torrent.infohash:
return
if isinstance(torrent, CollectedTorrent):
self.guiutility.frame.top_bg.AddCollectedTorrent(torrent)
def update():
if not self:
return
page = self.guiutility.GetSelectedPage()
if page and hasattr(page, 'GetExpandedItems'):
for infohash, item in page.GetExpandedItems():
if infohash == torrent.infohash:
item.SetCollectedTorrent(torrent)
wx.CallLater(1, update)
self.state = -1
self.torrent = torrent
self.canEdit = False
self.canComment = False
self.canMark = False
isChannelTorrent = isinstance(self.torrent, ChannelTorrent) or (
isinstance(self.torrent, CollectedTorrent) and isinstance(self.torrent.torrent, ChannelTorrent))
if isChannelTorrent and self.torrent.hasChannel():
# This is a db call
channel_state = self.torrent.channel.getState()
if channel_state:
state, _ = channel_state
if isinstance(self, LibraryDetails):
self.canMark = state >= ChannelCommunity.CHANNEL_SEMI_OPEN
else:
self.canEdit = state >= ChannelCommunity.CHANNEL_OPEN
self.canComment = state >= ChannelCommunity.CHANNEL_SEMI_OPEN
self.updateAllTabs()
self._Refresh(self.torrent.ds)
def createMessagePanel(self):
# Create messagePanel
self.messagePanel = FancyPanel(self.notebook)
self.messagePanel.SetBackgroundColour(GRADIENT_LGREY, GRADIENT_DGREY)
self.messageIcon = TransparentStaticBitmap(self.messagePanel, -1, wx.ArtProvider.GetBitmap(wx.ART_INFORMATION))
self.messageText = TransparentText(
self.messagePanel, -1, "Loading details, please wait.\nTribler first needs to fetch the torrent file before this information can be accessed.")
self.messageGauge = wx.Gauge(self.messagePanel, -1, size=(100, 15))
self.messageButton = wx.Button(self.messagePanel, -1, "Retry")
self.messageButton.Bind(wx.EVT_BUTTON, lambda evt: self.setTorrent(self.torrent))
_set_font(self.messageText, size_increment=2, fontweight=wx.FONTWEIGHT_NORMAL)
vSizer = wx.BoxSizer(wx.VERTICAL)
vSizer.AddStretchSpacer()
hSizer = wx.BoxSizer(wx.HORIZONTAL)
hSizer.Add(self.messageIcon, 0, wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, 15)
hSizer.Add(self.messageText, 0, wx.ALL, 3)
vSizer.Add(hSizer, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL)
vSizer.Add(self.messageGauge, 0, wx.ALIGN_CENTER_HORIZONTAL | wx.TOP, 10)
vSizer.Add(self.messageButton, 0, wx.ALIGN_CENTER_HORIZONTAL | wx.TOP, 10)
vSizer.AddStretchSpacer()
self.messageGauge.Show(False)
self.messageButton.Show(False)
self.messagePanel.SetSizer(vSizer)
def createAllTabs(self):
self.Freeze()
self.createDetailsTab()
self.createFilesTab()
self.createEditTab()
self.createCommentsTab()
self.createModificationsTab()
self.createTrackersTab()
self.Thaw()
self.Layout()
showTab = getattr(self.parent, self.__class__.__name__ + '_tab', None) if self.parent else None
if showTab:
for i in range(self.notebook.GetPageCount()):
if self.notebook.GetPageText(i) == showTab:
self.notebook.SetSelection(i)
break
else:
self.notebook.SetSelection(0)
def createDetailsTab(self):
def OnToggleInfohash(event):
self.showInfohash = not self.showInfohash
self.updateDetailsTab()
self.detailsTab, self.detailsSizer = self._create_tab(self.notebook, 'Torrent details', border=10)
self.detailsTab.SetBackgroundColour(wx.WHITE)
self.detailsTab.Bind(wx.EVT_LEFT_DCLICK, OnToggleInfohash)
self.Freeze()
fgSizer = wx.FlexGridSizer(0, 2, 3, 10)
fgSizer.AddGrowableCol(1)
titles = ['Name', 'Description', 'Status', 'Type', 'Uploaded', 'Filesize', 'Health']
for title in titles:
control1, control2 = self._add_row(self.detailsTab, fgSizer, title, '')
setattr(self, title.lower() + '_title', control1)
setattr(self, title.lower(), control2)
# Add piece progress
class tmp_object():
def __init__(self, data, original_data):
self.data = data
self.original_data = original_data
self.item = tmp_object(['', [0, 0], [0, 0], 0, 0], self.torrent)
self.downloaded = ProgressPanel(self.detailsTab, self.item, show_bar=True, show_status=False)
self.downloaded.SetMinSize((-1, 25))
self.detailsSizer.Add(self.downloaded, 0, wx.EXPAND | wx.BOTTOM, 10)
# Add infohash
textCtrl = wx.TextCtrl(self.detailsTab, -1, '')
textCtrl.SetEditable(False)
self.infohash_title, self.infohash = self._add_row(self.detailsTab, fgSizer, "Infohash", textCtrl)
# Add associated channel
ulfont = self.GetFont()
ulfont.SetUnderlined(True)
link = LinkText(self.detailsTab, '', fonts=[
self.GetFont(), ulfont], colours=[self.GetForegroundColour(), wx.RED])
link.SetBackgroundColour(self.detailsTab.GetBackgroundColour())
link.Bind(wx.EVT_LEFT_UP, lambda evt: self.torrent.get('channel')
and self.guiutility.showChannel(self.torrent.channel))
self.channel_title, self.channel = self._add_row(self.detailsTab, fgSizer, 'Channel', link, flags=0)
# Add thumbnails
self.thumbnails = StaticBitmaps(self.detailsTab, -1)
self.thumbnails.SetBackgroundColour(self.detailsTab.GetBackgroundColour())
self.thumbnails.SetBitmaps([])
tSizer = wx.BoxSizer(wx.HORIZONTAL)
tSizer.Add(fgSizer, 1, wx.ALIGN_LEFT | wx.ALIGN_TOP | wx.EXPAND)
tSizer.Add(self.thumbnails, 0, wx.ALIGN_RIGHT | wx.ALIGN_TOP | wx.EXPAND)
self.detailsSizer.Add(tSizer, 1, wx.EXPAND)
self.thumbnails.Show(False)
self.no_thumb_bitmap = wx.StaticBitmap(self.detailsTab, -1)
bitmap = GuiImageManager.getInstance().drawBitmap("no-thumbnail",
(125, 100), self.no_thumb_bitmap.GetFont())
self.no_thumb_bitmap.SetBitmap(bitmap)
vsizer = wx.BoxSizer(wx.VERTICAL)
vsizer.Add(self.no_thumb_bitmap, 1, wx.EXPAND)
tSizer.Add(vsizer, 0, wx.EXPAND)
# Add 'Mark this torrent' option
self.marking_hSizer = wx.BoxSizer(wx.HORIZONTAL)
self.marking_vSizer = wx.BoxSizer(wx.VERTICAL)
self.marking_vSizer.Add(
wx.StaticLine(self.detailsTab, -1, style=wx.LI_HORIZONTAL), 0, wx.TOP | wx.BOTTOM | wx.EXPAND, 5)
self.marking_vSizer.Add(self.marking_hSizer, 1, wx.EXPAND)
self.markicon = GuiImageManager.getInstance().getBitmap(
self, u"arrow", self.GetBackgroundColour(), state=0).ConvertToImage().Rotate90(False).ConvertToBitmap()
self.markicon = wx.StaticBitmap(self.detailsTab, -1, self.markicon)
ulfont = self.GetFont()
ulfont.SetUnderlined(True)
self.marktoggle = LinkText(self.detailsTab, 'Mark this torrent', fonts=[
self.GetFont(), ulfont], colours=[self.GetForegroundColour(), wx.RED])
self.marktoggle.SetBackgroundColour(self.detailsTab.GetBackgroundColour())
self.marktoggle.Bind(wx.EVT_LEFT_UP, self.OnMark)
self.marking_hSizer.AddStretchSpacer()
self.marking_hSizer.Add(self.markicon, 0, wx.CENTER | wx.RIGHT, 3)
self.marking_hSizer.Add(self.marktoggle)
self.detailsSizer.Add(self.marking_vSizer, 0, wx.EXPAND)
self.marking_vSizer.ShowItems(False)
self.detailsTab.OnChange()
self.detailsTab.Layout()
self.Thaw()
def createFilesTab(self):
self.filesTab = wx.Panel(self.notebook)
self.filesTab.SetBackgroundColour(wx.WHITE)
self.filesList = SelectableListCtrl(self.filesTab)
self.filesList.InsertColumn(0, 'Name')
self.filesList.InsertColumn(1, 'Size', wx.LIST_FORMAT_RIGHT, 100)
if isinstance(self, LibraryDetails):
self.filesList.InsertColumn(2, 'Priority', wx.LIST_FORMAT_RIGHT)
self.filesList.InsertColumn(3, 'Status', wx.LIST_FORMAT_RIGHT)
self.filesList.Bind(wx.EVT_LEFT_DCLICK, self.OnDoubleClick)
self.filesList.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnFilesSelected)
self.filesList.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.OnFilesSelected)
self.il = wx.ImageList(16, 16)
self.play_img = self.il.Add(GuiImageManager.getInstance().getImage(u"file_video.png"))
self.file_img = self.il.Add(GuiImageManager.getInstance().getImage(u"file_default.png"))
self.filesList.SetImageList(self.il, wx.IMAGE_LIST_SMALL)
self.filesList.setResizeColumn(0)
# Calling SetColumnWidth seems to cause Refresh issues in list_body
# self.filesList.SetColumnWidth(1, wx.LIST_AUTOSIZE) # autosize only works after adding rows
self.filesList.SetMinSize((1, -1))
self.filesSizer = wx.BoxSizer(wx.VERTICAL)
self.filesList.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.OnRightUp)
self.filesSizer.Add(self.filesList, 1, wx.EXPAND | wx.LEFT | wx.TOP | wx.BOTTOM, 10)
self.filesTab.SetSizer(self.filesSizer)
self.notebook.AddPage(self.filesTab, "Files")
def createEditTab(self):
self.editTab, self.editSizer = self._create_tab(self.notebook, 'Edit', border=10)
self.editTab.SetBackgroundColour(wx.WHITE)
vSizer = wx.FlexGridSizer(0, 2, 3, 10)
vSizer.AddGrowableCol(1)
vSizer.AddGrowableRow(1)
self.isEditable['name'] = EditText(self.editTab, '')
self.isEditable['description'] = EditText(self.editTab, '', True)
self.isEditable['description'].SetMinSize((1, 1))
self._add_row(self.editTab, vSizer, "Name", self.isEditable['name'])
self._add_row(self.editTab, vSizer, "Description", self.isEditable['description'])
def save(event):
self.doSave(self.torrent.channel, self)
button = event.GetEventObject()
button.Enable(False)
wx.CallLater(5000, button.Enable, True)
self.editButton = wx.Button(self.editTab, -1, "Save")
self.editButton.Bind(wx.EVT_BUTTON, save)
vSizer.Add((-1, -1), 0, wx.ALIGN_RIGHT)
vSizer.Add(self.editButton, 0, wx.ALIGN_RIGHT)
self.editSizer.Add(vSizer, 1, wx.EXPAND)
def createCommentsTab(self):
from Tribler.Main.vwxGUI.channel import CommentList
self.commentList = NotebookPanel(self.notebook)
self.commentList.SetList(
CommentList(self.commentList, self.parent, canReply=True, quickPost=True, horizontal=True, noheader=True))
def updateTitle(nrcomments):
for i in range(self.notebook.GetPageCount()):
if self.notebook.GetPageText(i).startswith('Comments'):
self.notebook.SetPageText(i, "Comments(%d)" % nrcomments)
self.commentList.SetNrResults = updateTitle
self.notebook.AddPage(self.commentList, 'Comments')
def createModificationsTab(self):
from channel import ModificationList
self.modificationList = NotebookPanel(self.notebook)
self.modificationList.SetList(ModificationList(self.modificationList, self.canEdit))
def updateTitle(nrmodifications):
for i in range(self.notebook.GetPageCount()):
if self.notebook.GetPageText(i).startswith('Modifications'):
self.notebook.SetPageText(i, "Modifications(%d)" % nrmodifications)
self.modificationList.SetNrResults = updateTitle
self.notebook.AddPage(self.modificationList, 'Modifications', tab_colour=wx.WHITE)
def createTrackersTab(self):
self.trackerTab, self.trackerSizer = self._create_tab(self.notebook, "Trackers", border=10)
self.trackerTab.SetBackgroundColour(wx.WHITE)
def updateAllTabs(self):
self.updateDetailsTab()
self.updateFilesTab()
self.updateEditTab()
self.updateCommentsTab()
self.updateModificationsTab()
self.updateTrackersTab()
def updateDetailsTab(self):
self.Freeze()
todo = []
todo.append((self.name, self.torrent.name))
todo.append((self.description, ''))
todo.append((self.type, self.torrent.category.capitalize()
if isinstance(self.torrent.category, basestring) else 'Unknown'))
todo.append((self.uploaded, self.torrent.formatCreationDate()
if hasattr(self.torrent, 'formatCreationDate') else ''))
todo.append((self.filesize, '%s in %d file(s)' % (size_format(self.torrent.length), len(self.torrent.files))
if hasattr(self.torrent, 'files') else '%s' % size_format(self.torrent.length)))
for control, new_value in todo:
if control.GetLabel() != new_value:
control.SetLabel(new_value)
# Toggle piece progress
self.downloaded.Update(torrent=self.torrent)
self.downloaded.Show(bool(self.torrent.state))
# Hide description
self.description_title.Show(False)
self.description.Show(False)
self._updateDescription()
# Toggle status
show_status = bool(self.torrent.state) or bool(self.torrent.magnetstatus)
self.status_title.Show(show_status)
self.status.Show(show_status)
# Toggle infohash
if self.showInfohash:
self.infohash.SetValue(self.torrent.infohash_as_hex)
self.infohash_title.Show(self.showInfohash)
self.infohash.Show(self.showInfohash)
# Toggle associated channel
show_channel = bool(self.torrent.get('channel', False))
if show_channel:
self.channel.SetLabel(self.torrent.channel.name)
self.channel_title.Show(show_channel)
self.channel.Show(show_channel)
# Toggle thumbnails
if self.torrent.metadata and 'thumb_hash' in self.torrent.metadata:
show_thumbnails = True
thumbnail_data = self.guiutility.utility.session.get_thumbnail_data(self.torrent.metadata['thumb_hash'])
image = wx.EmptyImage()
image.LoadStream(StringIO(thumbnail_data))
bitmap = wx.BitmapFromImage(image)
resolution = limit_resolution(bitmap.GetSize(), (175, 175))
bitmaps = [bitmap.ConvertToImage().Scale(*resolution, quality=wx.IMAGE_QUALITY_HIGH).ConvertToBitmap()]
self.thumbnails.SetBitmaps(bitmaps)
else:
show_thumbnails = False
self.thumbnails.Show(show_thumbnails)
self.no_thumb_bitmap.Show(not show_thumbnails)
# Toggle 'Mark this torrent' option
self.marking_vSizer.ShowItems(self.canComment)
self.UpdateHealth()
self.detailsTab.OnChange()
self.detailsTab.Layout()
self.Thaw()
def _updateDescription(self):
def set_description(widget_id, description):
if not wx.FindWindowById(widget_id):
return
if not description:
if self.canEdit:
description = 'No description yet, be the first to add a description.'
else:
description = ''
# Toggle description
self.description.SetLabel(description)
show_description = self.canEdit or bool(description)
self.description_title.Show(show_description)
self.description.Show(show_description)
the_description = self.torrent.get('description', '')
wid = self.GetId()
if not the_description:
metadata = self.torrent.get('metadata', None)
if metadata:
the_description = metadata.get('description', '')
set_description(wid, the_description)
def updateFilesTab(self):
self.filesList.DeleteAllItems()
if hasattr(self.torrent, 'files') and len(self.torrent.files) > 0:
self.notebook.ShowMessageOnPage(self.notebook.GetIndexFromText('Files'), False)
files = copy.copy(self.torrent.files)
keywords = ' | '.join(self.guiutility.current_search_query)
def sort_by_keywords(a, b):
a_match = re.search(keywords, a[0].lower())
b_match = re.search(keywords, b[0].lower())
if a_match and not b_match:
return -1
if b_match and not a_match:
return 1
return cmp(a[0], b[0])
files.sort(sort_by_keywords)
for filename, size in files:
try:
pos = self.filesList.InsertStringItem(sys.maxint, filename)
except:
try:
pos = self.filesList.InsertStringItem(sys.maxint, filename.decode('utf-8', 'ignore'))
except:
self._logger.error("Could not format filename %s", self.torrent.name)
self.filesList.SetItemData(pos, pos)
size = "%.1f MB" % (size / 1048576.0)
self.filesList.SetStringItem(pos, 1, size)
if filename in self.torrent.videofiles:
self.filesList.SetItemColumnImage(pos, 0, self.play_img)
else:
self.filesList.SetItemColumnImage(pos, 0, self.file_img)
else:
self.notebook.ShowMessageOnPage(self.notebook.GetIndexFromText('Files'), True)
def updateEditTab(self):
if self.canEdit:
self.isEditable['name'].SetValue(self.torrent.name)
self.isEditable['description'].SetValue(self.torrent.description or '')
self.editButton.Enable(self.canEdit)
self.notebook.ShowPage(self.notebook.GetIndexFromText('Edit'), self.canEdit)
def updateCommentsTab(self):
if self.canComment:
commentManager = self.commentList.GetManager()
commentManager.SetIds(self.torrent.channel, channeltorrent=self.torrent)
commentManager.refresh()
self.notebook.ShowPage(self.notebook.GetIndexFromText('Comments'), self.canComment)
def updateModificationsTab(self):
show_modifications = self.canEdit or bool(self.torrent.get('description', ''))
if show_modifications:
modificationManager = self.modificationList.GetManager()
modificationManager.SetIds(self.torrent)
modificationManager.refresh()
self.notebook.ShowPage(self.notebook.GetIndexFromText('Modifications'), show_modifications)
def updateTrackersTab(self):
self.trackerSizer.Clear(deleteWindows=True)
collected_trackers = hasattr(self.torrent, 'trackers')
notcollected_trackers = hasattr(self.torrent, 'torrent') and hasattr(self.torrent.torrent, 'trackers')
if collected_trackers or notcollected_trackers:
self.notebook.ShowMessageOnPage(self.notebook.GetIndexFromText('Trackers'), False)
if self.torrent.trackers and len(self.torrent.trackers) > 0:
for tracker in (self.torrent.trackers if collected_trackers else self.torrent.torrent.trackers):
if isinstance(tracker, basestring):
self._add_row(self.trackerTab, self.trackerSizer, None, tracker)
self.trackerSizer.Layout()
else:
self.notebook.ShowMessageOnPage(self.notebook.GetIndexFromText('Trackers'), True)
@warnWxThread
def ShowPanel(self, newState=None):
if getattr(self, 'notebook', False):
if newState is None:
newState = self._GetState()
if self.state != newState:
self.state = newState
else:
# Additionally called by database event, thus we need to check if sizer exists(torrent is downloaded).
wx.CallAfter(self.ShowPanel, newState)
@warnWxThread
def OnChange(self, event):
page = event.GetSelection()
title = self.notebook.GetPageText(page)
if title.startswith('Comments'):
self.commentList.Show()
self.commentList.SetupScrolling()
self.commentList.SetFocus()
elif title.startswith('Modifications'):
self.modificationList.Show()
self.modificationList.SetupScrolling()
self.modificationList.SetFocus()
setattr(self.parent, self.__class__.__name__ + '_tab', title)
event.Skip()
def OnCommentCreated(self, infohash):
if self.torrent.infohash == infohash and self.canComment:
manager = self.commentList.GetManager()
manager.new_comment()
def OnModificationCreated(self, channeltorrent_id):
if self.canEdit:
manager = self.modificationList.GetManager()
manager.new_modification()
def OnMarkingCreated(self, channeltorrent_id):
if self.torrent.get('channeltorrent_id', False) == channeltorrent_id:
self.UpdateMarkings()
def UpdateMarkings(self):
if self.torrent.get('channeltorrent_id', False):
startWorker(self.ShowMarkings, self.guiutility.channelsearch_manager.getTorrentMarkings,
wargs=(self.torrent.channeltorrent_id,), priority=GUI_PRI_DISPERSY)
@warnWxThread
def ShowMarkings(self, delayedResult):
markings = delayedResult.get()
if len(markings) > 0:
msg = 'This torrent is marked as:'
for marktype, nr, myMark in markings:
msg += ' %s (%d)' % (marktype, nr)
if myMark:
self.myMark = marktype
# see if we are updating
if not self.markings:
self.markings = MaxBetterText(self.detailsTab, unicode(msg), maxLines=3)
self.markingSizer.Insert(0, self.markings)
else:
self.markings.SetLabel(msg)
self.detailsSizer.Layout()
def GetChanged(self):
newValues = {}
for key, editable in self.isEditable.iteritems():
newValue = editable.GetChanged()
if newValue:
newValues[key] = newValue
return newValues
def Saved(self):
for editable in self.isEditable.values():
editable.Saved()
@warnWxThread
def OnDoubleClick(self, event):
selected = self.filesList.GetFirstSelected()
playable_files = self.torrent.videofiles
if selected != -1:
selected_file = self.filesList.GetItemText(selected)
if selected_file in playable_files:
self.guiutility.library_manager.playTorrent(self.torrent.infohash, selected_file)
elif self.torrent.progress == 1: # not playable, but are we complete?
file = self._GetPath(selected_file)
if os.path.isfile(file):
startfile(file)
@warnWxThread
def OnRightUp(self, event):
if not self.torrent or not self.torrent.ds or not self.torrent.ds.download:
return
download = self.torrent.ds.download
selection = []
index = self.filesList.GetFirstSelected()
selection.append(index)
while len(selection) != self.filesList.GetSelectedItemCount():
index = self.filesList.GetNextSelected(index)
selection.append(index)
selection = set([self.filesList.GetItem(index, 0).GetText() for index in selection])
selected_files = set(download.get_selected_files()) or set(download.get_def().get_files_as_unicode())
selected_files_includable = selection - selected_files
selected_files_excludable = selection & selected_files
if not selected_files_includable and not selected_files_excludable:
return
menu = wx.Menu()
menuitems = [("Include", [], False), ("Exclude", [], False)]
if selected_files_includable:
files = list(selected_files | selected_files_includable)
menuitems[0] = ("Include", files, True)
if selected_files_excludable:
files = list(selected_files - selected_files_excludable)
# Don't allow excluding everything
if files:
menuitems[1] = ("Exclude", files, True)
for label, files, enabled in menuitems:
itemid = wx.NewId()
menu.Append(itemid, label)
menu.Enable(itemid, enabled)
if enabled:
menu.Bind(wx.EVT_MENU, lambda evt, d=download, f=files: d.set_selected_files(f), id=itemid)
self.PopupMenu(menu, self.ScreenToClient(wx.GetMousePosition()))
menu.Destroy()
self.old_progress = None
@warnWxThread
def _GetPath(self, file=None):
ds = self.torrent.ds
if ds:
destdirs = ds.get_download().get_dest_files()
if file:
for filenameintorrent, path in destdirs:
if filenameintorrent == file:
return path
return os.path.commonprefix([os.path.split(path)[0] for _, path in destdirs])
@warnWxThread
def OnFilesSelected(self, event):
pass
@warnWxThread
def OnClick(self, event):
label = event.GetEventObject()
if label.target == 'my_files':
self.guiutility.frame.actlist.selectTab('my_files')
self.guiutility.ShowPage('my_files', self.torrent.infohash)
else:
self.guiutility.showChannel(self.torrent.channel)
@warnWxThread
def OnMark(self, event):
menu = wx.Menu()
itemid = wx.NewId()
for mark in ['Good', 'High-Quality', 'Mid-Quality', 'Low-Quality', 'Corrupt', 'Fake', 'Spam']:
itemid = wx.NewId()
if self.myMark:
menu.AppendRadioItem(itemid, mark)
menu.Check(itemid, self.myMark == mark)
else:
menu.Append(itemid, mark)
menu.Bind(wx.EVT_MENU, lambda x, selected=mark: self.doMark(
self.torrent.channel, self.torrent.infohash, unicode(selected)), id=itemid)
pos = wx.Point(self.markicon.GetPosition().x, self.marktoggle.GetPosition().y + self.marktoggle.GetSize().y)
self.detailsTab.PopupMenu(menu, pos)
menu.Destroy()
@warnWxThread
def RefreshData(self, data):
if isinstance(self.torrent, Torrent):
curTorrent = self.torrent
else:
curTorrent = self.torrent.torrent
newTorrent = data[2]
if curTorrent.infohash != newTorrent.infohash:
return
self.torrent.updateSwarminfo(newTorrent.swarminfo)
self.torrent.update_torrent_id(newTorrent.torrent_id)
if not curTorrent.exactCopy(newTorrent):
# replace current torrent
curTorrent.name = newTorrent.name
curTorrent.length = newTorrent.length
curTorrent.category = newTorrent.category
curTorrent.status = newTorrent.status
self.updateDetailsTab()
if self.canEdit:
if not self.isEditable['name'].IsChanged():
self.isEditable['name'].SetValue(curTorrent.name)
if not self.isEditable['description'].IsChanged():
self.isEditable['description'].SetValue(curTorrent.description or '')
@forceDBThread
def UpdateHealth(self):
if not (self and self.torrent and self.torrent.swarminfo):
return
if getattr(self.torrent, 'trackers', None) and len(self.torrent.trackers) > 0:
# touch swarminfo property
_, _, last_successful_check = self.torrent.swarminfo
last_check = self.tracker_checks.get(self.torrent.infohash, 0)
now = time()
if now - last_successful_check > 1800 and now - last_check > 300:
self.utility.session.check_torrent_health(self.torrent.infohash)
self.ShowHealth(True)
self.tracker_checks[self.torrent.infohash] = now
else:
self.ShowHealth(False)
else:
self.ShowHealth(False, ', no trackers found')
@forceWxThread
def ShowHealth(self, updating, no_update_reason=''):
if not self:
return
if isinstance(self.torrent, CollectedTorrent):
updating = ', updating now' if updating else no_update_reason
num_seeders, num_leechers, last_check = self.torrent.swarminfo
diff = time() - last_check
if num_seeders < 0 and num_leechers < 0:
if self.torrent.status == 'good':
self.health.SetLabel("Unknown, but found peers in the DHT")
else:
self.health.SetLabel("Unknown" + updating)
else:
if diff < 5:
self.health.SetLabel("%s seeders, %s leechers (current)" % (num_seeders, num_leechers))
else:
updated = eta_value(diff, 2)
if updated == '<unknown>':
self.health.SetLabel("%s seeders, %s leechers" % (num_seeders, num_leechers) + updating)
else:
self.health.SetLabel("%s seeders, %s leechers (updated %s ago%s)" % (
num_seeders, num_leechers, updated, updating))
else:
self.health.SetLabel("Unknown")
def OnRefresh(self, dslist, magnetlist):
"""
The download statelist and the magnet list are provided by
the _do_gui_callback function in the SearchGridManager.
"""
found = False
if self and self.torrent: # avoid pydeadobject error
for ds in dslist:
if self.torrent.addDs(ds):
found = True
self.torrent.magnetstatus = magnetlist.get(self.torrent.infohash, None)
if not found:
self.torrent.clearDs()
self._Refresh()
@warnWxThread
def _Refresh(self, ds=None):
if ds:
self.torrent.addDs(ds)
state = self._GetState()
if state != self.state:
self.ShowPanel(state)
if state in [TorrentDetails.INCOMPLETE, TorrentDetails.INCOMPLETE_INACTIVE, TorrentDetails.VOD, TorrentDetails.FINISHED]:
self.updateDetailsTab()
if self.status_title.IsShown() != (bool(self.torrent.state) or bool(self.torrent.magnetstatus)):
self.updateDetailsTab()
self.UpdateStatus()
def UpdateStatus(self):
ds = self.torrent.ds
progress = ds.get_progress() if ds else 0
statusflag = ds.get_status() if ds else DLSTATUS_STOPPED
finished = progress == 1.0
is_vod = ds.get_download().get_mode() == DLMODE_VOD if ds else False
status = None
if statusflag == DLSTATUS_DOWNLOADING:
dls = ds.get_current_speed('down')
status = 'Streaming' if is_vod else 'Downloading'
status += ' @ %s' % speed_format(dls)
elif statusflag == DLSTATUS_METADATA:
status = 'Torrent file is being downloaded from the DHT'
elif statusflag == DLSTATUS_SEEDING:
uls = ds.get_current_speed('up')
status = 'Seeding @ %s, ratio: %.3f' % (speed_format(uls), ds.seeding_ratio)
elif finished:
status = 'Completed'
elif statusflag in [DLSTATUS_ALLOCATING_DISKSPACE, DLSTATUS_WAITING4HASHCHECK]:
status = 'Waiting'
elif statusflag == DLSTATUS_HASHCHECKING:
status = 'Checking'
elif statusflag == DLSTATUS_STOPPED:
status = 'Stopped'
if status and not finished and self.torrent.progress and statusflag in [DLSTATUS_DOWNLOADING, DLSTATUS_STOPPED]:
status += " (%.1f%%)" % (self.torrent.progress * 100)
if status:
self.status.SetLabel(status)
def _GetState(self):
active = vod = False
progress = self.torrent.progress
finished = progress == 1.0
ds = self.torrent.ds
if ds:
if finished: # finished download
active = ds.get_status() == DLSTATUS_SEEDING