forked from Tribler/tribler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommunity.py
1275 lines (1067 loc) · 61.7 KB
/
community.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
import json
import logging
from binascii import hexlify
from struct import pack
from time import time
from traceback import print_stack
from twisted.python.threadable import isInIOThread
from Tribler.Core.CacheDB.sqlitecachedb import str2bin
from Tribler.community.channel.payload import ModerationPayload
from Tribler.dispersy.authentication import MemberAuthentication, NoAuthentication
from Tribler.dispersy.candidate import CANDIDATE_WALK_LIFETIME
from Tribler.dispersy.community import Community
from Tribler.dispersy.conversion import DefaultConversion
from Tribler.dispersy.destination import CandidateDestination, CommunityDestination
from Tribler.dispersy.distribution import FullSyncDistribution, DirectDistribution
from Tribler.dispersy.message import BatchConfiguration, Message, DropMessage, DelayMessageByProof
from Tribler.dispersy.resolution import LinearResolution, PublicResolution, DynamicResolution
from Tribler.dispersy.util import call_on_reactor_thread
from .conversion import ChannelConversion
from .message import DelayMessageReqChannelMessage
from .payload import (ChannelPayload, TorrentPayload, PlaylistPayload, CommentPayload, ModificationPayload,
PlaylistTorrentPayload, MissingChannelPayload, MarkTorrentPayload)
from Tribler.community.bartercast4.statistics import BartercastStatisticTypes, _barter_statistics
logger = logging.getLogger(__name__)
METADATA_TYPES = [u'name', u'description', u'swift-url', u'swift-thumbnails', u'video-info', u'metadata-json']
def warnIfNotDispersyThread(func):
def invoke_func(*args, **kwargs):
if not isInIOThread():
logger.critical("This method MUST be called on the DispersyThread")
print_stack()
return None
else:
return func(*args, **kwargs)
invoke_func.__name__ = func.__name__
return invoke_func
class ChannelCommunity(Community):
"""
Each user owns zero or more ChannelCommunities that other can join and use to discuss.
"""
def __init__(self, *args, **kwargs):
super(ChannelCommunity, self).__init__(*args, **kwargs)
self._channel_id = None
self._channel_name = None
self._channel_description = None
self.tribler_session = None
self.integrate_with_tribler = None
self._peer_db = None
self._channelcast_db = None
def initialize(self, tribler_session=None):
self.tribler_session = tribler_session
self.integrate_with_tribler = tribler_session is not None
super(ChannelCommunity, self).initialize()
if self.integrate_with_tribler:
from Tribler.Core.simpledefs import NTFY_PEERS, NTFY_CHANNELCAST
# tribler channelcast database
self._peer_db = tribler_session.open_dbhandler(NTFY_PEERS)
self._channelcast_db = tribler_session.open_dbhandler(NTFY_CHANNELCAST)
# tribler channel_id
result = self._channelcast_db._db.fetchone(
u"SELECT id, name, description FROM Channels WHERE dispersy_cid = ? and (peer_id <> -1 or peer_id ISNULL)",
(buffer(self._master_member.mid),
))
if result is not None:
self._channel_id, self._channel_name, self._channel_description = result
else:
try:
message = self._get_latest_channel_message()
if message:
self._channel_id = self.cid
except:
pass
from Tribler.community.allchannel.community import AllChannelCommunity
for community in self.dispersy.get_communities():
if isinstance(community, AllChannelCommunity):
self._channelcast_db = community._channelcast_db
def initiate_meta_messages(self):
batch_delay = 3.0
# 30/11/11 Boudewijn: we frequently see dropped packets when joining a channel. this can be
# caused when a sync results in both torrent and modification messages. when the
# modification messages are processed first they will all cause the associated torrent
# message to be requested, when these are received they are duplicates. solution: ensure
# that the modification messages are processed after messages that they can request. normal
# priority is 128, therefore, modification_priority is one less
modification_priority = 128 - 1
return super(ChannelCommunity, self).initiate_meta_messages() + [
Message(self, u"channel",
MemberAuthentication(),
LinearResolution(),
FullSyncDistribution(enable_sequence_number=False, synchronization_direction=u"DESC", priority=130),
CommunityDestination(node_count=10),
ChannelPayload(),
self._disp_check_channel,
self._disp_on_channel),
Message(self, u"torrent",
MemberAuthentication(),
DynamicResolution(LinearResolution(), PublicResolution()),
FullSyncDistribution(enable_sequence_number=False, synchronization_direction=u"DESC", priority=129),
CommunityDestination(node_count=10),
TorrentPayload(),
self._disp_check_torrent,
self._disp_on_torrent,
self._disp_undo_torrent,
batch=BatchConfiguration(max_window=batch_delay)),
Message(self, u"playlist",
MemberAuthentication(),
LinearResolution(),
FullSyncDistribution(enable_sequence_number=False, synchronization_direction=u"DESC", priority=128),
CommunityDestination(node_count=10),
PlaylistPayload(),
self._disp_check_playlist,
self._disp_on_playlist,
self._disp_undo_playlist,
batch=BatchConfiguration(max_window=batch_delay)),
Message(self, u"comment",
MemberAuthentication(),
DynamicResolution(LinearResolution(), PublicResolution()),
FullSyncDistribution(enable_sequence_number=False, synchronization_direction=u"DESC", priority=128),
CommunityDestination(node_count=10),
CommentPayload(),
self._disp_check_comment,
self._disp_on_comment,
self._disp_undo_comment,
batch=BatchConfiguration(max_window=batch_delay)),
Message(self, u"modification",
MemberAuthentication(),
DynamicResolution(LinearResolution(), PublicResolution()),
FullSyncDistribution(enable_sequence_number=False,
synchronization_direction=u"DESC",
priority=modification_priority),
CommunityDestination(node_count=10),
ModificationPayload(),
self._disp_check_modification,
self._disp_on_modification,
self._disp_undo_modification,
batch=BatchConfiguration(max_window=batch_delay)),
Message(self, u"playlist_torrent",
MemberAuthentication(),
DynamicResolution(LinearResolution(), PublicResolution()),
FullSyncDistribution(enable_sequence_number=False, synchronization_direction=u"DESC", priority=128),
CommunityDestination(node_count=10),
PlaylistTorrentPayload(),
self._disp_check_playlist_torrent,
self._disp_on_playlist_torrent,
self._disp_undo_playlist_torrent,
batch=BatchConfiguration(max_window=batch_delay)),
Message(self, u"moderation",
MemberAuthentication(),
DynamicResolution(LinearResolution(), PublicResolution()),
FullSyncDistribution(enable_sequence_number=False, synchronization_direction=u"DESC", priority=128),
CommunityDestination(node_count=10),
ModerationPayload(),
self._disp_check_moderation,
self._disp_on_moderation,
self._disp_undo_moderation,
batch=BatchConfiguration(max_window=batch_delay)),
Message(self, u"mark_torrent",
MemberAuthentication(),
DynamicResolution(LinearResolution(), PublicResolution()),
FullSyncDistribution(enable_sequence_number=False, synchronization_direction=u"DESC", priority=128),
CommunityDestination(node_count=10),
MarkTorrentPayload(),
self._disp_check_mark_torrent,
self._disp_on_mark_torrent,
self._disp_undo_mark_torrent,
batch=BatchConfiguration(max_window=batch_delay)),
Message(self, u"missing-channel",
NoAuthentication(),
PublicResolution(),
DirectDistribution(),
CandidateDestination(),
MissingChannelPayload(),
self._disp_check_missing_channel,
self._disp_on_missing_channel),
]
@property
def dispersy_sync_response_limit(self):
return 25 * 1024
def initiate_conversions(self):
return [DefaultConversion(self), ChannelConversion(self)]
CHANNEL_CLOSED, CHANNEL_SEMI_OPEN, CHANNEL_OPEN, CHANNEL_MODERATOR = range(4)
CHANNEL_ALLOWED_MESSAGES = ([],
[u"comment", u"mark_torrent"],
[u"torrent",
u"comment",
u"modification",
u"playlist_torrent",
u"moderation",
u"mark_torrent"],
[u"channel",
u"torrent",
u"playlist",
u"comment",
u"modification",
u"playlist_torrent",
u"moderation",
u"mark_torrent"])
def get_channel_id(self):
return self._channel_id
def get_channel_name(self):
return self._channel_name
def get_channel_description(self):
return self._channel_description
def get_channel_mode(self):
public = set()
permitted = set()
for meta in self.get_meta_messages():
if isinstance(meta.resolution, DynamicResolution):
policy, _ = self._timeline.get_resolution_policy(meta, self.global_time + 1)
else:
policy = meta.resolution
if isinstance(policy, PublicResolution):
public.add(meta.name)
else:
allowed, _ = self._timeline.allowed(meta)
if allowed:
permitted.add(meta.name)
def isCommunityType(state, checkPermitted=False):
for type in ChannelCommunity.CHANNEL_ALLOWED_MESSAGES[state]:
if type not in public:
if checkPermitted and type in permitted:
continue
return False
return True
isModerator = isCommunityType(ChannelCommunity.CHANNEL_MODERATOR, True)
if isCommunityType(ChannelCommunity.CHANNEL_OPEN):
return ChannelCommunity.CHANNEL_OPEN, isModerator
if isCommunityType(ChannelCommunity.CHANNEL_SEMI_OPEN):
return ChannelCommunity.CHANNEL_SEMI_OPEN, isModerator
return ChannelCommunity.CHANNEL_CLOSED, isModerator
def set_channel_mode(self, mode):
curmode, isModerator = self.get_channel_mode()
if isModerator and mode != curmode:
public_messages = ChannelCommunity.CHANNEL_ALLOWED_MESSAGES[mode]
new_policies = []
for meta in self.get_meta_messages():
if isinstance(meta.resolution, DynamicResolution):
if meta.name in public_messages:
new_policies.append((meta, meta.resolution.policies[1]))
else:
new_policies.append((meta, meta.resolution.policies[0]))
self.create_dynamic_settings(new_policies)
def create_channel(self, name, description, store=True, update=True, forward=True):
self._disp_create_channel(name, description, store, update, forward)
@call_on_reactor_thread
def _disp_create_channel(self, name, description, store=True, update=True, forward=True):
name = unicode(name[:255])
description = unicode(description[:1023])
meta = self.get_meta_message(u"channel")
message = meta.impl(authentication=(self._my_member,),
distribution=(self.claim_global_time(),),
payload=(name, description))
self._dispersy.store_update_forward([message], store, update, forward)
return message
def _disp_check_channel(self, messages):
for message in messages:
accepted, proof = self._timeline.check(message)
if not accepted:
yield DelayMessageByProof(message)
continue
yield message
def _disp_on_channel(self, messages):
if self.integrate_with_tribler:
for message in messages:
assert self._cid == self._master_member.mid
logger.debug("%s %s", message.candidate, self._cid.encode("HEX"))
authentication_member = message.authentication.member
if authentication_member == self._my_member:
peer_id = None
else:
peer_id = self._peer_db.addOrGetPeerID(authentication_member.public_key)
self._channel_id = self._channelcast_db.on_channel_from_dispersy(self._master_member.mid,
peer_id,
message.payload.name,
message.payload.description)
# emit signal of channel creation if the channel is created by us
if authentication_member == self._my_member:
self._channel_name = message.payload.name
self._channel_description = message.payload.description
from Tribler.Core.simpledefs import SIGNAL_CHANNEL, SIGNAL_ON_CREATED
channel_data = {u'channel': self,
u'name': message.payload.name,
u'description': message.payload.description}
self.tribler_session.notifier.notify(SIGNAL_CHANNEL, SIGNAL_ON_CREATED, None, channel_data)
else:
for message in messages:
self._channel_id = self._master_member.mid
authentication_member = message.authentication.member
self._channelcast_db.setChannelId(self._channel_id, authentication_member == self._my_member)
def _disp_create_torrent_from_torrentdef(self, torrentdef, timestamp, store=True, update=True, forward=True):
files = torrentdef.get_files_as_unicode_with_length()
return (self._disp_create_torrent(torrentdef.get_infohash(), timestamp,
torrentdef.get_name_as_unicode(), tuple(files),
torrentdef.get_trackers_as_single_tuple(), store, update, forward))
def _disp_create_torrent(self, infohash, timestamp, name, files, trackers, store=True, update=True, forward=True):
meta = self.get_meta_message(u"torrent")
global_time = self.claim_global_time()
current_policy, _ = self._timeline.get_resolution_policy(meta, global_time)
message = meta.impl(authentication=(self._my_member,),
resolution=(current_policy.implement(),),
distribution=(global_time,),
payload=(infohash, timestamp, name, files, trackers))
self._dispersy.store_update_forward([message], store, update, forward)
return message
def _disp_create_torrents(self, torrentlist, store=True, update=True, forward=True):
messages = []
meta = self.get_meta_message(u"torrent")
current_policy, _ = self._timeline.get_resolution_policy(meta, self.global_time + 1)
for infohash, timestamp, name, files, trackers in torrentlist:
message = meta.impl(authentication=(self._my_member,),
resolution=(current_policy.implement(),),
distribution=(self.claim_global_time(),),
payload=(infohash, timestamp, name, files, trackers))
messages.append(message)
self._dispersy.store_update_forward(messages, store, update, forward)
return messages
def _disp_check_torrent(self, messages):
for message in messages:
if not self._channel_id:
yield DelayMessageReqChannelMessage(message)
continue
accepted, proof = self._timeline.check(message)
if not accepted:
yield DelayMessageByProof(message)
continue
yield message
def _disp_on_torrent(self, messages):
if self.integrate_with_tribler:
torrentlist = []
for message in messages:
dispersy_id = message.packet_id
authentication_member = message.authentication.member
if authentication_member == self._my_member:
peer_id = None
else:
peer_id = self._peer_db.addOrGetPeerID(authentication_member.public_key)
# sha_other_peer = (sha1(str(message.candidate.sock_addr) + self.my_member.mid))
torrentlist.append(
(self._channel_id,
dispersy_id,
peer_id,
message.payload.infohash,
message.payload.timestamp,
message.payload.name,
message.payload.files,
message.payload.trackers))
self._logger.debug("torrent received: %s on channel: %s", hexlify(message.payload.infohash), self._master_member)
if message.candidate and message.candidate.sock_addr:
_barter_statistics.dict_inc_bartercast(
BartercastStatisticTypes.TORRENTS_RECEIVED,
# sha_other_peer)
"%s:%s" % (message.candidate.sock_addr[0], message.candidate.sock_addr[1]))
self._channelcast_db.on_torrents_from_dispersy(torrentlist)
else:
for message in messages:
self._channelcast_db.newTorrent(message)
self._logger.debug("torrent received: %s on channel: %s", message.payload.infohash, self._master_member)
if message.candidate and message.candidate.sock_addr:
_barter_statistics.dict_inc_bartercast(BartercastStatisticTypes.TORRENTS_RECEIVED,
"%s:%s" % (message.candidate.sock_addr[0], message.candidate.sock_addr[1]))
def _disp_undo_torrent(self, descriptors, redo=False):
for _, _, packet in descriptors:
dispersy_id = packet.packet_id
self._channelcast_db.on_remove_torrent_from_dispersy(self._channel_id, dispersy_id, redo)
def remove_torrents(self, dispersy_ids):
for dispersy_id in dispersy_ids:
message = self._dispersy.load_message_by_packetid(self, dispersy_id)
if message:
if not message.undone:
self.create_undo(message)
else: # hmm signal gui that this message has been removed already
self._disp_undo_torrent([(None, None, message)])
def remove_playlists(self, dispersy_ids):
for dispersy_id in dispersy_ids:
message = self._dispersy.load_message_by_packetid(self, dispersy_id)
if message:
if not message.undone:
self.create_undo(message)
else: # hmm signal gui that this message has been removed already
self._disp_undo_playlist([(None, None, message)])
# create, check or receive playlists
@call_on_reactor_thread
def create_playlist(self, name, description, infohashes=[], store=True, update=True, forward=True):
message = self._disp_create_playlist(name, description)
if len(infohashes) > 0:
self._disp_create_playlist_torrents(message, infohashes, store, update, forward)
@call_on_reactor_thread
def _disp_create_playlist(self, name, description, store=True, update=True, forward=True):
name = unicode(name[:255])
description = unicode(description[:1023])
meta = self.get_meta_message(u"playlist")
message = meta.impl(authentication=(self._my_member,),
distribution=(self.claim_global_time(),),
payload=(name, description))
self._dispersy.store_update_forward([message], store, update, forward)
return message
def _disp_check_playlist(self, messages):
for message in messages:
if not self._channel_id:
yield DelayMessageReqChannelMessage(message)
continue
accepted, proof = self._timeline.check(message)
if not accepted:
yield DelayMessageByProof(message)
continue
yield message
def _disp_on_playlist(self, messages):
if self.integrate_with_tribler:
for message in messages:
dispersy_id = message.packet_id
authentication_member = message.authentication.member
if authentication_member == self._my_member:
peer_id = None
else:
peer_id = self._peer_db.addOrGetPeerID(authentication_member.public_key)
self._channelcast_db.on_playlist_from_dispersy(self._channel_id,
dispersy_id,
peer_id,
message.payload.name,
message.payload.description)
def _disp_undo_playlist(self, descriptors, redo=False):
if self.integrate_with_tribler:
for _, _, packet in descriptors:
dispersy_id = packet.packet_id
self._channelcast_db.on_remove_playlist_from_dispersy(self._channel_id, dispersy_id, redo)
# create, check or receive comments
@call_on_reactor_thread
def create_comment(self, text, timestamp, reply_to, reply_after, playlist_id, infohash, store=True, update=True,
forward=True):
reply_to_message = reply_to
reply_after_message = reply_after
playlist_message = playlist_id
if reply_to:
reply_to_message = self._dispersy.load_message_by_packetid(self, reply_to)
if reply_after:
reply_after_message = self._dispersy.load_message_by_packetid(self, reply_after)
if playlist_id:
playlist_message = self._get_message_from_playlist_id(playlist_id)
self._disp_create_comment(text, timestamp, reply_to_message,
reply_after_message, playlist_message,
infohash, store, update, forward)
@call_on_reactor_thread
def _disp_create_comment(self, text, timestamp, reply_to_message, reply_after_message, playlist_message, infohash,
store=True, update=True, forward=True):
reply_to_mid = None
reply_to_global_time = None
if reply_to_message:
message = reply_to_message.load_message()
reply_to_mid = message.authentication.member.mid
reply_to_global_time = message.distribution.global_time
reply_after_mid = None
reply_after_global_time = None
if reply_after_message:
message = reply_after_message.load_message()
reply_after_mid = message.authentication.member.mid
reply_after_global_time = message.distribution.global_time
text = unicode(text[:1023])
meta = self.get_meta_message(u"comment")
global_time = self.claim_global_time()
current_policy, _ = self._timeline.get_resolution_policy(meta, global_time)
message = meta.impl(authentication=(self._my_member,),
resolution=(current_policy.implement(),),
distribution=(global_time,), payload=(text,
timestamp, reply_to_mid, reply_to_global_time,
reply_after_mid, reply_after_global_time,
playlist_message, infohash))
self._dispersy.store_update_forward([message], store, update, forward)
return message
def _disp_check_comment(self, messages):
for message in messages:
if not self._channel_id:
yield DelayMessageReqChannelMessage(message)
continue
accepted, proof = self._timeline.check(message)
if not accepted:
yield DelayMessageByProof(message)
continue
yield message
def _disp_on_comment(self, messages):
if self.integrate_with_tribler:
for message in messages:
dispersy_id = message.packet_id
authentication_member = message.authentication.member
if authentication_member == self._my_member:
peer_id = None
else:
peer_id = self._peer_db.addOrGetPeerID(authentication_member.public_key)
mid_global_time = pack('!20sQ', message.authentication.member.mid, message.distribution.global_time)
reply_to_id = None
if message.payload.reply_to_mid:
try:
reply_to_id = self._get_packet_id(
message.payload.reply_to_global_time,
message.payload.reply_to_mid)
except:
reply_to_id = pack('!20sQ', message.payload.reply_to_mid, message.payload.reply_to_global_time)
reply_after_id = None
if message.payload.reply_after_mid:
try:
reply_after_id = self._get_packet_id(
message.payload.reply_after_global_time,
message.payload.reply_after_mid)
except:
reply_after_id = pack(
'!20sQ',
message.payload.reply_after_mid,
message.payload.reply_after_global_time)
playlist_dispersy_id = None
if message.payload.playlist_packet:
playlist_dispersy_id = message.payload.playlist_packet.packet_id
self._channelcast_db.on_comment_from_dispersy(self._channel_id,
dispersy_id,
mid_global_time,
peer_id,
message.payload.text,
message.payload.timestamp,
reply_to_id,
reply_after_id,
playlist_dispersy_id,
message.payload.infohash)
def _disp_undo_comment(self, descriptors, redo=False):
if self.integrate_with_tribler:
for _, _, packet in descriptors:
dispersy_id = packet.packet_id
message = packet.load_message()
infohash = message.payload.infohash
self._channelcast_db.on_remove_comment_from_dispersy(self._channel_id, dispersy_id, infohash, redo)
def remove_comment(self, dispersy_id):
message = self._dispersy.load_message_by_packetid(self, dispersy_id)
if message:
self.create_undo(message)
# modify channel, playlist or torrent
@call_on_reactor_thread
def modifyChannel(self, modifications, store=True, update=True, forward=True):
latest_modifications = {}
for type, value in modifications.iteritems():
type = unicode(type)
latest_modifications[type] = self._get_latest_modification_from_channel_id(type)
modification_on_message = self._get_latest_channel_message()
for type, value in modifications.iteritems():
type = unicode(type)
timestamp = long(time())
self._disp_create_modification(type, value, timestamp,
modification_on_message,
latest_modifications[type], store,
update, forward)
@call_on_reactor_thread
def modifyPlaylist(self, playlist_id, modifications, store=True, update=True, forward=True):
latest_modifications = {}
for type, value in modifications.iteritems():
type = unicode(type)
latest_modifications[type] = self._get_latest_modification_from_playlist_id(playlist_id, type)
modification_on_message = self._get_message_from_playlist_id(playlist_id)
for type, value in modifications.iteritems():
type = unicode(type)
timestamp = long(time())
self._disp_create_modification(type, value, timestamp,
modification_on_message,
latest_modifications[type], store,
update, forward)
@call_on_reactor_thread
def modifyTorrent(self, channeltorrent_id, modifications, store=True, update=True, forward=True):
latest_modifications = {}
for type, value in modifications.iteritems():
type = unicode(type)
try:
latest_modifications[type] = self._get_latest_modification_from_torrent_id(channeltorrent_id, type)
except:
logger.error(exc_info=True)
modification_on_message = self._get_message_from_torrent_id(channeltorrent_id)
for type, value in modifications.iteritems():
timestamp = long(time())
self._disp_create_modification(type, value, timestamp,
modification_on_message,
latest_modifications[type], store,
update, forward)
def _disp_create_modification(self, modification_type, modifcation_value, timestamp, modification_on,
latest_modification, store=True, update=True, forward=True):
modification_type = unicode(modification_type)
modifcation_value = unicode(modifcation_value[:1023])
latest_modification_mid = None
latest_modification_global_time = None
if latest_modification:
message = latest_modification.load_message()
latest_modification_mid = message.authentication.member.mid
latest_modification_global_time = message.distribution.global_time
meta = self.get_meta_message(u"modification")
global_time = self.claim_global_time()
current_policy, _ = self._timeline.get_resolution_policy(meta, global_time)
message = meta.impl(authentication=(self._my_member,),
resolution=(current_policy.implement(),),
distribution=(global_time,),
payload=(modification_type, modifcation_value,
timestamp, modification_on, latest_modification,
latest_modification_mid,
latest_modification_global_time))
self._dispersy.store_update_forward([message], store, update, forward)
return message
def _disp_check_modification(self, messages):
th_handler = self.tribler_session.lm.rtorrent_handler
for message in messages:
if not self._channel_id:
yield DelayMessageReqChannelMessage(message)
continue
accepted, proof = self._timeline.check(message)
if not accepted:
yield DelayMessageByProof(message)
continue
if message.payload.modification_on.name == u"torrent" and message.payload.modification_type == u"metadata-json":
try:
data = json.loads(message.payload.modification_value)
thumbnail_hash = data[u'thumb_hash'].decode('hex')
except:
yield DropMessage(message, "Not compatible json format")
continue
else:
modifying_dispersy_id = message.payload.modification_on.packet_id
torrent_id = self._channelcast_db._db.fetchone(
u"SELECT torrent_id FROM _ChannelTorrents WHERE dispersy_id = ?",
(modifying_dispersy_id,))
infohash = self._channelcast_db._db.fetchone(
u"SELECT infohash FROM Torrent WHERE torrent_id = ?", (torrent_id,))
if infohash:
infohash = str2bin(infohash)
logger.debug(
"Incoming metadata-json with infohash %s from %s",
infohash.encode("HEX"),
message.candidate.sock_addr[0])
if not th_handler.has_metadata(thumbnail_hash):
@call_on_reactor_thread
def callback(_, message=message):
self.on_messages([message])
logger.debug(
"Will try to download metadata-json thumbnail with infohash %s from %s",
infohash.encode("HEX"),
message.candidate.sock_addr[0])
th_handler.download_metadata(message.candidate, thumbnail_hash, usercallback=callback,
timeout=CANDIDATE_WALK_LIFETIME)
continue
yield message
def _disp_on_modification(self, messages):
if self.integrate_with_tribler:
channeltorrentDict = {}
playlistDict = {}
for message in messages:
dispersy_id = message.packet_id
message_name = message.payload.modification_on.name
mid_global_time = "%s@%d" % (message.authentication.member.mid, message.distribution.global_time)
modifying_dispersy_id = message.payload.modification_on.packet_id
modification_type = unicode(message.payload.modification_type)
modification_value = message.payload.modification_value
timestamp = message.payload.timestamp
if message.payload.prev_modification_packet:
prev_modification_id = message.payload.prev_modification_packet.packet_id
else:
prev_modification_id = message.payload.prev_modification_id
prev_modification_global_time = message.payload.prev_modification_global_time
# load local ids from database
if message_name == u"torrent":
channeltorrent_id = self._get_torrent_id_from_message(modifying_dispersy_id)
if not channeltorrent_id:
self._logger.info("CANNOT FIND channeltorrent_id %s", modifying_dispersy_id)
channeltorrentDict[modifying_dispersy_id] = channeltorrent_id
elif message_name == u"playlist":
playlist_id = self._get_playlist_id_from_message(modifying_dispersy_id)
playlistDict[modifying_dispersy_id] = playlist_id
authentication_member = message.authentication.member
if authentication_member == self._my_member:
peer_id = None
else:
peer_id = self._peer_db.addOrGetPeerID(authentication_member.public_key)
# always store metadata
self._channelcast_db.on_metadata_from_dispersy(message_name,
channeltorrentDict.get(modifying_dispersy_id, None),
playlistDict.get(modifying_dispersy_id, None),
self._channel_id,
dispersy_id,
peer_id,
mid_global_time,
modification_type,
modification_value,
timestamp,
prev_modification_id,
prev_modification_global_time)
for message in messages:
dispersy_id = message.packet_id
message_name = message.payload.modification_on.name
modifying_dispersy_id = message.payload.modification_on.packet_id
modification_type = unicode(message.payload.modification_type)
modification_value = message.payload.modification_value
# see if this is new information, if so call on_X_from_dispersy to update local 'cached' information
if message_name == u"torrent":
channeltorrent_id = channeltorrentDict[modifying_dispersy_id]
if channeltorrent_id:
latest = self._get_latest_modification_from_torrent_id(channeltorrent_id, modification_type)
if not latest or latest.packet_id == dispersy_id:
self._channelcast_db.on_torrent_modification_from_dispersy(
channeltorrent_id, modification_type, modification_value)
elif message_name == u"playlist":
playlist_id = playlistDict[modifying_dispersy_id]
latest = self._get_latest_modification_from_playlist_id(playlist_id, modification_type)
if not latest or latest.packet_id == dispersy_id:
self._channelcast_db.on_playlist_modification_from_dispersy(
playlist_id, modification_type, modification_value)
elif message_name == u"channel":
latest = self._get_latest_modification_from_channel_id(modification_type)
if not latest or latest.packet_id == dispersy_id:
self._channelcast_db.on_channel_modification_from_dispersy(
self._channel_id, modification_type, modification_value)
def _disp_undo_modification(self, descriptors, redo=False):
if self.integrate_with_tribler:
for _, _, packet in descriptors:
dispersy_id = packet.packet_id
message = packet.load_message()
message_name = message.name
modifying_dispersy_id = message.payload.modification_on.packet_id
modification_type = unicode(message.payload.modification_type)
# load local ids from database
playlist_id = channeltorrent_id = None
if message_name == u"torrent":
channeltorrent_id = self._get_torrent_id_from_message(modifying_dispersy_id)
elif message_name == u"playlist":
playlist_id = self._get_playlist_id_from_message(modifying_dispersy_id)
self._channelcast_db.on_remove_metadata_from_dispersy(self._channel_id, dispersy_id, redo)
if message_name == u"torrent":
latest = self._get_latest_modification_from_torrent_id(channeltorrent_id, modification_type)
if not latest or latest.packet_id == dispersy_id:
modification_value = latest.payload.modification_value if latest else ''
self._channelcast_db.on_torrent_modification_from_dispersy(
channeltorrent_id, modification_type, modification_value)
elif message_name == u"playlist":
latest = self._get_latest_modification_from_playlist_id(playlist_id, modification_type)
if not latest or latest.packet_id == dispersy_id:
modification_value = latest.payload.modification_value if latest else ''
self._channelcast_db.on_playlist_modification_from_dispersy(
playlist_id, modification_type, modification_value)
elif message_name == u"channel":
latest = self._get_latest_modification_from_channel_id(modification_type)
if not latest or latest.packet_id == dispersy_id:
modification_value = latest.payload.modification_value if latest else ''
self._channelcast_db.on_channel_modification_from_dispersy(
self._channel_id, modification_type, modification_value)
# create, check or receive playlist_torrent messages
@call_on_reactor_thread
def create_playlist_torrents(self, playlist_id, infohashes, store=True, update=True, forward=True):
playlist_packet = self._get_message_from_playlist_id(playlist_id)
self._disp_create_playlist_torrents(playlist_packet, infohashes, store, update, forward)
def remove_playlist_torrents(self, playlist_id, dispersy_ids):
for dispersy_id in dispersy_ids:
message = self._dispersy.load_message_by_packetid(self, dispersy_id)
if message:
self.create_undo(message)
@call_on_reactor_thread
def _disp_create_playlist_torrents(self, playlist_packet, infohashes, store=True, update=True, forward=True):
meta = self.get_meta_message(u"playlist_torrent")
current_policy, _ = self._timeline.get_resolution_policy(meta, self.global_time + 1)
messages = []
for infohash in infohashes:
message = meta.impl(authentication=(self._my_member,),
resolution=(current_policy.implement(),),
distribution=(self.claim_global_time(),),
payload=(infohash, playlist_packet))
messages.append(message)
self._dispersy.store_update_forward(messages, store, update, forward)
return message
def _disp_check_playlist_torrent(self, messages):
for message in messages:
if not self._channel_id:
yield DelayMessageReqChannelMessage(message)
continue
accepted, proof = self._timeline.check(message)
if not accepted:
yield DelayMessageByProof(message)
yield message
def _disp_on_playlist_torrent(self, messages):
if self.integrate_with_tribler:
for message in messages:
dispersy_id = message.packet_id
playlist_dispersy_id = message.payload.playlist.packet_id
authentication_member = message.authentication.member
if authentication_member == self._my_member:
peer_id = None
else:
peer_id = self._peer_db.addOrGetPeerID(authentication_member.public_key)
self._channelcast_db.on_playlist_torrent(dispersy_id,
playlist_dispersy_id,
peer_id,
message.payload.infohash)
def _disp_undo_playlist_torrent(self, descriptors, redo=False):
if self.integrate_with_tribler:
for _, _, packet in descriptors:
message = packet.load_message()
infohash = message.payload.infohash
playlist_dispersy_id = message.payload.playlist.packet_id
self._channelcast_db.on_remove_playlist_torrent(self._channel_id, playlist_dispersy_id, infohash, redo)
# check or receive moderation messages
@call_on_reactor_thread
def _disp_create_moderation(self, text, timestamp, severity, cause, store=True, update=True, forward=True):
causemessage = self._dispersy.load_message_by_packetid(self, cause)
if causemessage:
text = unicode(text[:1023])
meta = self.get_meta_message(u"moderation")
global_time = self.claim_global_time()
current_policy, _ = self._timeline.get_resolution_policy(meta, global_time)
message = meta.impl(authentication=(self._my_member,),
resolution=(current_policy.implement(),),
distribution=(global_time,),
payload=(text, timestamp, severity, causemessage))
self._dispersy.store_update_forward([message], store, update, forward)
return message
def _disp_check_moderation(self, messages):
for message in messages:
if not self._channel_id:
yield DelayMessageReqChannelMessage(message)
continue
accepted, proof = self._timeline.check(message)
if not accepted:
yield DelayMessageByProof(message)
yield message
def _disp_on_moderation(self, messages):
if self.integrate_with_tribler:
for message in messages:
dispersy_id = message.packet_id
authentication_member = message.authentication.member
if authentication_member == self._my_member:
peer_id = None
else:
peer_id = self._peer_db.addOrGetPeerID(authentication_member.public_key)
# if cause packet is present, it is enforced by conversion
cause = message.payload.causepacket.packet_id
cause_message = message.payload.causepacket.load_message()
authentication_member = cause_message.authentication.member
if authentication_member == self._my_member:
by_peer_id = None
else:
by_peer_id = self._peer_db.addOrGetPeerID(authentication_member.public_key)
# determine if we are reverting latest
updateTorrent = False
modifying_dispersy_id = cause_message.payload.modification_on.packet_id
channeltorrent_id = self._get_torrent_id_from_message(modifying_dispersy_id)
if channeltorrent_id:
modification_type = unicode(cause_message.payload.modification_type)
latest = self._get_latest_modification_from_torrent_id(channeltorrent_id, modification_type)
if not latest or latest.packet_id == cause_message.packet_id: