forked from nicotine-plus/nicotine-plus
-
Notifications
You must be signed in to change notification settings - Fork 1
/
transfers.py
2639 lines (1917 loc) · 93.1 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+ Contributors
# COPYRIGHT (C) 2016-2017 Michael Labouebe <[email protected]>
# COPYRIGHT (C) 2016 Mutnick <[email protected]>
# COPYRIGHT (C) 2013 eLvErDe <[email protected]>
# COPYRIGHT (C) 2008-2012 quinox <[email protected]>
# COPYRIGHT (C) 2009 hedonist <[email protected]>
# COPYRIGHT (C) 2006-2009 daelstorm <[email protected]>
# COPYRIGHT (C) 2003-2004 Hyriand <[email protected]>
# 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 time
from collections import defaultdict
from collections import deque
from operator import itemgetter
from pynicotine import slskmessages
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.events import events
from pynicotine.logfacility import log
from pynicotine.slskmessages import increment_token
from pynicotine.slskmessages import FileListMessage
from pynicotine.slskmessages import TransferDirection
from pynicotine.slskmessages import UserStatus
from pynicotine.utils import execute_command
from pynicotine.utils import clean_file
from pynicotine.utils import clean_path
from pynicotine.utils import encode_path
from pynicotine.utils import human_speed
from pynicotine.utils import load_file
from pynicotine.utils import truncate_string_byte
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", "size_changed")
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 = 0
self.time_left = None
self.iterator = None
self.legacy_attempt = False
self.size_changed = False
class Transfers:
""" This is the transfers manager """
def __init__(self):
self.allow_saving_transfers = False
self.downloads = deque()
self.uploads = deque()
self.privileged_users = set()
self.requested_folders = defaultdict(dict)
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(config.data_dir, "downloads.json")
self.uploads_file_name = os.path.join(config.data_dir, "uploads.json")
self._transfer_timeout_timer_id = None
self._download_queue_timer_id = None
self._upload_queue_timer_id = None
self._retry_download_limits_timer_id = None
self._retry_failed_uploads_timer_id = None
for event_name, callback in (
("add-privileged-user", self._add_to_privileged),
("download-connection-closed", self._download_connection_closed),
("download-file-error", self._download_file_error),
("file-download-init", self._file_download_init),
("file-download-progress", self._file_download_progress),
("file-upload-init", self._file_upload_init),
("file-upload-progress", self._file_upload_progress),
("folder-contents-response", self._folder_contents_response),
("peer-connection-error", self._peer_connection_error),
("place-in-queue-request", self._place_in_queue_request),
("place-in-queue-response", self._place_in_queue_response),
("queue-upload", self._queue_upload),
("quit", self._quit),
("remove-privileged-user", self._remove_from_privileged),
("server-login", self._server_login),
("server-disconnect", self._server_disconnect),
("start", self._start),
("transfer-request", self._transfer_request),
("transfer-response", self._transfer_response),
("upload-connection-closed", self._upload_connection_closed),
("upload-denied", self._upload_denied),
("upload-failed", self._upload_failed),
("upload-file-error", self._upload_file_error),
("user-stats", self._user_stats),
("user-status", self._user_status)
):
events.connect(event_name, callback)
def _start(self):
self.add_stored_transfers("downloads")
self.add_stored_transfers("uploads")
self.allow_saving_transfers = True
# Save list of transfers every minute
events.schedule(delay=60, callback=self.save_transfers, repeat=True)
self.update_download_filters()
self.update_download_limits()
self.update_upload_limits()
def _quit(self):
self.save_transfers()
self.allow_saving_transfers = False
self.downloads.clear()
self.uploads.clear()
self.upload_speed = 0
self.token = 0
def _server_login(self, msg):
if not msg.success:
return
self.requested_folders.clear()
self.update_download_limits()
self.update_upload_limits()
self.watch_stored_downloads()
# Check for transfer timeouts
self._transfer_timeout_timer_id = events.schedule(delay=1, callback=self._check_transfer_timeouts, repeat=True)
# Request queue position of queued downloads and retry failed downloads every 3 minutes
self._download_queue_timer_id = events.schedule(delay=180, callback=self.check_download_queue, repeat=True)
# Check if queued uploads can be started every 10 seconds
self._upload_queue_timer_id = events.schedule(delay=10, callback=self.check_upload_queue, repeat=True)
# Re-queue limited downloads every 12 minutes
self._retry_download_limits_timer_id = events.schedule(
delay=720, callback=self.retry_download_limits, repeat=True)
# Re-queue timed out uploads every 3 minutes
self._retry_failed_uploads_timer_id = events.schedule(
delay=180, callback=self.retry_failed_uploads, repeat=True)
def _server_disconnect(self, _msg):
for timer_id in (self._transfer_timeout_timer_id, self._download_queue_timer_id, self._upload_queue_timer_id,
self._retry_download_limits_timer_id, self._retry_failed_uploads_timer_id):
events.cancel_scheduled(timer_id)
need_update = False
for download in self.downloads:
if download.status not in ("Finished", "Filtered", "Paused"):
download.status = "User logged off"
self.abort_download(download, abort_reason=None)
need_update = True
if need_update:
events.emit("update-downloads")
need_update = False
for upload in self.uploads.copy():
if upload.status != "Finished":
need_update = True
self.clear_upload(upload)
if need_update:
events.emit("update-uploads")
self.privileged_users.clear()
self.requested_folders.clear()
self.transfer_request_times.clear()
self.user_update_counters.clear()
self.user_update_counter = 0
""" Load Transfers """
def get_download_queue_file_name(self):
data_dir = 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(encode_path(downloads_file_json)):
# New file format
return downloads_file_json
if os.path.exists(encode_path(downloads_file_1_4_2)):
# Nicotine+ 1.4.2+
return downloads_file_1_4_2
if os.path.exists(encode_path(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 = 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 """
transfers_file = encode_path(transfers_file)
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) """
transfers_file = encode_path(transfers_file)
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 transfer_row in transfers:
num_attributes = len(transfer_row)
if num_attributes < 3:
continue
# User / filename / path
user = transfer_row[0]
if not isinstance(user, str):
continue
filename = transfer_row[1]
if not isinstance(filename, str):
continue
path = transfer_row[2]
if not isinstance(path, str):
continue
# Status
loaded_status = None
if num_attributes >= 4:
loaded_status = str(transfer_row[3])
if transfer_type == "uploads" and loaded_status != "Finished":
# Only finished uploads are supposed to be restored
continue
if loaded_status in ("Aborted", "Paused"):
status = "Paused"
elif loaded_status in ("Filtered", "Finished"):
status = loaded_status
else:
status = "User logged off"
# Size / offset
size = 0
current_byte_offset = None
if num_attributes >= 5:
loaded_size = transfer_row[4]
if loaded_size and isinstance(loaded_size, (int, float)):
size = int(loaded_size)
if num_attributes >= 6:
loaded_byte_offset = transfer_row[5]
if loaded_byte_offset and isinstance(loaded_byte_offset, (int, float)):
current_byte_offset = int(loaded_byte_offset)
# Bitrate / length
bitrate = length = None
if num_attributes >= 7:
loaded_bitrate = transfer_row[6]
if loaded_bitrate is not None:
bitrate = str(loaded_bitrate)
if num_attributes >= 8:
loaded_length = transfer_row[7]
if loaded_length is not None:
length = str(loaded_length)
transfer_list.appendleft(
Transfer(
user=user, filename=filename, path=path, 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 download in self.downloads:
if download.status in ("Filtered", "Finished"):
continue
users.add(download.user)
for user in users:
core.watch_user(user)
""" Privileges """
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
user_data = core.userlist.buddies.get(user)
if user_data:
# All users
if config.sections["transfers"]["preferfriends"]:
return True
# Only explicitly prioritized users
return bool(user_data.is_prioritized)
return False
""" File Actions """
@staticmethod
def get_file_size(filename):
try:
size = os.path.getsize(encode_path(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.decode("utf-8", "replace"),
"error": error
})
""" Limits """
def update_download_limits(self):
events.emit("update-download-limits")
if core.user_status == UserStatus.OFFLINE:
return
use_speed_limit = config.sections["transfers"]["use_download_speed_limit"]
if use_speed_limit == "primary":
speed_limit = config.sections["transfers"]["downloadlimit"]
elif use_speed_limit == "alternative":
speed_limit = config.sections["transfers"]["downloadlimitalt"]
else:
speed_limit = 0
core.queue.append(slskmessages.SetDownloadLimit(speed_limit))
def update_upload_limits(self):
events.emit("update-upload-limits")
if core.user_status == UserStatus.OFFLINE:
return
use_speed_limit = config.sections["transfers"]["use_upload_speed_limit"]
limit_by = config.sections["transfers"]["limitby"]
if use_speed_limit == "primary":
speed_limit = config.sections["transfers"]["uploadlimit"]
elif use_speed_limit == "alternative":
speed_limit = config.sections["transfers"]["uploadlimitalt"]
else:
speed_limit = 0
core.queue.append(slskmessages.SetUploadLimit(speed_limit, limit_by))
def queue_limit_reached(self, user):
file_limit = config.sections["transfers"]["filelimit"]
queue_size_limit = config.sections["transfers"]["queuelimit"] * 1024 * 1024
if not file_limit and not queue_size_limit:
return False, None
num_files = 0
queue_size = 0
for upload in self.uploads:
if upload.user != user or upload.status != "Queued":
continue
if file_limit:
num_files += 1
if num_files >= file_limit:
return True, "Too many files"
if queue_size_limit:
queue_size += upload.size
if queue_size >= queue_size_limit:
return True, "Too many megabytes"
return False, None
def slot_limit_reached(self):
upload_slot_limit = config.sections["transfers"]["uploadslots"]
if upload_slot_limit <= 0:
upload_slot_limit = 1
num_in_progress = 0
active_statuses = ("Getting status", "Transferring")
for upload in self.uploads:
if upload.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 = config.sections["transfers"]["uploadbandwidth"] * 1024
if not bandwidth_limit:
return False
bandwidth_sum = 0
for upload in self.uploads:
if upload.sock is not None and upload.speed is not None:
bandwidth_sum += upload.speed
if bandwidth_sum >= bandwidth_limit:
return True
return False
def allow_new_uploads(self):
if core.shares.rescanning:
return False
if 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", "Transferring")
return next(
(upload.filename == filename and upload.status in statuses and upload.user == user
for upload in self.uploads), False
)
@staticmethod
def file_is_readable(filename, real_path):
try:
if os.access(encode_path(real_path), os.R_OK):
return True
log.add_transfer("Cannot access file, not sharing: %(virtual_name)s with real path %(path)s", {
"virtual_name": filename,
"path": real_path
})
except Exception:
log.add_transfer(("Requested file path contains invalid characters or other errors, not sharing: "
"%(virtual_name)s with real path %(path)s"), {
"virtual_name": filename,
"path": real_path
})
return False
""" Events """
def _user_status(self, msg):
""" Server code: 7 """
""" We get a status of a user and if he's online, we request a file from him """
update = False
username = msg.user
privileged = msg.privileged
user_offline = (msg.status == UserStatus.OFFLINE)
download_statuses = ("Queued", "Getting status", "Too many files", "Too many megabytes", "Pending shutdown.",
"User logged off", "Connection timeout", "Remote file error", "Cancelled")
upload_statuses = ("Getting status", "User logged off", "Connection timeout")
if privileged is not None:
if privileged:
events.emit("add-privileged-user", username)
else:
events.emit("remove-privileged-user", username)
for download in reversed(self.downloads.copy()):
if (download.user == username
and (download.status in download_statuses or download.status.startswith("User limit of"))):
if user_offline:
download.status = "User logged off"
self.abort_download(download, abort_reason=None)
update = True
elif download.status == "User logged off":
self.get_file(username, download.filename, path=download.path, transfer=download, ui_callback=False)
update = True
if update:
events.emit("update-downloads")
update = False
# We need a copy due to upload auto-clearing modifying the deque during iteration
for upload in reversed(self.uploads.copy()):
if upload.user == username and upload.status in upload_statuses:
if user_offline:
if not self.auto_clear_upload(upload):
upload.status = "User logged off"
self.abort_upload(upload, abort_reason=None)
update = True
elif upload.status == "User logged off":
if not self.auto_clear_upload(upload):
upload.status = "Cancelled"
update = True
if update:
events.emit("update-uploads")
def _connect_to_peer(self, msg):
""" Server code: 18 """
if msg.privileged is None:
return
if msg.privileged:
events.emit("add-privileged-user", msg.user)
else:
events.emit("remove-privileged-user", msg.user)
def _user_stats(self, msg):
""" Server code: 36 """
if msg.user == core.login_username:
self.upload_speed = msg.avgspeed
def _peer_connection_error(self, user, msgs=None, is_offline=False):
if msgs is None:
return
for i in msgs:
if i.__class__ in (slskmessages.TransferRequest, slskmessages.FileUploadInit):
self._cant_connect_upload(user, i.token, is_offline)
elif i.__class__ is slskmessages.QueueUpload:
self._cant_connect_queue_file(user, i.file, is_offline)
def _cant_connect_queue_file(self, username, filename, is_offline):
""" We can't connect to the user, either way (QueueUpload). """
for download in self.downloads:
if download.filename != filename or download.user != username:
continue
log.add_transfer("Download attempt for file %(filename)s from user %(user)s timed out", {
"filename": filename,
"user": username
})
self.abort_download(download, abort_reason="User logged off" if is_offline else "Connection timeout")
core.watch_user(username)
break
def _cant_connect_upload(self, username, token, is_offline):
""" We can't connect to the user, either way (TransferRequest, FileUploadInit). """
for upload in self.uploads:
if upload.token != token or upload.user != username:
continue
log.add_transfer("Upload attempt for file %(filename)s with token %(token)s to user %(user)s timed out", {
"filename": upload.filename,
"token": token,
"user": username
})
if upload.sock is not None:
log.add_transfer("Existing file connection for upload with token %s already exists?", token)
return
upload_cleared = is_offline and self.auto_clear_upload(upload)
if not upload_cleared:
self.abort_upload(upload, abort_reason="User logged off" if is_offline else "Connection timeout")
core.watch_user(username)
self.check_upload_queue()
return
def _folder_contents_response(self, msg, check_num_files=True):
""" Peer code: 37 """
""" 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][:]
num_files = len(files)
if check_num_files and num_files > 100:
events.emit("download-large-folder", username, directory, num_files, msg)
return
destination = self.get_folder_destination(username, directory)
files.sort(key=itemgetter(1), reverse=config.sections["transfers"]["reverseorder"])
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 = FileListMessage.parse_result_bitrate_length(size, file[4])
self.get_file(
username, virtualpath, path=destination,
size=size, bitrate=h_bitrate, length=h_length)
def _queue_upload(self, msg):
""" Peer code: 43 """
""" 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
filename = msg.file
log.add_transfer("Received upload request for file %(filename)s from user %(user)s", {
"user": user,
"filename": filename,
})
real_path = core.shares.virtual2real(filename)
allowed, reason = self.check_queue_upload_allowed(user, msg.init.addr, filename, real_path, msg)
log.add_transfer(("Upload request for file %(filename)s from user: %(user)s, "
"allowed: %(allowed)s, reason: %(reason)s"), {
"filename": filename,
"user": user,
"allowed": allowed,
"reason": reason
})
if not allowed:
if reason and reason != "Queued":
core.send_message_to_peer(user, slskmessages.UploadDenied(file=filename, reason=reason))
return
transfer = Transfer(user=user, filename=filename, path=os.path.dirname(real_path),
status="Queued", size=self.get_file_size(real_path))
self.append_upload(user, filename, transfer)
self.update_upload(transfer)
core.pluginhandler.upload_queued_notification(user, filename, real_path)
self.check_upload_queue()
def _transfer_request(self, msg):
""" Peer code: 40 """
user = msg.init.target_user
if msg.direction == TransferDirection.UPLOAD:
response = self._transfer_request_downloads(msg)
log.add_transfer(("Responding to download request with token %(token)s for file %(filename)s "
"from user: %(user)s, allowed: %(allowed)s, reason: %(reason)s"), {
"token": response.token, "filename": msg.file, "user": user,
"allowed": response.allowed, "reason": response.reason
})
elif msg.direction == TransferDirection.DOWNLOAD:
response = self._transfer_request_uploads(msg)
if response is None:
return
log.add_transfer(("Responding to legacy upload request %(token)s for file %(filename)s "
"from user %(user)s, allowed: %(allowed)s, reason: %(reason)s"), {
"token": response.token, "filename": msg.file, "user": user,
"allowed": response.allowed, "reason": response.reason
})
else:
log.add_transfer(("Received unknown transfer direction %(direction)s for file %(filename)s "
"from user %(user)s"), {
"direction": msg.direction, "filename": msg.file, "user": user
})
return
core.send_message_to_peer(user, response)
def _transfer_request_downloads(self, msg):
user = msg.init.target_user
filename = msg.file
size = msg.filesize
token = msg.token
log.add_transfer("Received download request with token %(token)s for file %(filename)s from user %(user)s", {
"token": token,
"filename": filename,
"user": user
})
cancel_reason = "Cancelled"
accepted = True
for download in self.downloads:
if download.filename != filename or download.user != user:
continue
status = download.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 size > 0:
if download.size != size:
# The remote user's file contents have changed since we queued the download
download.size_changed = True
download.size = size
download.token = token
download.status = "Getting status"
self.transfer_request_times[download] = time.time()
self.update_download(download)
return slskmessages.TransferResponse(allowed=True, token=token)
# Check if download exists in our default download folder
if self.get_complete_download_file_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 config.sections["transfers"]["uploadsinsubdirs"]:
parentdir = filename.replace("/", "\\").split("\\")[-2]
path = os.path.join(config.sections["transfers"]["uploaddir"], user, parentdir)
transfer = Transfer(user=user, filename=filename, path=path, status="Queued",
size=size, token=token)
self.downloads.appendleft(transfer)
self.update_download(transfer)
core.watch_user(user)
return slskmessages.TransferResponse(allowed=True, token=token)
log.add_transfer("Denied file request: User %(user)s, %(msg)s", {
"user": user,
"msg": msg
})
return slskmessages.TransferResponse(allowed=False, reason=cancel_reason, token=token)
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. """
user = msg.init.target_user
filename = msg.file
token = msg.token
log.add_transfer("Received legacy upload request %(token)s for file %(filename)s from user %(user)s", {
"token": token,
"filename": filename,
"user": user
})
# Is user allowed to download?
real_path = core.shares.virtual2real(filename)
allowed, reason = self.check_queue_upload_allowed(user, msg.init.addr, filename, real_path, msg)
if not allowed:
if reason:
return slskmessages.TransferResponse(allowed=False, reason=reason, token=token)
return None
# All checks passed, user can queue file!
core.pluginhandler.upload_queued_notification(user, filename, real_path)
# Is user already downloading/negotiating a download?
already_downloading = False
active_statuses = ("Getting status", "Transferring")
for upload in self.uploads:
if upload.status not in active_statuses or upload.user != user:
continue
already_downloading = True
break
if not self.allow_new_uploads() or already_downloading:
transfer = Transfer(user=user, filename=filename, path=os.path.dirname(real_path),
status="Queued", size=self.get_file_size(real_path))
self.append_upload(user, filename, transfer)