-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathipfs_datatransmission.py
More file actions
executable file
·1791 lines (1599 loc) · 73.1 KB
/
ipfs_datatransmission.py
File metadata and controls
executable file
·1791 lines (1599 loc) · 73.1 KB
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
"""
This is a module that enables the user to transmit and receive transmissions of data over the Interplanetary File System's P2P network (libp2p).
To use it you must have IPFS running on your computer.
Configure IPFS to enable all this:
ipfs config --json Experimental.Libp2pStreamMounting true
"""
# from pdb import set_trace as debug
from ipfs_api import _ipfs_host_ip
import shutil
from queue import Queue, Empty as QueueEmpty
import socket
import threading
from threading import Thread, Event
from datetime import datetime, UTC
import time
import traceback
import os
# import inspect
from inspect import signature
try:
import ipfs_api
except:
import IPFS_API_Remote_Client as ipfs_api
# -------------- Settings ---------------------------------------------------------------------------------------------------
PRINT_LOG = False # whether or not to print debug in output terminal
PRINT_LOG_CONNECTIONS = False
PRINT_LOG_TRANSMISSIONS = False
PRINT_LOG_CONVERSATIONS = False
PRINT_LOG_FILES = True
if not PRINT_LOG:
PRINT_LOG_CONNECTIONS = False
PRINT_LOG_TRANSMISSIONS = False
PRINT_LOG_CONVERSATIONS = False
PRINT_LOG_FILES = False
TRANSM_REQ_MAX_RETRIES = 3
TRANSM_SEND_TIMEOUT_SEC = 10
TRANSM_RECV_TIMEOUT_SEC = 10
BUFFER_SIZE = 4096 # the communication buffer size
# the size of the chunks into which files should be split before transmission
BLOCK_SIZE = 1048576 # 1MiB
sending_ports = [x for x in range(20001, 20500)]
# -------------- User Functions ----------------------------------------------------------------------------------------------
def transmit_data(
data: bytes,
peer_id: str,
req_lis_name: str,
timeout_sec: int = TRANSM_SEND_TIMEOUT_SEC,
max_retries: int = TRANSM_REQ_MAX_RETRIES):
"""
Transmits the input data (a bytearray of any length) to the computer with the specified IPFS peer ID.
Args:
data (bytearray): the data to be transmitted to the receiver
string peer_id (str): the IPFS peer ID of [the recipient computer to send the data to]
string listener_name (str): the name of the IPFS-Data-Transmission-Listener instance running on the recipient computer to send the data to (allows distinguishing multiple IPFS-Data-Transmission-Listeners running on the same computer for different applications)
transm_send_timeout_sec (int): connection attempt timeout, multiplied with the maximum number of retries will result in the total time required for a failed attempt
transm_req_max_retries (int): how often the transmission should be reattempted when the timeout is reached
Returns:
bool: whether or not the transmission succeeded
"""
if peer_id == ipfs_api.my_id():
raise InvalidPeer(
message="You cannot use your own IPFS peer ID as the recipient.")
def SendTransmissionRequest():
"""
Sends transmission request to the recipient.
"""
request_data = __add_integritybyte_to_buffer(ipfs_api.my_id().encode())
tries = 0
# repeatedly try to send transmission request to recipient until a reply is received
while max_retries == -1 or tries < max_retries:
if PRINT_LOG_TRANSMISSIONS:
print("Sending transmission request to " + str(req_lis_name))
sock = _create_sending_connection(peer_id, req_lis_name)
# sock.sendall(request_data)
sock.settimeout(timeout_sec)
_tcp_send_all(sock, request_data)
if PRINT_LOG_TRANSMISSIONS:
print("Sent transmission request to " + str(req_lis_name))
try:
# reply = sock.recv(BUFFER_SIZE)
reply = _tcp_recv_buffer_timeout(sock, BUFFER_SIZE,
timeout=timeout_sec)
except socket.timeout:
sock.close()
_close_sending_connection(peer_id, req_lis_name)
raise CommunicationTimeout(
"Received no response from peer while sending transmission request.")
# reply = _tcp_recv_all(sock, timeout_sec)
# _tcp_recv_all
sock.close()
del sock
_close_sending_connection(peer_id, req_lis_name)
if reply:
try:
their_trsm_port = reply[30:].decode() # signal success
if their_trsm_port:
if PRINT_LOG_TRANSMISSIONS:
print("Transmission request to " +
str(req_lis_name) + "was received.")
return their_trsm_port
else:
raise UnreadableReply()
except:
raise UnreadableReply()
else:
if PRINT_LOG_TRANSMISSIONS:
print("Transmission request send " +
str(req_lis_name) + "timeout_sec reached.")
tries += 1
_close_sending_connection(peer_id, req_lis_name)
raise CommunicationTimeout(
"Received no response from peer while sending transmission request.")
their_trsm_port = SendTransmissionRequest()
sock = _create_sending_connection(peer_id, their_trsm_port)
sock.settimeout(timeout_sec)
# sock.sendall(data) # transmit Data
_tcp_send_all(sock, data)
if PRINT_LOG_TRANSMISSIONS:
print("Sent Transmission Data", data)
response = sock.recv(BUFFER_SIZE)
if response and response == b"Finished!":
# conn.close()
sock.close()
_close_sending_connection(peer_id, their_trsm_port)
if PRINT_LOG_TRANSMISSIONS:
print(": Finished transmission.")
return True # signal success
else:
if PRINT_LOG_TRANSMISSIONS:
print("Received unrecognised response:", response)
raise UnreadableReply()
# sock.close()
# _close_sending_connection(peer_id, their_trsm_port)
def listen_for_transmissions(listener_name, eventhandler):
"""
Listens for incoming transmission requests (senders requesting to transmit
data to us) and sets up the machinery needed to receive those transmissions.
Call `.terminate()` on the returned TransmissionListener object when you
no longer need it to clean up IPFS connection configurations.
Args:
listener_name (str): the name of this TransmissionListener (chosen by
user, allows distinguishing multiple IPFS-DataTransmission-Listeners
running on the same computer for different applications)
eventhandler (function): the function that should be called when a
transmission of data is received
Parameters: data (bytearray), peer_id (str)
Returns:
TramissionListener: listener object which can be terminated with
`.terminate()` or whose `.eventhandler` attribute can be changed.
"""
return TransmissionListener(listener_name, eventhandler)
class TransmissionListener:
"""
Listens for incoming transmission requests (senders requesting to transmit
data to us) and sets up the machinery needed to receive those transmissions.
Call `.terminate()` on TransmissionListener objects when you no longer
need them to clean up IPFS connection configurations.
"""
# This function itself is called to process the transmission request buffer sent by the transmission sender.
_terminate = False
def __init__(self, listener_name, eventhandler):
"""
Args:
listener_name (str): the name of this TransmissionListener (chosen by
user, allows distinguishing multiple IPFS-DataTransmission-Listeners
running on the same computer for different applications)
eventhandler (function): the function that should be called when a transmission of
data is received.
Parameters: data (bytearray), peer_id (str)
"""
self._listener_name = listener_name
self.eventhandler = eventhandler
self.port = 0 # not yet set
self._listener = Thread(target=self._listen, args=(),
name=f"DataTransmissionListener-{listener_name}")
self._listener.start()
def __receive_transmission_requests(self, data):
if PRINT_LOG_TRANSMISSIONS:
print(self._listener_name + ": processing transmission request...")
# decoding the transission request buffer
try:
# Performing buffer integrity check
integrity_byte = data[0]
data = data[1:]
sum = 0
for byte in data:
sum += byte
if sum > 65000: # if the sum is reaching the upper limit of an unsigned 16-bit integer
sum = sum % 256 # reduce the sum to its modulus256 so that the calculation above doesn't take too much processing power in later iterations of this for loop
# if the integrity byte doesn't match the buffer, exit the function ignoring the buffer
if sum % 256 != integrity_byte:
if PRINT_LOG:
print(
self._listener_name + ": Received a buffer with a non-matching integrity buffer")
return
peer_id = data.decode()
if PRINT_LOG_TRANSMISSIONS:
print(
self._listener_name + ": Received transmission request.")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((_ipfs_host_ip(), 0))
our_port = sock.getsockname()[1]
_create_listening_connection(str(our_port), our_port)
sock.listen()
listener = Thread(target=self._receive_transmission, args=(
peer_id, sock, our_port, self.eventhandler), name=f"DataTransmissionReceiver-{our_port}")
listener.start()
return our_port
except Exception as e:
print("")
print(
self._listener_name + ": Exception in NetTerm.ReceiveTransmissions.__receive_transmission_requests()")
print("----------------------------------------------------")
traceback.print_exc() # printing stack trace
print("----------------------------------------------------")
print("")
print(e)
print(self._listener_name + ": Could not decode transmission request.")
def _receive_transmission(self, peer_id, sock, our_port, eventhandler):
#
# sock = _create_sending_connection(peer_id, str(sender_port))
#
# if PRINT_LOG_TRANSMISSIONS:
# print("Ready to receive transmission.")
#
# sock.sendall(b"start transmission")
if PRINT_LOG_TRANSMISSIONS:
print("waiting to receive actual transmission")
conn, addr = sock.accept()
if PRINT_LOG_TRANSMISSIONS:
print("received connection response fro actual transmission")
data = _tcp_recv_all(conn, timeout=TRANSM_RECV_TIMEOUT_SEC)
conn.send("Finished!".encode())
# conn.close()
Thread(target=eventhandler, args=(data, peer_id),
name="TransmissionListener.ReceivedTransmission").start()
_close_listening_connection(str(our_port), our_port)
sock.close()
def _listen(self):
if PRINT_LOG_TRANSMISSIONS:
print("Creating Listener")
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.bind((_ipfs_host_ip(), 0))
self.port = self.socket.getsockname()[1]
_create_listening_connection(self._listener_name, self.port)
if PRINT_LOG_TRANSMISSIONS:
print(self._listener_name
+ ": Listening for transmission requests as " + self._listener_name)
self.socket.listen()
while True:
conn, addr = self.socket.accept()
data = _tcp_recv_all(conn, timeout=TRANSM_RECV_TIMEOUT_SEC)
if self._terminate:
# conn.sendall(b"Righto.")
conn.close()
self.socket.close()
return
port = self.__receive_transmission_requests(data)
if port:
conn.send(f"Transmission request accepted.{port}".encode())
else:
conn.send(b"Transmission request not accepted.")
def terminate(self):
"""Stop listening for transmissions and clean up IPFS connection
configurations."""
# self.socket.unbind(self.port)
if self._terminate:
return
self._terminate = True
# if socket hasn't been initialised yet
if not self.port:
return
_close_listening_connection(self._listener_name, self.port)
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((_ipfs_host_ip(), self.port))
# sock.sendall("close".encode())
_tcp_send_all(sock, "close".encode())
# _tcp_recv_all(sock)
sock.close()
del sock
except:
pass
def __del__(self):
self.terminate()
def start_conversation(conv_name,
peer_id,
others_req_listener,
data_received_eventhandler=None,
file_eventhandler=None,
file_progress_callback=None,
encryption_callbacks=None,
timeout_sec=TRANSM_SEND_TIMEOUT_SEC,
max_retries=TRANSM_REQ_MAX_RETRIES,
dir="."):
"""Starts a conversation object with which 2 peers can repetatively make
data transmissions to each other asynchronously and bidirectionally.
Sends a conversation request to the other peer's conversation request
listener which the other peer must (programmatically) accept (joining the
conversation) in order to start conversing.
Call `.terminate()` on the returned Conversation object when you
no longer need it to clean up IPFS connection configurations.
Args:
conv_name (str): the name of the IPFS port forwarding connection
(IPFS Libp2pStreamMounting protocol)
peer_id (str): the IPFS peer ID of the node to communicate with
others_req_listener (str): the name of the ther peer's conversation
listener object
data_received_eventhandler (function): function to be called when we've
received a data transmission
Parameters: (data:bytearray)
file_eventhandler (function): function to be called when a file is
receive over this conversation
Parameters: (filepath:str, metadata:bytearray)
progress_handler (function): eventhandler to send progress (fraction
twix 0-1) every for sending/receiving files
Parameters: (progress:float)
encryption_callbacks (tuple): encryption and decryption functions
Tuple Contents: two functions which each take a
a bytearray as a parameter and return a bytearray
(
function(plaintext:bytearray):bytearray,
function(cipher:bytearray):bytearray
)
transm_send_timeout_sec (int): (low level) data transmission -
connection attempt timeout, multiplied with the
maximum number of retries will result in the
total time required for a failed attempt
transm_req_max_retries (int): (low level) data transmission -
how often the transmission should be
reattempted when the timeout is reached
dir (str): the path where received files should be downloaded to
Returns:
Conversation: an object through which messages and files can be sent
"""
conv = Conversation()
conv.start(conv_name,
peer_id,
others_req_listener,
data_received_eventhandler,
file_eventhandler=file_eventhandler,
file_progress_callback=file_progress_callback,
encryption_callbacks=encryption_callbacks,
transm_send_timeout_sec=timeout_sec,
transm_req_max_retries=max_retries,
dir=dir
)
return conv
def join_conversation(conv_name,
peer_id,
others_req_listener,
data_received_eventhandler=None,
file_eventhandler=None,
file_progress_callback=None,
encryption_callbacks=None,
timeout_sec=TRANSM_SEND_TIMEOUT_SEC,
max_retries=TRANSM_REQ_MAX_RETRIES,
dir="."):
"""Join a conversation object started by another peer.
Call `.terminate()` on the returned Conversation object when you
no longer need it to clean up IPFS connection configurations.
Args:
conv_name (str): the name of the IPFS port forwarding connection
(IPFS Libp2pStreamMounting protocol)
peer_id (str): the IPFS peer ID of the node to communicate with
others_req_listener (str): the name of the ther peer's conversation
listener object
data_received_eventhandler (function): function to be called when we've
received a data transmission
Parameters: (data:bytearray)
file_eventhandler (function): function to be called when a file is
receive over this conversation
Parameters: (filepath:str, metadata:bytearray)
progress_handler (function): eventhandler to send progress (fraction
twix 0-1) every for sending/receiving files
Parameters: (progress:float)
encryption_callbacks (tuple): encryption and decryption functions
Tuple Contents: two functions which each take a
a bytearray as a parameter and return a bytearray
(
function(plaintext:bytearray):bytearray,
function(cipher:bytearray):bytearray
)
transm_send_timeout_sec (int): (low level) data transmission -
connection attempt timeout, multiplied with the
maximum number of retries will result in the
total time required for a failed attempt
transm_req_max_retries (int): (low level) data transmission -
how often the transmission should be
reattempted when the timeout is reached
dir (str): the path where received files should be downloaded to
Returns:
Conversation: an object through which messages and files can be sent
"""
conv = Conversation()
conv.join(conv_name,
peer_id,
others_req_listener,
data_received_eventhandler,
file_eventhandler=file_eventhandler,
file_progress_callback=file_progress_callback,
encryption_callbacks=encryption_callbacks,
transm_send_timeout_sec=timeout_sec,
transm_req_max_retries=max_retries,
dir=dir
)
return conv
def listen_for_conversations(listener_name: str, eventhandler):
"""
Listen for incoming conversation requests.
Whenever a new conversation request is received, the specified eventhandler
is called which must then decide whether or not to join the conversation,
and then act upon that decision.
Call `.terminate()` on the returned ConversationListener object when you
no longer need it to clean up IPFS connection configurations.
Args:
listener_name (str): the name which this ConversationListener should
have (becomes its IPFS Libp2pStreamMounting protocol)
eventhandler (function): the function to be called when a conversation
request is received
Parameters: (conv_name:str, peer_id:str)
Returns:
ConversationListener: an object which listens for incoming conversation
requests
"""
return ConversationListener(listener_name, eventhandler)
class Conversation:
"""Communication object which allows 2 peers to repetatively make
data transmissions to each other asynchronously and bidirectionally.
"""
conv_name = ""
peer_id = ""
data_received_eventhandler = None
file_eventhandler = None
file_progress_callback = None
_transm_send_timeout_sec = TRANSM_SEND_TIMEOUT_SEC
_transm_req_max_retries = TRANSM_REQ_MAX_RETRIES
_listener = None
__encryption_callback = None
__decryption_callback = None
_terminate = False
_last_coms_time = None
def __init__(self):
self.started = Event()
self._conversation_started = False
self.data_received_eventhandler = None
self.file_listener = None
self.file_eventhandler = None
self.file_progress_callback = None
self.message_queue = Queue()
self._file_queue = Queue()
def start(self,
conv_name,
peer_id,
others_req_listener,
data_received_eventhandler=None,
file_eventhandler=None,
file_progress_callback=None,
encryption_callbacks=None,
transm_send_timeout_sec=_transm_send_timeout_sec,
transm_req_max_retries=_transm_req_max_retries,
dir="."):
"""Initialises this conversation object so that it can be used.
Code execution blocks until the other peer joins the conversation or
timeout is reached.
Args:
conv_name (str): the name of the IPFS port forwarding connection
(IPFS Libp2pStreamMounting protocol)
peer_id (str): the IPFS peer ID of the node to communicate with
others_req_listener (str): the name of the ther peer's conversation
listener object
data_received_eventhandler (function): function to be called when
we've received a data transmission
Parameters: (data:bytearray)
file_eventhandler (function): function to be called when a file is
receive over this conversation
Parameters: (filepath:str, metadata:bytearray)
progress_handler (function): eventhandler to send progress (float
twix 0-1) every for sending/receiving files
Parameters: (progress:float)
encryption_callbacks (tuple): encryption and decryption functions
Tuple Contents: two functions which each take a
a bytearray as a parameter and return a bytearray
(
function(plaintext:bytearray):bytearray,
function(cipher:bytearray):bytearray
)
transm_send_timeout_sec (int): (low level) data transmission
connection attempt timeout, multiplied with the
maximum number of retries will result in the
total time required for a failed attempt
transm_req_max_retries (int): (low level) data
transmission how often the transmission should be
reattempted when the timeout is reached
dir (str): the path where received files should be downloaded to
"""
if peer_id == ipfs_api.my_id():
raise InvalidPeer(
message="You cannot use your own IPFS peer ID as your conversation partner.")
if (PRINT_LOG_CONVERSATIONS):
print(conv_name + ": Starting conversation")
self.conv_name = conv_name
self.data_received_eventhandler = data_received_eventhandler
self.file_eventhandler = file_eventhandler
self.file_progress_callback = file_progress_callback
if encryption_callbacks:
self.__encryption_callback = encryption_callbacks[0]
self.__decryption_callback = encryption_callbacks[1]
self._transm_send_timeout_sec = transm_send_timeout_sec
self._transm_req_max_retries = transm_req_max_retries
self.peer_id = peer_id
if PRINT_LOG_CONVERSATIONS:
print(conv_name + ": sending conversation request")
self._listener = listen_for_transmissions(conv_name,
self._hear
)
self.file_listener = listen_for_file_transmissions(
f"{conv_name}:files",
self._file_received,
progress_handler=self._on_file_progress_received,
dir=dir,
encryption_callbacks=encryption_callbacks
)
# self._listener = listen_for_transmissions(conv_name, self.hear_eventhandler)
data = bytearray("I want to start a conversation".encode(
'utf-8')) + bytearray([255]) + bytearray(conv_name.encode('utf-8'))
try:
transmit_data(data,
peer_id,
others_req_listener,
self._transm_send_timeout_sec,
self._transm_req_max_retries
)
except Exception as e:
self.terminate()
raise e
self._last_coms_time = datetime.now(UTC)
if PRINT_LOG_CONVERSATIONS:
print(conv_name + ": sent conversation request")
success = self.started.wait(transm_send_timeout_sec)
if not success:
raise CommunicationTimeout(
f"Successfully transmitted conversation request but received no reply within timeout of {transm_send_timeout_sec}s.")
return True # signal success
def join(self,
conv_name,
peer_id,
others_trsm_listener,
data_received_eventhandler=None,
file_eventhandler=None,
file_progress_callback=None,
encryption_callbacks=None,
transm_send_timeout_sec=_transm_send_timeout_sec,
transm_req_max_retries=_transm_req_max_retries,
dir="."):
"""Joins a conversation which another peer started, given their peer ID
and conversation's transmission-listener's name.
Used by a conversation listener.
See listen_for_conversations for usage.
Args:
conv_name (str): the name of the IPFS port forwarding connection
(IPFS Libp2pStreamMounting protocol)
peer_id (str): the IPFS peer ID of the node to communicate with
others_req_listener (str): the name of the ther peer's conversation
listener object
data_received_eventhandler (function): function to be called when
we've received a data transmission
Parameters: (data:bytearray)
file_eventhandler (function): function to be called when a file is
receive over this conversation
Parameters: (filepath:str, metadata:bytearray)
progress_handler (function): eventhandler to send progress (float
twix 0-1) every for sending/receiving files
Parameters: (progress:float)
encryption_callbacks (tuple): encryption and decryption functions
Tuple Contents: two functions which each take a
a bytearray as a parameter and return a bytearray
(
function(plaintext:bytearray):bytearray,
function(cipher:bytearray):bytearray
)
transm_send_timeout_sec (int): (low level) data transmission
connection attempt timeout, multiplied with the
maximum number of retries will result in the
total time required for a failed attempt
transm_req_max_retries (int): (low level) data
transmission how often the transmission should be
reattempted when the timeout is reached
dir (str): the path where received files should be downloaded to
"""
self.conv_name = conv_name
if PRINT_LOG_CONVERSATIONS:
print(conv_name + ": Joining conversation "
+ others_trsm_listener)
self.data_received_eventhandler = data_received_eventhandler
self.file_eventhandler = file_eventhandler
self.file_progress_callback = file_progress_callback
if encryption_callbacks:
self.__encryption_callback = encryption_callbacks[0]
self.__decryption_callback = encryption_callbacks[1]
self._transm_send_timeout_sec = transm_send_timeout_sec
self._transm_req_max_retries = transm_req_max_retries
self._listener = listen_for_transmissions(conv_name,
self._hear,
)
self.file_listener = listen_for_file_transmissions(
f"{conv_name}:files", self._file_received,
progress_handler=self._on_file_progress_received,
dir=dir,
encryption_callbacks=encryption_callbacks
)
self.others_trsm_listener = others_trsm_listener
self.peer_id = peer_id
data = bytearray("I'm listening".encode(
'utf-8')) + bytearray([255]) + bytearray(conv_name.encode('utf-8'))
self._conversation_started = True
transmit_data(data, peer_id, others_trsm_listener)
self._last_coms_time = datetime.now(UTC)
if PRINT_LOG_CONVERSATIONS:
print(conv_name + ": Joined conversation "
+ others_trsm_listener)
return True # signal success
def _hear(self, data, peer_id, arg3=""):
"""
Receives this conversation's data transmissions.
Forwards it to the user's data_received_eventhandler if the
conversation has already started,
otherwise processes the conversation initiation codes.
"""
if self._terminate:
return
# print("HEAR", data)
if not data:
print("CONV.HEAR: RECEIVED NONE")
return
self._last_coms_time = datetime.now(UTC)
if not self._conversation_started:
info = _split_by_255(data)
if bytearray(info[0]) == bytearray("I'm listening".encode('utf-8')):
self.others_trsm_listener = info[1].decode('utf-8')
# self.hear_eventhandler = self._hear
self._conversation_started = True
if PRINT_LOG_CONVERSATIONS:
print(self.conv_name +
": peer joined, conversation started")
self.started.set()
elif PRINT_LOG_CONVERSATIONS:
print(self.conv_name +
": received unrecognisable buffer, expected join confirmation")
print(info[0])
return
else: # conversation has already started
if self.__decryption_callback:
if PRINT_LOG_CONVERSATIONS:
print("Conv._hear: decrypting message")
data = self.__decryption_callback(data)
self.message_queue.put(data)
if self.data_received_eventhandler:
# if the data_received_eventhandler has 2 parameters
if len(signature(self.data_received_eventhandler).parameters) == 2:
Thread(target=self.data_received_eventhandler,
args=(self, data), name="Converstion.data_received_eventhandler").start()
else:
Thread(target=self.data_received_eventhandler, args=(
self, data, arg3), name="Converstion.data_received_eventhandler").start()
def listen(self, timeout=None):
"""Waits until the conversation peer sends a message, then returns that
message. Can be used as an alternative to specifying an
data_received_eventhandler to process received messages,
or both can be used in parallel.
Args:
timeout (int): how many seconds to wait until giving up and
raising an exception
Returns:
bytearray: received data
"""
if self._terminate:
return
if not timeout:
data = self.message_queue.get()
else:
try:
data = self.message_queue.get(timeout=timeout)
except: # timeout reached
raise ConvListenTimeout("Didn't receive any data.") from None
if data:
return data
else:
if PRINT_LOG_CONVERSATIONS:
print("Conv.listen: received nothing restarting Event Wait")
self.listen()
def _file_received(self, peer, filepath, metadata):
"""Receives this conversation's file transmissions."""
self._last_coms_time = datetime.now(UTC)
if PRINT_LOG_CONVERSATIONS:
print(f"{self.conv_name}: Received file: ", filepath)
self._file_queue.put({'filepath': filepath, 'metadata': metadata})
if self.file_eventhandler:
Thread(target=self.file_eventhandler, args=(self, filepath, metadata),
name='Conversation.file_eventhandler').start()
def listen_for_file(self, abs_timeout=None, no_coms_timeout=None):
"""
Args:
abs_timeout (int): how many seconds to wait for file reception to
finish until giving up and raising an exception
no_coms_timeout (int): how many seconds of no signal from peer
until giving up and returning None or raising an exception
Returns:
str: the path of the received file
"""
start_time = datetime.now(UTC)
if not (abs_timeout or no_coms_timeout): # if no timeouts are specified
data = self._file_queue.get()
else: # timeouts are specified
while True:
# calculate timeouts relative to current time
if no_coms_timeout:
# time left till next coms timeout check
_no_coms_timeout = no_coms_timeout - \
(datetime.now(UTC) - self._last_coms_time).total_seconds()
if abs_timeout:
# time left till absolute timeout would be reached
_abs_timeout = abs_timeout - \
(datetime.now(UTC) - start_time).total_seconds()
# Choose the timeout we need to wait for
timeout = None
if not abs_timeout:
timeout = _no_coms_timeout
elif not no_coms_timeout:
timeout = _abs_timeout
else:
timeout = min(_no_coms_timeout, _abs_timeout)
try:
data = self._file_queue.get(timeout=timeout)
break
except QueueEmpty: # qeue timeout reached
# check if any of the user's timeouts were reached
if abs_timeout and (datetime.now(UTC) - start_time).total_seconds() > abs_timeout:
raise ConvListenTimeout(
"Didn't receive any files.") from None
elif (datetime.now(UTC) - self._last_coms_time).total_seconds() > no_coms_timeout:
raise CommunicationTimeout(
"Communication timeout reached while waiting for file.") from None
if data:
return data
else:
if PRINT_LOG_CONVERSATIONS:
print("Conv.FileListen: received nothign restarting Event Wait")
self.listen_for_file(timeout)
def _on_file_progress_received(self, peer_id: str, filename: str, filesize: str, progress):
self._last_coms_time = datetime.now(UTC)
if self.file_progress_callback:
# run callback on a new thread, specifying only as many parameters as the callback wants
Thread(target=call_progress_callback,
args=(self.file_progress_callback,
peer_id,
filename,
filesize,
progress),
name='Conversation.progress_handler'
).start()
# if len(signature(self.progress_handler).parameters) == 1:
# self.file_progress_callback(progress)
# elif len(signature(self.progress_handler).parameters) == 2:
# self.file_progress_callback(filename, progress)
# elif len(signature(self.progress_handler).parameters) == 3:
# self.file_progress_callback(
# filename, filesize, progress)
def say(self,
data,
timeout_sec=_transm_send_timeout_sec,
max_retries=_transm_req_max_retries
):
"""
Transmits the provided data (a bytearray of any length) to this
conversation's peer.
Args:
bytearray data: the data to be transmitted to the receiver
timeout_sec: connection attempt timeout, multiplied with the
maximum number of retries will result in the
total time required for a failed attempt
max_retries: how often the transmission should be reattempted
when the timeout is reached
Returns:
bool success: whether or not the transmission succeeded
"""
while not self._conversation_started:
if PRINT_LOG:
print("Wanted to say something but conversation was not yet started")
time.sleep(0.01)
if self.__encryption_callback:
if PRINT_LOG_CONVERSATIONS:
print("Conv.say: encrypting message")
data = self.__encryption_callback(data)
transmit_data(data, self.peer_id, self.others_trsm_listener,
timeout_sec, max_retries)
self._last_coms_time = datetime.now(UTC)
return True
def transmit_file(self,
filepath,
metadata=bytearray(),
progress_handler=file_progress_callback,
block_size=BLOCK_SIZE,
transm_send_timeout_sec=_transm_send_timeout_sec,
transm_req_max_retries=_transm_req_max_retries
):
"""
Transmits the provided file to the other computer in this conversation.
"""
while not self._conversation_started:
if PRINT_LOG:
print("Wanted to say something but conversation was not yet started")
time.sleep(0.01)
if PRINT_LOG_CONVERSATIONS:
print("Transmitting file to ",
f"{self.others_trsm_listener}:files")
def _progress_handler(peer_id: str, filename: str, filesize: str, progress):
self._last_coms_time = datetime.now(UTC)
if progress_handler:
# run callback on a new thread, specifying only as many parameters as the callback wants
Thread(target=call_progress_callback,
args=(progress_handler,
peer_id,
filename,
filesize,
progress),
name='Conversation.progress_handler'
).start()
return transmit_file(
filepath,
self.peer_id,
f"{self.others_trsm_listener}:files",
metadata,
_progress_handler,
encryption_callbacks=(self.__encryption_callback,
self.__decryption_callback),
block_size=block_size,
transm_send_timeout_sec=transm_send_timeout_sec,
transm_req_max_retries=transm_req_max_retries)
def terminate(self):
"""Stop the conversation and clean up IPFS connection configurations.
"""
if self._terminate:
return
self._terminate = True
if self._listener:
self._listener.terminate()
if self.file_listener:
self.file_listener.terminate()
def close(self):
"""Stop the conversation and clean up IPFS connection configurations.
"""
self.terminate()
def __del__(self):
self.terminate()
class ConversationListener:
"""
Object which listens to incoming conversation requests.
Whenever a new conversation request is received, the specified eventhandler
is called which must then decide whether or not to join the conversation,
and then act upon that decision.
"""
def __init__(self, listener_name, eventhandler):
self._listener_name = listener_name
if (PRINT_LOG_CONVERSATIONS):
print("Listening for conversations as " + listener_name)
self.eventhandler = eventhandler
self._listener = listen_for_transmissions(
listener_name, self._on_request_received)
def _on_request_received(self, data, peer_id):
if PRINT_LOG_CONVERSATIONS:
print(
f"ConvLisReceived {self._listener_name}: Received Conversation Request")
info = _split_by_255(data)
if info[0] == bytearray("I want to start a conversation".encode('utf-8')):
if PRINT_LOG_CONVERSATIONS:
print(
f"ConvLisReceived {self._listener_name}: Starting conversation...")
conv_name = info[1].decode('utf-8')
self.eventhandler(conv_name, peer_id)
elif PRINT_LOG_CONVERSATIONS:
print(
f"ConvLisReceived {self._listener_name}: Received unreadable request")
print(info[0])
def terminate(self):
"""Stop listening for conversation requests and clean up IPFS
connection configurations.
"""
self._listener.terminate()
def __del__(self):
self.terminate()
def transmit_file(filepath,
peer_id,
others_req_listener,
metadata=bytearray(),
progress_handler=None,
encryption_callbacks=None,
block_size=BLOCK_SIZE,
transm_send_timeout_sec=TRANSM_SEND_TIMEOUT_SEC,
transm_req_max_retries=TRANSM_REQ_MAX_RETRIES
):
"""Transmits the provided file to the specified peer.
Args:
filepath (str): the path of the file to transmit
peer_id (str): the IPFS peer ID of the node to communicate with
others_req_listener (str): the name of the other peer's FileListener
metadata (bytearray): optional metadata to send to the receiver
progress_handler (function): eventhandler to send progress (fraction
twix 0-1) every for sending/receiving files
Parameters: (progress:float)
encryption_callbacks (tuple): encryption and decryption functions
Tuple Contents: two functions which each take a
a bytearray as a parameter and return a bytearray
(
function(plaintext:bytearray):bytearray,
function(cipher:bytearray):bytearray
)
block_size (int): the FileTransmitter sends the file in chunks. This is
the size of those chunks in bytes (default 1MiB).
Increasing this speeds up transmission but reduces the
frequency of progress update messages.
transm_send_timeout_sec (int): (low level) data transmission -
connection attempt timeout, multiplied with the maximum
number of retries will result in the total time