/
transfers.py
2476 lines (1807 loc) · 82.9 KB
/
transfers.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
# COPYRIGHT (C) 2020-2022 Nicotine+ Team
# COPYRIGHT (C) 2016-2017 Michael Labouebe <gfarmerfr@free.fr>
# COPYRIGHT (C) 2016 Mutnick <muhing@yahoo.com>
# COPYRIGHT (C) 2013 eL_vErDe <gandalf@le-vert.net>
# COPYRIGHT (C) 2008-2012 Quinox <quinox@users.sf.net>
# COPYRIGHT (C) 2009 Hedonist <ak@sensi.org>
# COPYRIGHT (C) 2006-2009 Daelstorm <daelstorm@gmail.com>
# COPYRIGHT (C) 2003-2004 Hyriand <hyriand@thegraveyard.org>
# COPYRIGHT (C) 2001-2003 Alexander Kanavin
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
""" This module contains classes that deal with file transfers:
the transfer manager.
"""
import json
import os
import os.path
import re
import stat
import threading
import time
from collections import defaultdict
from collections import deque
from collections import OrderedDict
from pynicotine import slskmessages
from pynicotine.logfacility import log
from pynicotine.slskmessages import increment_token
from pynicotine.utils import execute_command
from pynicotine.utils import clean_file
from pynicotine.utils import clean_path
from pynicotine.utils import get_result_bitrate_length
from pynicotine.utils import load_file
from pynicotine.utils import write_file_and_backup
class Transfer:
""" This class holds information about a single transfer """
__slots__ = ("sock", "user", "filename",
"path", "token", "size", "file", "start_time", "last_update",
"current_byte_offset", "last_byte_offset", "speed", "time_elapsed",
"time_left", "modifier", "queue_position", "bitrate", "length",
"iterator", "status", "legacy_attempt")
def __init__(self, user=None, filename=None, path=None, status=None, token=None, size=0,
current_byte_offset=None, bitrate=None, length=None):
self.user = user
self.filename = filename
self.path = path
self.size = size
self.status = status
self.token = token
self.current_byte_offset = current_byte_offset
self.bitrate = bitrate
self.length = length
self.sock = None
self.file = None
self.queue_position = 0
self.modifier = None
self.start_time = None
self.last_update = None
self.last_byte_offset = None
self.speed = None
self.time_elapsed = None
self.time_left = None
self.iterator = None
self.legacy_attempt = False
class Transfers:
""" This is the transfers manager """
def __init__(self, core, config, queue, network_callback, ui_callback=None):
self.core = core
self.config = config
self.queue = queue
self.allow_saving_transfers = False
self.downloads = deque()
self.uploads = deque()
self.privileged_users = set()
self.requested_folders = defaultdict(dict)
self.last_save_times = {"downloads": 0, "uploads": 0}
self.transfer_request_times = {}
self.upload_speed = 0
self.token = 0
self.user_update_counter = 0
self.user_update_counters = {}
self.downloads_file_name = os.path.join(self.config.data_dir, 'downloads.json')
self.uploads_file_name = os.path.join(self.config.data_dir, 'uploads.json')
self.network_callback = network_callback
self.download_queue_timer_count = -1
self.downloadsview = None
self.uploadsview = None
if hasattr(ui_callback, "downloads"):
self.downloadsview = ui_callback.downloads
if hasattr(ui_callback, "uploads"):
self.uploadsview = ui_callback.uploads
self.update_download_filters()
def init_transfers(self):
self.add_stored_transfers("downloads")
self.add_stored_transfers("uploads")
if self.downloadsview:
self.downloadsview.init_transfers(self.downloads)
if self.uploadsview:
self.uploadsview.init_transfers(self.uploads)
self.allow_saving_transfers = True
def server_login(self):
self.requested_folders.clear()
self.update_limits()
self.watch_stored_downloads()
# Check for transfer timeouts
thread = threading.Thread(target=self._check_transfer_timeouts)
thread.name = "TransferTimeoutTimer"
thread.daemon = True
thread.start()
# Check for failed downloads (1 min delay)
thread = threading.Thread(target=self._check_download_queue_timer)
thread.name = "DownloadQueueTimer"
thread.daemon = True
thread.start()
# Check if queued uploads can be started
thread = threading.Thread(target=self._check_upload_queue_timer)
thread.name = "UploadQueueTimer"
thread.daemon = True
thread.start()
if self.downloadsview:
self.downloadsview.server_login()
if self.uploadsview:
self.uploadsview.server_login()
""" Load Transfers """
def get_download_queue_file_name(self):
data_dir = self.config.data_dir
downloads_file_json = os.path.join(data_dir, 'downloads.json')
downloads_file_1_4_2 = os.path.join(data_dir, 'config.transfers.pickle')
downloads_file_1_4_1 = os.path.join(data_dir, 'transfers.pickle')
if os.path.exists(downloads_file_json):
# New file format
return downloads_file_json
if os.path.exists(downloads_file_1_4_2):
# Nicotine+ 1.4.2+
return downloads_file_1_4_2
if os.path.exists(downloads_file_1_4_1):
# Nicotine <=1.4.1
return downloads_file_1_4_1
# Fall back to new file format
return downloads_file_json
def get_upload_list_file_name(self):
data_dir = self.config.data_dir
uploads_file_json = os.path.join(data_dir, 'uploads.json')
return uploads_file_json
@staticmethod
def load_transfers_file(transfers_file):
""" Loads a file of transfers in json format """
if not os.path.isfile(transfers_file):
return None
with open(transfers_file, encoding="utf-8") as handle:
return json.load(handle)
@staticmethod
def load_legacy_transfers_file(transfers_file):
""" Loads a download queue file in pickle format (legacy) """
if not os.path.isfile(transfers_file):
return None
with open(transfers_file, "rb") as handle:
from pynicotine.utils import RestrictedUnpickler
return RestrictedUnpickler(handle, encoding="utf-8").load()
def load_transfers(self, transfer_type):
load_func = self.load_transfers_file
if transfer_type == "uploads":
transfers_file = self.get_upload_list_file_name()
else:
transfers_file = self.get_download_queue_file_name()
if transfer_type == "downloads" and not transfers_file.endswith("downloads.json"):
load_func = self.load_legacy_transfers_file
return load_file(transfers_file, load_func)
def add_stored_transfers(self, transfer_type):
transfers = self.load_transfers(transfer_type)
if not transfers:
return
if transfer_type == "uploads":
transfer_list = self.uploads
else:
transfer_list = self.downloads
for i in transfers:
loaded_status = current_byte_offset = bitrate = length = None
size = 0
try:
loaded_status = str(i[3])
except Exception:
pass
try:
size = int(i[4])
except Exception:
pass
try:
current_byte_offset = int(i[5])
except Exception:
pass
try:
loaded_bitrate = i[6]
if loaded_bitrate is not None:
bitrate = str(loaded_bitrate)
except Exception:
pass
try:
loaded_length = i[7]
if loaded_length is not None:
length = str(loaded_length)
except Exception:
pass
if loaded_status in ("Aborted", "Paused"):
status = "Paused"
elif loaded_status in ("Filtered", "Finished"):
status = loaded_status
else:
status = "User logged off"
if transfer_type == "uploads" and status != "Finished":
# Only finished uploads are supposed to be restored
continue
transfer_list.appendleft(
Transfer(
user=i[0], filename=i[1], path=i[2], status=status,
size=size, current_byte_offset=current_byte_offset, bitrate=bitrate,
length=length
)
)
def watch_stored_downloads(self):
""" When logging in, we request to watch the status of our downloads """
users = set()
for i in self.downloads:
users.add(i.user)
if i.status in ("Aborted", "Paused"):
i.status = "Paused"
elif i.status in ("Filtered", "Finished"):
continue
else:
i.status = "Getting status"
for user in users:
self.core.watch_user(user)
""" Privileges """
def set_privileged_users(self, user_list):
for user in user_list:
self.add_to_privileged(user)
def add_to_privileged(self, user):
self.privileged_users.add(user)
def remove_from_privileged(self, user):
if user in self.privileged_users:
self.privileged_users.remove(user)
def is_privileged(self, user):
if not user:
return False
if user in self.privileged_users:
return True
return self.is_buddy_prioritized(user)
def is_buddy_prioritized(self, user):
if not user:
return False
for row in self.config.sections["server"]["userlist"]:
if not row or not isinstance(row, list):
continue
if user == str(row[0]):
# All users
if self.config.sections["transfers"]["preferfriends"]:
return True
# Only explicitly prioritized users
try:
return bool(row[3]) # Prioritized column
except IndexError:
return False
return False
""" File Actions """
@staticmethod
def get_file_size(filename):
try:
size = os.path.getsize(filename)
except Exception:
# file doesn't exist (remote files are always this)
size = 0
return size
@staticmethod
def close_file(file_handle, transfer):
transfer.file = None
if file_handle is None:
return
try:
file_handle.close()
except Exception as error:
log.add_transfer("Failed to close file %(filename)s: %(error)s", {
"filename": file_handle.name,
"error": error
})
""" Limits """
def _update_regular_limits(self):
""" Sends the regular speed limits to the networking thread """
uselimit = self.config.sections["transfers"]["uselimit"]
uploadlimit = self.config.sections["transfers"]["uploadlimit"]
limitby = self.config.sections["transfers"]["limitby"]
self.queue.append(slskmessages.SetUploadLimit(uselimit, uploadlimit, limitby))
self.queue.append(slskmessages.SetDownloadLimit(self.config.sections["transfers"]["downloadlimit"]))
def _update_alt_limits(self):
""" Sends the alternative speed limits to the networking thread """
uselimit = True
uploadlimit = self.config.sections["transfers"]["uploadlimitalt"]
limitby = self.config.sections["transfers"]["limitby"]
self.queue.append(slskmessages.SetUploadLimit(uselimit, uploadlimit, limitby))
self.queue.append(slskmessages.SetDownloadLimit(self.config.sections["transfers"]["downloadlimitalt"]))
def update_limits(self):
if self.config.sections["transfers"]["usealtlimits"]:
self._update_alt_limits()
return
self._update_regular_limits()
def queue_limit_reached(self, user):
queue_size_limit = self.config.sections["transfers"]["queuelimit"] * 1024 * 1024
if not queue_size_limit:
return False
queue_size = 0
for i in self.uploads:
if i.user == user and i.status == "Queued":
queue_size += i.size
if queue_size >= queue_size_limit:
return True
return False
def file_limit_reached(self, user):
file_limit = self.config.sections["transfers"]["filelimit"]
if not file_limit:
return False
num_files = 0
for i in self.uploads:
if i.user == user and i.status == "Queued":
num_files += 1
if num_files >= file_limit:
return True
return False
def slot_limit_reached(self):
upload_slot_limit = self.config.sections["transfers"]["uploadslots"]
if upload_slot_limit <= 0:
upload_slot_limit = 1
num_in_progress = 0
active_statuses = ("Getting status", "Establishing connection", "Transferring")
for i in self.uploads:
if i.status in active_statuses:
num_in_progress += 1
if num_in_progress >= upload_slot_limit:
return True
return False
def bandwidth_limit_reached(self):
bandwidth_limit = self.config.sections["transfers"]["uploadbandwidth"] * 1024
if not bandwidth_limit:
return False
bandwidth_sum = 0
for i in self.uploads:
if i.speed is not None and i.sock is not None:
bandwidth_sum += i.speed
if bandwidth_sum >= bandwidth_limit:
return True
return False
def allow_new_uploads(self):
if self.config.sections["transfers"]["useupslots"]:
# Limit by upload slots
if self.slot_limit_reached():
return False
else:
# Limit by maximum bandwidth
if self.bandwidth_limit_reached():
return False
# No limits
return True
def file_is_upload_queued(self, user, filename):
statuses = ("Queued", "Getting status", "Establishing connection", "Transferring")
for i in self.uploads:
if i.user == user and i.filename == filename and i.status in statuses:
return True
return False
""" Network Events """
def get_user_status(self, msg):
""" We get a status of a user and if he's online, we request a file from him """
download_statuses = ("Queued", "Getting status", "Establishing connection", "Too many files",
"Too many megabytes", "Pending shutdown.", "User logged off", "Connection closed by peer",
"Cannot connect", "Remote file error")
upload_statuses = ("Getting status", "Establishing connection", "Disallowed extension",
"User logged off", "Cannot connect", "Cancelled")
for i in reversed(self.downloads.copy()):
if msg.user == i.user and (i.status in download_statuses or i.status.startswith("User limit of")):
if msg.status <= 0:
i.status = "User logged off"
self.abort_transfer(i)
self.update_download(i)
elif i.status in ("Getting status", "User logged off", "Connection closed by peer", "Cannot connect"):
self.get_file(i.user, i.filename, i.path, i)
# We need a copy due to upload auto-clearing modifying the deque during iteration
for i in reversed(self.uploads.copy()):
if msg.user == i.user and i.status in upload_statuses:
if msg.status <= 0:
i.status = "User logged off"
self.abort_transfer(i)
if not self.auto_clear_upload(i):
self.update_upload(i)
elif i.status == "User logged off":
i.status = "Cancelled"
if not self.auto_clear_upload(i):
self.update_upload(i)
def get_cant_connect_request(self, token):
""" We can't connect to the user, either way (FileRequest, TransferRequest). """
for i in self.downloads:
if i.token == token:
self._get_cant_connect_download(i)
break
for i in self.uploads:
if i.token == token:
self._get_cant_connect_upload(i)
break
def get_cant_connect_queue_file(self, username, filename):
""" We can't connect to the user, either way (QueueUpload). """
for i in self.downloads:
if i.user == username and i.filename == filename:
self._get_cant_connect_download(i)
break
def _get_cant_connect_download(self, i):
i.status = "Cannot connect"
i.token = None
self.update_download(i)
self.core.watch_user(i.user)
def _get_cant_connect_upload(self, i):
i.status = "Cannot connect"
i.token = None
i.queue_position = 0
self.update_user_counter(i.user)
self.update_upload(i)
self.core.watch_user(i.user)
self.check_upload_queue()
def folder_contents_response(self, msg):
""" When we got a contents of a folder, get all the files in it, but
skip the files in subfolders """
username = msg.init.target_user
file_list = msg.list
log.add_transfer("Received response for folder content request from user %s", username)
for i in file_list:
for directory in file_list[i]:
if os.path.commonprefix([i, directory]) != directory:
continue
files = file_list[i][directory][:]
destination = self.get_folder_destination(username, directory)
if self.config.sections["transfers"]["reverseorder"]:
files.sort(key=lambda x: x[1], reverse=True)
log.add_transfer(
"Attempting to download files in folder %(folder)s for user %(user)s. "
+ "Destination path: %(destination)s", {
"folder": directory,
"user": username,
"destination": destination
}
)
for file in files:
virtualpath = directory.rstrip('\\') + '\\' + file[1]
size = file[2]
h_bitrate, _bitrate, h_length, _length = get_result_bitrate_length(size, file[4])
self.get_file(
username, virtualpath, destination,
size=size, bitrate=h_bitrate, length=h_length)
if directory in self.requested_folders.get(username, []):
del self.requested_folders[username][directory]
def queue_upload(self, msg):
""" Peer remotely queued a download (upload here). This is the modern replacement to
a TransferRequest with direction 0 (download request). We will initiate the upload of
the queued file later. """
user = msg.init.target_user
real_path = self.core.shares.virtual2real(msg.file)
log.add_transfer("QueueUpload request: User %(user)s, %(msg)s", {
'user': user,
'msg': str(vars(msg))
})
if not self.file_is_upload_queued(user, msg.file):
limits = True
if self.config.sections["transfers"]["friendsnolimits"]:
friend = user in (i[0] for i in self.config.sections["server"]["userlist"])
if friend:
limits = False
ip_address, _port = msg.init.addr
checkuser, reason = self.core.network_filter.check_user(user, ip_address)
if not checkuser:
self.queue.append(
slskmessages.UploadDenied(msg.init, msg.file, reason)
)
elif limits and self.queue_limit_reached(user):
self.queue.append(
slskmessages.UploadDenied(msg.init, msg.file, "Too many megabytes")
)
elif limits and self.file_limit_reached(user):
self.queue.append(
slskmessages.UploadDenied(msg.init, msg.file, "Too many files")
)
elif self.core.shares.file_is_shared(user, msg.file, real_path):
newupload = Transfer(
user=user, filename=msg.file,
path=os.path.dirname(real_path), status="Queued",
size=self.get_file_size(real_path)
)
self.append_upload(user, msg.file, newupload)
self.update_upload(newupload)
self.core.pluginhandler.upload_queued_notification(user, msg.file, real_path)
self.check_upload_queue()
else:
self.queue.append(
slskmessages.UploadDenied(msg.init, msg.file, "File not shared.")
)
def transfer_request(self, msg):
user = msg.init.target_user
response = None
if msg.direction == 1:
log.add_transfer("Received upload request %(request)s for file %(filename)s from user %(user)s", {
"request": msg.token,
"filename": msg.file,
"user": user
})
response = self.transfer_request_downloads(msg)
log.add_transfer("Sending response to upload request %(request)s for file %(filename)s "
+ "from user %(user)s: %(allowed)s", {
"request": response.token,
"filename": msg.file,
"user": user,
"allowed": response.allowed
})
else:
log.add_transfer("Received download request %(request)s for file %(filename)s from user %(user)s", {
"request": msg.token,
"filename": msg.file,
"user": user
})
response = self.transfer_request_uploads(msg)
log.add_transfer("Sending response to download request %(request)s for file %(filename)s "
+ "from user %(user)s: %(allowed)s", {
"request": response.token,
"filename": msg.file,
"user": user,
"allowed": response.allowed
})
self.core.send_message_to_peer(user, response)
def transfer_request_downloads(self, msg):
user = msg.init.target_user
filename = msg.file
size = msg.filesize
cancel_reason = "Cancelled"
accepted = True
for i in self.downloads:
if i.filename == filename and user == i.user:
status = i.status
if status == "Finished":
# SoulseekQt sends "Complete" as the reason for rejecting the download if it exists
cancel_reason = "Complete"
accepted = False
break
if status in ("Paused", "Filtered"):
accepted = False
break
# Remote peer is signaling a transfer is ready, attempting to download it
# If the file is larger than 2GB, the SoulseekQt client seems to
# send a malformed file size (0 bytes) in the TransferRequest response.
# In that case, we rely on the cached, correct file size we received when
# we initially added the download.
if msg.filesize > 0:
i.size = size
i.token = msg.token
i.status = "Getting status"
self.transfer_request_times[i] = time.time()
self.update_download(i)
response = slskmessages.TransferResponse(None, 1, token=i.token)
return response
# Check if download exists in our default download folder
if self.get_existing_download_path(user, filename, "", size):
cancel_reason = "Complete"
accepted = False
# If this file is not in your download queue, then it must be
# a remotely initiated download and someone is manually uploading to you
if accepted and self.can_upload(user):
path = ""
if self.config.sections["transfers"]["uploadsinsubdirs"]:
parentdir = msg.file.replace('/', '\\').split('\\')[-2]
path = os.path.join(self.config.sections["transfers"]["uploaddir"], user, parentdir)
transfer = Transfer(
user=user, filename=msg.file, path=path,
status="Queued", size=msg.filesize, token=msg.token
)
self.downloads.appendleft(transfer)
self.core.watch_user(user)
response = slskmessages.TransferResponse(None, 0, reason="Queued", token=transfer.token)
self.update_download(transfer)
else:
response = slskmessages.TransferResponse(None, 0, reason=cancel_reason, token=msg.token)
log.add_transfer("Denied file request: User %(user)s, %(msg)s", {
'user': user,
'msg': str(vars(msg))
})
return response
def transfer_request_uploads(self, msg):
""" Remote peer is requesting to download a file through your upload queue.
Note that the QueueUpload peer message has replaced this method of requesting
a download in most clients. """
response = self._transfer_request_uploads(msg)
log.add_transfer("Legacy TransferRequest upload request: %(req)s Response: %(resp)s", {
'req': str(vars(msg)),
'resp': response
})
return response
def _transfer_request_uploads(self, msg):
# Is user allowed to download?
user = msg.init.target_user
ip_address, _port = msg.init.addr
checkuser, reason = self.core.network_filter.check_user(user, ip_address)
if not checkuser:
return slskmessages.TransferResponse(None, 0, reason=reason, token=msg.token)
# Do we actually share that file with the world?
real_path = self.core.shares.virtual2real(msg.file)
if not self.core.shares.file_is_shared(user, msg.file, real_path):
return slskmessages.TransferResponse(None, 0, reason="File not shared.", token=msg.token)
# Is that file already in the queue?
if self.file_is_upload_queued(user, msg.file):
return slskmessages.TransferResponse(None, 0, reason="Queued", token=msg.token)
# Has user hit queue limit?
limits = True
if self.config.sections["transfers"]["friendsnolimits"]:
friend = user in (i[0] for i in self.config.sections["server"]["userlist"])
if friend:
limits = False
if limits and self.queue_limit_reached(user):
return slskmessages.TransferResponse(None, 0, reason="Too many megabytes", token=msg.token)
if limits and self.file_limit_reached(user):
return slskmessages.TransferResponse(None, 0, reason="Too many files", token=msg.token)
# All checks passed, user can queue file!
self.core.pluginhandler.upload_queued_notification(user, msg.file, real_path)
# Is user already downloading/negotiating a download?
already_downloading = False
active_statuses = ("Getting status", "Establishing connection", "Transferring")
for i in self.uploads:
if i.user != user:
continue
if i.status in active_statuses:
already_downloading = True
break
if not self.allow_new_uploads() or already_downloading:
response = slskmessages.TransferResponse(None, 0, reason="Queued", token=msg.token)
newupload = Transfer(
user=user, filename=msg.file,
path=os.path.dirname(real_path), status="Queued",
size=self.get_file_size(real_path)
)
self.append_upload(user, msg.file, newupload)
self.update_upload(newupload)
return response
# All checks passed, starting a new upload.
size = self.get_file_size(real_path)
response = slskmessages.TransferResponse(None, 1, token=msg.token, filesize=size)
transferobj = Transfer(
user=user, filename=msg.file,
path=os.path.dirname(real_path), status="Getting status",
token=msg.token, size=size
)
self.transfer_request_times[transferobj] = time.time()
self.append_upload(user, msg.file, transferobj)
self.update_upload(transferobj)
return response
def transfer_response(self, msg):
""" Received a response to the file request from the peer """
log.add_transfer("Received response for transfer request %(request)s. Allowed: %(allowed)s. "
+ "Reason: %(reason)s. Filesize: %(size)s", {
"request": msg.token,
"allowed": msg.allowed,
"reason": msg.reason,
"size": msg.filesize
})
if msg.reason is not None:
for i in self.uploads:
if i.token != msg.token:
continue
i.status = msg.reason
i.token = None
i.queue_position = 0
self.update_upload(i)
if i in self.transfer_request_times:
del self.transfer_request_times[i]
self.update_user_counter(i.user)
if msg.reason == "Complete":
# A complete download of this file already exists on the user's end
self.upload_finished(i)
elif msg.reason in ("Cancelled", "Disallowed extension"):
self.auto_clear_upload(i)
self.check_upload_queue()
break
else:
for i in self.uploads:
if i.token != msg.token:
continue
i.status = "Establishing connection"
self.core.send_message_to_peer(i.user, slskmessages.FileRequest(None, msg.token))
self.update_upload(i)
self.check_upload_queue()
break
else:
log.add_transfer("Got unknown transfer response: %s", str(vars(msg)))
def transfer_timeout(self, msg):
transfer = msg.transfer
if transfer.status == "Transferring":
# Check if the transfer has started since the timeout callback was initiated
return
log.add_transfer("Transfer %(filename)s with request %(request)s for user %(user)s timed out", {
"filename": transfer.filename,
"request": transfer.token,
"user": transfer.user
})
transfer.status = "Cannot connect"
transfer.token = None
self.core.watch_user(transfer.user)
if transfer in self.downloads:
self.update_download(transfer)
elif transfer in self.uploads:
transfer.queue_position = 0
self.update_user_counter(transfer.user)
self.update_upload(transfer)
if transfer in self.transfer_request_times:
del self.transfer_request_times[transfer]
self.check_upload_queue()
def file_error(self, msg):
""" Networking thread encountered a local file error """
for i in self.downloads + self.uploads:
if i.sock != msg.sock:
continue
self.abort_transfer(i)
i.status = "Local file error"