forked from Tribler/tribler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchannel.py
2604 lines (2034 loc) · 96 KB
/
channel.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
import wx
import os
import sys
from time import time
import pickle
from random import sample
from traceback import print_exc
import re
from binascii import hexlify
from Tribler.Main.vwxGUI.GuiUtility import GUIUtility, forceWxThread
from Tribler.Main.vwxGUI.widgets import _set_font, NotebookPanel, SimpleNotebook, EditText, BetterText
from Tribler.Category.Category import Category
from Tribler.Core.TorrentDef import TorrentDef
from Tribler.Core.CacheDB.sqlitecachedb import forceDBThread
from Tribler.Main.vwxGUI import (CHANNEL_MAX_NON_FAVORITE, warnWxThread, LIST_GREY, LIST_LIGHTBLUE, LIST_DESELECTED,
DEFAULT_BACKGROUND, format_time, showError)
from Tribler.Main.vwxGUI.list import BaseManager, GenericSearchList, SizeList, List
from Tribler.Main.vwxGUI.list_body import ListBody
from Tribler.Main.vwxGUI.list_footer import (CommentFooter, PlaylistFooter, ManageChannelFilesFooter,
ManageChannelPlaylistFooter)
from Tribler.Main.vwxGUI.list_header import (ChannelHeader, SelectedChannelFilter, SelectedPlaylistFilter,
PlaylistHeader, ManageChannelHeader, TitleHeader)
from Tribler.Main.vwxGUI.list_item import (PlaylistItem, ColumnsManager, DragItem, TorrentListItem, CommentItem,
CommentActivityItem, NewTorrentActivityItem, TorrentActivityItem,
ModificationActivityItem, ModerationActivityItem, MarkingActivityItem,
ModificationItem, ModerationItem, ThumbnailListItem)
from Tribler.Main.vwxGUI.list_details import (AbstractDetails, SelectedchannelInfoPanel, PlaylistDetails,
PlaylistInfoPanel, TorrentDetails, MyChannelPlaylist)
from Tribler.Main.Utility.GuiDBHandler import startWorker, cancelWorker, GUI_PRI_DISPERSY
from Tribler.community.channel.community import ChannelCommunity
from Tribler.Main.Utility.GuiDBTuples import Torrent, CollectedTorrent, ChannelTorrent
from Tribler.Main.Dialogs.AddTorrent import AddTorrent
class ChannelManager(BaseManager):
def __init__(self, list):
super(ChannelManager, self).__init__(list)
self.channelsearch_manager = self.guiutility.channelsearch_manager
self.library_manager = self.guiutility.library_manager
self.Reset()
def Reset(self):
super(ChannelManager, self).Reset()
if self.list.channel:
cancelWorker("ChannelManager_refresh_list_%d" % self.list.channel.id)
self.list.SetChannel(None)
def refreshDirty(self):
if 'COMPLETE_REFRESH_STATE' in self.dirtyset:
self._refresh_list(stateChanged=True)
self.dirtyset.clear()
else:
BaseManager.refreshDirty(self)
@forceDBThread
def reload(self, channel_id):
channel = self.channelsearch_manager.getChannel(channel_id)
self.refresh(channel)
@forceWxThread
def refresh(self, channel=None):
if channel:
# copy torrents if channel stays the same
if channel == self.list.channel:
if self.list.channel.torrents:
if channel.torrents:
channel.torrents.update(self.list.channel.torrents)
else:
channel.torrents = self.list.channel.torrents
self.list.Reset()
self.list.SetChannel(channel)
self._refresh_list(channel)
def refresh_if_required(self, channel):
if self.list.channel != channel:
self.refresh(channel)
def _refresh_list(self, stateChanged=False):
t1 = time()
self._logger.debug("SelChannelManager complete refresh %s", t1)
self.list.dirty = False
def db_callback():
channel = self.list.channel
if channel:
t2 = time()
state = iamModerator = None
if stateChanged:
result = channel.refreshState()
if result:
state, iamModerator = channel.refreshState()
if self.list.channel.isDispersy():
nr_playlists, playlists = self.channelsearch_manager.getPlaylistsFromChannel(channel)
total_items, nrfiltered, torrentList = self.channelsearch_manager.getTorrentsNotInPlaylist(
channel, self.guiutility.getFamilyFilter())
else:
playlists = []
total_items, nrfiltered, torrentList = self.channelsearch_manager.getTorrentsFromChannel(
channel, self.guiutility.getFamilyFilter())
t3 = time()
self._logger.debug("SelChannelManager complete refresh took %s %s %s", t3 - t1, t2 - t1, t3)
return total_items, nrfiltered, torrentList, playlists, state, iamModerator
def do_gui(delayedResult):
result = delayedResult.get()
if result:
total_items, nrfiltered, torrentList, playlists, state, iamModerator = result
if state is not None:
self.list.SetChannelState(state, iamModerator)
self._on_data(total_items, nrfiltered, torrentList, playlists)
if self.list.channel:
startWorker(
do_gui,
db_callback,
uId=u"ChannelManager_refresh_list_%d" %
self.list.channel.id,
retryOnBusy=True,
priority=GUI_PRI_DISPERSY)
@forceWxThread
def _on_data(self, total_items, nrfiltered, torrents, playlists):
# only show a small random selection of available content for non-favorite channels
inpreview = not self.list.channel.isFavorite() and not self.list.channel.isMyChannel()
if inpreview:
if len(playlists) > 3:
playlists = sample(playlists, 3)
if len(torrents) > CHANNEL_MAX_NON_FAVORITE:
def cmp_torrent(a, b):
return cmp(a.time_stamp, b.time_stamp)
torrents = sample(torrents, CHANNEL_MAX_NON_FAVORITE)
torrents.sort(cmp=cmp_torrent, reverse=True)
# sometimes a channel has some torrents in the torrents variable, merge them here
if self.list.channel.torrents:
remoteTorrents = set(torrent.infohash for torrent in self.list.channel.torrents)
for i in xrange(len(torrents), 0, -1):
if torrents[i - 1].infohash in remoteTorrents:
torrents.pop(i - 1)
torrents = list(self.list.channel.torrents) + torrents
if inpreview:
torrents = torrents[:CHANNEL_MAX_NON_FAVORITE]
self.list.SetData(playlists, torrents)
self._logger.debug("SelChannelManager complete refresh done")
@forceDBThread
def refresh_partial(self, ids):
if self.list.channel:
id_data = {}
for id in ids:
if isinstance(id, str) and len(id) == 20:
id_data[id] = self.channelsearch_manager.getTorrentFromChannel(self.list.channel, id)
else:
id_data[id] = self.channelsearch_manager.getPlaylist(self.list.channel, id)
def do_gui():
for id, data in id_data.iteritems():
if data:
self.list.RefreshData(id, data)
else:
self.list.RemoveItem(id)
wx.CallAfter(do_gui)
@forceWxThread
def downloadStarted(self, infohash):
if self.list.InList(infohash):
item = self.list.GetItem(infohash)
torrent_details = item.GetExpandedPanel()
if torrent_details:
torrent_details.DownloadStarted()
else:
item.DoExpand()
def torrentUpdated(self, infohash):
if self.list.InList(infohash):
self.do_or_schedule_partial([infohash])
def torrentsUpdated(self, infohashes):
infohashes = [infohash for infohash in infohashes if self.list.InList(infohash)]
self.do_or_schedule_partial(infohashes)
def channelUpdated(self, channel_id, stateChanged=False, modified=False):
_channel = self.list.channel
if _channel and _channel == channel_id:
if _channel.isFavorite() or _channel.isMyChannel():
# only update favorite or mychannel
if modified:
self.reload(channel_id)
else:
if self.list.ShouldGuiUpdate():
self._refresh_list(stateChanged)
else:
key = 'COMPLETE_REFRESH'
if stateChanged:
key += '_STATE'
self.dirtyset.add(key)
self.list.dirty = True
def playlistCreated(self, channel_id):
if self.list.channel == channel_id:
self.do_or_schedule_refresh()
def playlistUpdated(self, playlist_id, infohash=False, modified=False):
if self.list.InList(playlist_id):
if self.list.InList(infohash): # if infohash is shown, complete refresh is necessary
self.do_or_schedule_refresh()
else: # else, only update this single playlist
self.do_or_schedule_partial([playlist_id])
class SelectedChannelList(GenericSearchList):
def __init__(self, parent):
self.guiutility = GUIUtility.getInstance()
self.utility = self.guiutility.utility
self.session = self.guiutility.utility.session
self.channelsearch_manager = self.guiutility.channelsearch_manager
self.display_grid = False
self.title = None
self.channel = None
self.iamModerator = False
self.my_channel = False
self.state = ChannelCommunity.CHANNEL_CLOSED
columns = [{'name': 'Name', 'sortAsc': True},
{'name': 'Torrents', 'width': '14em', 'fmt': lambda x: '?' if x == -1 else str(x)}]
columns = self.guiutility.SetColumnInfo(PlaylistItem, columns)
ColumnsManager.getInstance().setColumns(PlaylistItem, columns)
self.category_names = {}
for key, name in Category.getInstance().getCategoryNames(filter=False):
self.category_names[key] = name
self.category_names[None] = 'Unknown'
GenericSearchList.__init__(self, None, wx.WHITE, [0, 0], True, borders=False, showChange=True, parent=parent)
self.list.OnBack = self.OnBack
self.list.Bind(wx.EVT_SHOW, lambda evt: self.notebook.SetSelection(0))
@warnWxThread
def _PostInit(self):
self.notebook = SimpleNotebook(self.parent, show_single_tab=False, style=wx.NB_NOPAGETHEME)
self.notebook.SetForegroundColour(self.parent.GetForegroundColour())
self.notebook.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnChange)
contentList = wx.Panel(self.notebook)
contentList.SetForegroundColour(self.notebook.GetForegroundColour())
contentList.SetFocus = contentList.SetFocusIgnoringChildren
self.header = self.CreateHeader(contentList)
self.list = self.CreateList(contentList)
vSizer = wx.BoxSizer(wx.VERTICAL)
vSizer.Add(self.header, 0, wx.EXPAND)
vSizer.Add(self.list, 1, wx.EXPAND)
contentList.SetSizer(vSizer)
self.notebook.AddPage(contentList, "Contents", tab_colour=wx.WHITE)
self.commentList = NotebookPanel(self.notebook)
self.commentList.SetList(CommentList(self.commentList, self, canReply=True))
self.commentList.header.SetBackgroundColour(wx.WHITE)
self.commentList.Show(False)
self.activityList = NotebookPanel(self.notebook)
self.activityList.SetList(ActivityList(self.activityList, self))
self.activityList.header.SetBackgroundColour(wx.WHITE)
self.activityList.Show(False)
self.moderationList = NotebookPanel(self.notebook)
self.moderationList.SetList(ModerationList(self.moderationList, self))
self.moderationList.header.SetBackgroundColour(wx.WHITE)
self.moderationList.Show(False)
self.leftLine = wx.Panel(self.parent, size=(1, -1))
self.rightLine = wx.Panel(self.parent, size=(1, -1))
listSizer = wx.BoxSizer(wx.HORIZONTAL)
listSizer.Add(self.leftLine, 0, wx.EXPAND)
listSizer.Add(self.notebook, 1, wx.EXPAND)
listSizer.Add(self.rightLine, 0, wx.EXPAND)
self.top_header = self.CreateTopHeader(self.parent)
self.Add(self.top_header, 0, wx.EXPAND)
self.Add(listSizer, 1, wx.EXPAND)
self.SetBackgroundColour(self.background)
self.Layout()
self.list.Bind(wx.EVT_SIZE, self.OnSize)
def _special_icon(self, item):
if not isinstance(item, PlaylistItem) and self.channel:
if self.channel.isFavorite():
return self.favorite, self.normal, "This torrent is part of one of your favorite channels, %s" % self.channel.name
else:
return self.normal, self.favorite, "This torrent is not part of one of your favorite channels"
def CreateList(self, parent=None, listRateLimit=1):
if not parent:
parent = self
return ListBody(parent, self, self.columns, self.spacers[0], self.spacers[1], self.singleSelect, self.showChange, listRateLimit=listRateLimit, grid_columns=4 if self.display_grid else 0)
@warnWxThread
def CreateHeader(self, parent):
return SelectedChannelFilter(parent, self)
@warnWxThread
def CreateTopHeader(self, parent):
return ChannelHeader(parent, self)
@warnWxThread
def Reset(self):
self.title = None
self.channel = None
self.iamModerator = False
self.my_channel = False
if GenericSearchList.Reset(self):
self.commentList.Reset()
self.activityList.Reset()
self.moderationList.Reset()
return True
return False
def ToggleGrid(self):
self.display_grid = not self.display_grid
new_raw_data = []
for data in (self.list.raw_data or []):
if self.display_grid and (len(data) < 4 or data[3] == TorrentListItem):
new_raw_data.append(list(data[:3]) + [ThumbnailListItem])
elif not self.display_grid and data[3] == ThumbnailListItem:
new_raw_data.append(list(data[:3]) + [TorrentListItem])
self.list.SetData(new_raw_data)
self.list.SetGrid(self.display_grid)
@warnWxThread
def SetChannel(self, channel):
self.channel = channel
self.Freeze()
self.SetIds(channel)
if channel:
self.SetTitle(channel)
self.Thaw()
def SetIds(self, channel):
if channel:
self.my_channel = channel.isMyChannel()
else:
self.my_channel = False
# Always switch to page 1 after new id
if self.notebook.GetPageCount() > 0:
self.notebook.SetSelection(0)
@warnWxThread
def SetChannelState(self, state, iamModerator):
self.iamModerator = iamModerator
self.state = state
self.channel.setState(state, iamModerator)
if state >= ChannelCommunity.CHANNEL_SEMI_OPEN:
if self.notebook.GetPageCount() == 1:
self.commentList.Show(True)
self.activityList.Show(True)
self.notebook.AddPage(self.commentList, "Comments", tab_colour=wx.WHITE)
self.notebook.AddPage(self.activityList, "Activity", tab_colour=wx.WHITE)
if state >= ChannelCommunity.CHANNEL_OPEN and self.notebook.GetPageCount() == 3:
self.moderationList.Show(True)
self.notebook.AddPage(self.moderationList, "Moderations", tab_colour=wx.WHITE)
else:
for i in range(self.notebook.GetPageCount(), 1, -1):
page = self.notebook.GetPage(i - 1)
page.Show(False)
self.notebook.RemovePage(i - 1)
# Update header + list ids
self.ResetBottomWindow()
self.top_header.SetButtons(self.channel)
self.commentList.GetManager().SetIds(channel=self.channel)
self.activityList.GetManager().SetIds(channel=self.channel)
self.moderationList.GetManager().SetIds(channel=self.channel)
@warnWxThread
def SetTitle(self, channel):
self.title = channel.name
self.top_header.SetTitle(channel)
self.Layout()
def GetManager(self):
if getattr(self, 'manager', None) is None:
self.manager = ChannelManager(self)
return self.manager
@forceWxThread
def SetData(self, playlists, torrents):
SizeList.SetData(self, torrents)
if len(playlists) > 0 or len(torrents) > 0:
data = [(playlist.id, [playlist.name, playlist.nr_torrents, 0, 0, 0, 0], playlist, PlaylistItem, index)
for index, playlist in enumerate(playlists)]
shouldDrag = len(playlists) > 0 and (self.channel.iamModerator or self.channel.isOpen())
if shouldDrag:
data += [(torrent.infohash, [torrent.name, torrent.length, self.category_names[torrent.category],
torrent.num_seeders, torrent.num_leechers, 0, None],
torrent, DragItem) for torrent in torrents]
elif self.display_grid:
data += [(torrent.infohash, [torrent.name, torrent.length, self.category_names[torrent.category],
torrent.num_seeders, torrent.num_leechers, 0, None],
torrent, ThumbnailListItem) for torrent in torrents]
else:
data += [(torrent.infohash, [torrent.name, torrent.length, self.category_names[torrent.category],
torrent.num_seeders, torrent.num_leechers, 0, None],
torrent, TorrentListItem) for torrent in torrents]
self.list.SetData(data)
else:
header = 'No torrents or playlists found.'
if self.channel and self.channel.isOpen():
message = 'As this is an "open" channel, '\
'you can add your own torrents to share them with others in this channel'
self.list.ShowMessage(message, header=header)
else:
self.list.ShowMessage(header)
self.SetNrResults(0)
@warnWxThread
def SetNrResults(self, nr):
SizeList.SetNrResults(self, nr)
if self.channel and (self.channel.isFavorite() or self.channel.isMyChannel()):
header = 'Discovered'
else:
header = 'Previewing'
if nr == 1:
self.header.SetSubTitle(header + ' %d torrent' % nr)
else:
if self.channel and self.channel.isFavorite():
self.header.SetSubTitle(header + ' %d torrents' % nr)
else:
self.header.SetSubTitle(header + ' %d torrents' % nr)
@forceWxThread
def RefreshData(self, key, data):
List.RefreshData(self, key, data)
if data:
if isinstance(data, Torrent):
if self.state == ChannelCommunity.CHANNEL_OPEN or self.iamModerator:
data = (data.infohash, [data.name, data.length, self.category_names[data.category],
data.num_seeders, data.num_leechers, 0, None], data, DragItem)
else:
data = (data.infohash, [data.name, data.length, self.category_names[data.category],
data.num_seeders, data.num_leechers, 0, None], data)
else:
data = (data.id, [data.name, data.nr_torrents], data, PlaylistItem)
self.list.RefreshData(key, data)
manager = self.activityList.GetManager()
manager.do_or_schedule_refresh()
@warnWxThread
def OnExpand(self, item):
if isinstance(item, PlaylistItem):
detailspanel = self.guiutility.SetBottomSplitterWindow(PlaylistDetails)
detailspanel.showPlaylist(item.original_data)
item.expandedPanel = detailspanel
elif isinstance(item, TorrentListItem) or isinstance(item, ThumbnailListItem):
detailspanel = self.guiutility.SetBottomSplitterWindow(TorrentDetails)
detailspanel.setTorrent(item.original_data)
item.expandedPanel = detailspanel
self.top_header.header_list.DeselectAll()
return True
@warnWxThread
def OnCollapse(self, item, panel, from_expand):
if not isinstance(item, PlaylistItem) and panel:
# detect changes
changes = panel.GetChanged()
if len(changes) > 0:
dlg = wx.MessageDialog(
None,
'Do you want to save your changes made to this torrent?',
'Save changes?',
wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
if dlg.ShowModal() == wx.ID_YES:
self.OnSaveTorrent(self.channel, panel)
dlg.Destroy()
GenericSearchList.OnCollapse(self, item, panel, from_expand)
@warnWxThread
def ResetBottomWindow(self):
_channel = self.channel
if _channel:
detailspanel = self.guiutility.SetBottomSplitterWindow(SelectedchannelInfoPanel)
num_items = len(self.list.raw_data) if self.list.raw_data else 1
detailspanel.Set(num_items, _channel.my_vote, self.state, self.iamModerator)
else:
self.guiutility.SetBottomSplitterWindow()
@warnWxThread
def OnSaveTorrent(self, channel, panel):
changes = panel.GetChanged()
if len(changes) > 0:
self.channelsearch_manager.modifyTorrent(channel.id, panel.torrent.channeltorrent_id, changes)
panel.Saved()
@forceDBThread
def AddTorrent(self, playlist, torrent):
def gui_call():
manager = self.GetManager()
manager._refresh_list()
self.channelsearch_manager.addPlaylistTorrent(playlist, torrent)
wx.CallAfter(gui_call)
@warnWxThread
def OnRemoveFavorite(self, event):
self.guiutility.RemoveFavorite(event, self.channel)
@warnWxThread
def OnFavorite(self, event=None):
self.guiutility.MarkAsFavorite(event, self.channel)
@warnWxThread
def OnRemoveSpam(self, event):
self.guiutility.RemoveSpam(event, self.channel)
@warnWxThread
def OnSpam(self, event):
self.guiutility.MarkAsSpam(event, self.channel)
@warnWxThread
def OnManage(self, event):
if self.channel:
self.guiutility.showManageChannel(self.channel)
@warnWxThread
def OnBack(self, event):
if self.channel:
self.guiutility.GoBack(self.channel.id)
@warnWxThread
def OnSize(self, event):
event.Skip()
def OnChange(self, event):
source = event.GetEventObject()
if source == self.notebook:
page = event.GetSelection()
if page == 1:
self.commentList.Show()
self.commentList.Focus()
elif page == 2:
self.activityList.Show()
self.activityList.Focus()
elif page == 3:
self.moderationList.Show()
self.moderationList.Focus()
self.UpdateSplitter()
event.Skip()
def OnDrag(self, dragitem):
torrent = dragitem.original_data
tdo = TorrentDO(torrent)
tds = wx.DropSource(dragitem)
tds.SetData(tdo)
tds.DoDragDrop(True)
@warnWxThread
def OnCommentCreated(self, channel_id):
if self.channel == channel_id:
manager = self.commentList.GetManager()
manager.new_comment()
manager = self.activityList.GetManager()
manager.new_activity()
else: # maybe channel_id is a infohash
panel = self.list.GetExpandedItem()
if panel:
torDetails = panel.GetExpandedPanel()
if torDetails:
torDetails.OnCommentCreated(channel_id)
@warnWxThread
def OnModificationCreated(self, channel_id):
if self.channel == channel_id:
manager = self.activityList.GetManager()
manager.new_activity()
else: # maybe channel_id is a channeltorrent_id
panel = self.list.GetExpandedItem()
if panel:
torDetails = panel.GetExpandedPanel()
if torDetails:
torDetails.OnModificationCreated(channel_id)
@warnWxThread
def OnModerationCreated(self, channel_id):
if self.channel == channel_id:
manager = self.moderationList.GetManager()
manager.new_moderation()
@warnWxThread
def OnMarkingCreated(self, channeltorrent_id):
panel = self.list.GetExpandedItem()
if panel:
torDetails = panel.GetExpandedPanel()
if torDetails:
torDetails.OnMarkingCreated(channeltorrent_id)
@warnWxThread
def OnMarkTorrent(self, channel, infohash, type):
self.channelsearch_manager.markTorrent(channel.id, infohash, type)
def OnFilter(self, keyword):
new_filter = keyword.lower().strip()
self.categoryfilter = None
if new_filter.find("category=") > -1:
try:
start = new_filter.find("category='")
start = start + 10 if start >= 0 else -1
end = new_filter.find("'", start)
if start == -1 or end == -1:
category = None
else:
category = new_filter[start:end]
self.categoryfilter = category
new_filter = new_filter[:start - 10] + new_filter[end + 1:]
except:
pass
SizeList.OnFilter(self, new_filter)
def GotFilter(self, keyword=None):
GenericSearchList.GotFilter(self, keyword)
self.GetManager().do_or_schedule_refresh()
@warnWxThread
def Select(self, key, raise_event=True, force=False):
if isinstance(key, Torrent):
torrent = key
key = torrent.infohash
if torrent.getPlaylist:
self.guiutility.showPlaylist(torrent.getPlaylist)
wx.CallLater(0, self.guiutility.frame.playlist.Select, key)
return
GenericSearchList.Select(self, key, raise_event, force)
if self.notebook.GetPageCount() > 0:
self.notebook.SetSelection(0)
self.UpdateSplitter()
self.ScrollToId(key)
def UpdateSplitter(self):
splitter = self.guiutility.frame.splitter
topwindow = self.guiutility.frame.splitter_top_window
bottomwindow = self.guiutility.frame.splitter_bottom_window
if self.notebook.GetPageText(self.notebook.GetSelection()) == 'Contents':
if not splitter.IsSplit():
sashpos = getattr(self.parent, 'sashpos', -185)
splitter.SplitHorizontally(topwindow, bottomwindow, sashpos)
else:
if splitter.IsSplit():
self.parent.sashpos = splitter.GetSashPosition()
splitter.Unsplit(bottomwindow)
def StartDownload(self, torrent):
def do_gui(delayedResult):
nrdownloaded = delayedResult.get()
if nrdownloaded:
self._ShowFavoriteDialog(nrdownloaded)
self.guiutility.torrentsearch_manager.downloadTorrent(torrent)
def do_db():
channel = self.channel
if channel:
return self.channelsearch_manager.getNrTorrentsDownloaded(channel.id) + 1
if not self.channel.isFavorite():
startWorker(do_gui, do_db, retryOnBusy=True, priority=GUI_PRI_DISPERSY)
else:
self.guiutility.torrentsearch_manager.downloadTorrent(torrent)
def _ShowFavoriteDialog(self, nrdownloaded):
dial = wx.MessageDialog(
None,
"You downloaded %d torrents from this Channel. "\
"'Mark as favorite' will ensure that you will always have access to newest channel content.\n\n"\
"Do you want to mark this channel as one of your favorites now?" % nrdownloaded,
'Mark as Favorite?',
wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
if dial.ShowModal() == wx.ID_YES:
self.OnFavorite()
dial.Destroy()
class TorrentDO(wx.CustomDataObject):
def __init__(self, data):
wx.CustomDataObject.__init__(self, wx.CustomDataFormat("TORRENT"))
self.setObject(data)
def setObject(self, obj):
self.SetData(pickle.dumps(obj))
def getObject(self):
return pickle.loads(self.GetData())
class TorrentDT(wx.PyDropTarget):
def __init__(self, playlist, callback):
wx.PyDropTarget.__init__(self)
self.playlist = playlist
self.callback = callback
self.cdo = TorrentDO(None)
self.SetDataObject(self.cdo)
def OnData(self, x, y, data):
if self.GetData():
self.callback(self.playlist, self.cdo.getObject())
class PlaylistManager(BaseManager):
def __init__(self, list):
BaseManager.__init__(self, list)
self.library_manager = self.guiutility.library_manager
self.channelsearch_manager = self.guiutility.channelsearch_manager
def SetPlaylist(self, playlist):
if self.list.playlist != playlist:
self.list.Reset()
self.list.playlist = playlist
self.list.SetChannel(playlist.channel)
self.refresh()
def Reset(self):
BaseManager.Reset(self)
if self.list.playlist:
cancelWorker("PlaylistManager_refresh_list_%d" % self.list.playlist.id)
def refresh(self):
def db_call():
self.list.dirty = False
return self.channelsearch_manager.getTorrentsFromPlaylist(self.list.playlist, self.guiutility.getFamilyFilter())
if self.list.playlist:
startWorker(
self._on_data,
db_call,
uId=u"PlaylistManager_refresh_list_%d" %
self.list.playlist.id,
retryOnBusy=True,
priority=GUI_PRI_DISPERSY)
@forceDBThread
def refresh_partial(self, ids):
if self.list.playlist:
id_data = {}
for id in ids:
if isinstance(id, str) and len(id) == 20:
id_data[id] = self.channelsearch_manager.getTorrentFromPlaylist(self.list.playlist, id)
def do_gui():
for id, data in id_data.iteritems():
self.list.RefreshData(id, data)
wx.CallAfter(do_gui)
def _on_data(self, delayedResult):
total_items, nrfiltered, torrents = delayedResult.get()
torrents = self.library_manager.addDownloadStates(torrents)
self.list.SetData([], torrents)
def torrentUpdated(self, infohash):
if self.list.InList(infohash):
self.do_or_schedule_partial([infohash])
def torrentsUpdated(self, infohashes):
infohashes = [infohash for infohash in infohashes if self.list.InList(infohash)]
self.do_or_schedule_partial(infohashes)
def playlistUpdated(self, playlist_id, modified=False):
if self.list.playlist == playlist_id:
if modified:
self.do_or_schedule_refresh()
else:
self.guiutility.GoBack()
class Playlist(SelectedChannelList):
def __init__(self, *args, **kwargs):
self.playlist = None
SelectedChannelList.__init__(self, *args, **kwargs)
def _special_icon(self, item):
if not isinstance(item, PlaylistItem) and self.playlist and self.playlist.channel:
if self.playlist.channel.isFavorite():
return self.favorite, self.normal, "This torrent is part of one of your favorite channels, %s" % self.playlist.channel.name
else:
return self.normal, self.favorite, "This torrent is not part of one of your favorite channels"
else:
pass
def GetManager(self):
if getattr(self, 'manager', None) is None:
self.manager = PlaylistManager(self)
return self.manager
@warnWxThread
def CreateHeader(self, parent):
return SelectedPlaylistFilter(parent, self)
@warnWxThread
def CreateTopHeader(self, parent):
return PlaylistHeader(parent, self)
def Set(self, playlist):
self.playlist = playlist
manager = self.GetManager()
manager.SetPlaylist(playlist)
if self.notebook.GetPageCount() > 0:
self.notebook.SetSelection(0)
if self.playlist:
self.top_header.SetTitle(self.playlist)
self.Layout()
def SetTitle(self, title, description):
header = u"%s's channel \u2192 %s" % (self.channel.name, self.playlist.name)
self.header.SetTitle(header)
self.header.SetStyle(self.playlist.description)
self.Layout()
def SetIds(self, channel):
if channel:
manager = self.commentList.GetManager()
manager.SetIds(channel=channel, playlist=self.playlist)
manager = self.activityList.GetManager()
manager.SetIds(channel=channel, playlist=self.playlist)
manager = self.moderationList.GetManager()
manager.SetIds(channel=channel, playlist=self.playlist)
def OnCommentCreated(self, key):
SelectedChannelList.OnCommentCreated(self, key)
if self.InList(key):
manager = self.commentList.GetManager()
manager.new_comment()
def CreateFooter(self, parent):
return PlaylistFooter(parent, radius=0, spacers=[7, 7])
@warnWxThread
def ResetBottomWindow(self):
detailspanel = self.guiutility.SetBottomSplitterWindow(PlaylistInfoPanel)
detailspanel.Set(
len(self.list.raw_data) if self.list.raw_data else 1,
self.playlist.channel.isFavorite() if self.playlist and self.playlist.channel else None)
class ManageChannelFilesManager(BaseManager):
def __init__(self, list):
BaseManager.__init__(self, list)
self.channel = None
self.channelsearch_manager = self.guiutility.channelsearch_manager
self.Reset()
def Reset(self):
BaseManager.Reset(self)
if self.channel:
cancelWorker("ManageChannelFilesManager_refresh_%d" % self.channel.id)
self.channel = None
def refresh(self):
def db_call():
self.list.dirty = False
return self.channelsearch_manager.getTorrentsFromChannel(self.channel, filterTorrents=False)
startWorker(
self._on_data,
db_call,
uId=u"ManageChannelFilesManager_refresh_%d" %
self.channel.id,
retryOnBusy=True,
priority=GUI_PRI_DISPERSY)
def _on_data(self, delayedResult):
total_items, nrfiltered, torrentList = delayedResult.get()
self.list.SetData(torrentList)
def SetChannel(self, channel):
if self.channel != channel:
self.channel = channel
self.do_or_schedule_refresh()
def RemoveItems(self, infohashes):
for infohash in infohashes:
self.channelsearch_manager.removeTorrent(self.channel, infohash)
def RemoveAllItems(self):
self.channelsearch_manager.removeAllTorrents(self.channel)
def startDownloadFromUrl(self, url, *args, **kwargs):
try:
tdef = TorrentDef.load_from_url(url)
if tdef:
return self.AddTDef(tdef)
except:
print_exc()
return False
def startDownloadFromMagnet(self, url, *args, **kwargs):
try:
callback = lambda meta_info: self.AddTDef(TorrentDef.load_from_dict(meta_info))
self.guiutility.utility.session.lm.ltmgr.get_metainfo(url, callback, timeout=300)
return True
except:
print_exc()
return False
def startDownload(self, torrentfilename, *args, **kwargs):
try:
# if fixtorrent not in kwargs -> new torrent created
tdef = TorrentDef.load(torrentfilename)
if 'fixtorrent' not in kwargs:
download = self.guiutility.frame.startDownload(torrentfilename=torrentfilename,
destdir=kwargs.get('destdir', None))
return self.AddTDef(tdef)
except:
print_exc()
return False