-
Notifications
You must be signed in to change notification settings - Fork 0
/
Connection.py
executable file
·1253 lines (1138 loc) · 54.6 KB
/
Connection.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
#!/usr/bin/env python
# -*- encoding=utf8 -*-
__copyright__ = """
Tramet, a sftp/ftp client
Copyright (C) 2020 Christian Metscher <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Tramet is licensed under the MIT, see `http://copyfree.org/licenses/mit/license.txt'.
"""
__license__ = "MIT"
from pathlib import Path
from os import listdir, makedirs, utime, stat, remove
from os.path import exists, join as ojoin, basename, getmtime, getsize, isdir, normpath, isfile, islink
from posixpath import join as pjoin
from stat import S_ISDIR, S_ISLNK, S_ISREG, filemode
from datetime import datetime
from re import search, IGNORECASE
from time import sleep
from ssh2.sftp import *
from ssh2.sftp import LIBSSH2_SFTP_ATTR_UIDGID, LIBSSH2_SFTP_ATTR_PERMISSIONS, LIBSSH2_SFTP_ATTR_ACMODTIME
from ssh2.sftp_handle import SFTPAttributes
from ssh2.exceptions import *
from ssh2.error_codes import *
from ftplib import error_perm
from thread_work import *
from threading import Lock
from ftplisting import ftp_file_list
from tkinter import filedialog, messagebox
def insert(ui, datas, selected=""):
selected_iid = ""
first_iid = ""
for da in datas:
iid = ui.tree.insert(
"", "end", text=da[0],
values=(da[1], da[2], da[3], da[4], da[5], da[6], da[7]),
image=da[8])
if da[0] == "..":
first_iid = iid
if selected == da[0]:
selected_iid = iid
if selected_iid:
ui.tree.see(selected_iid)
ui.tree.selection_set(selected_iid)
ui.tree.focus(selected_iid)
elif first_iid:
ui.tree.see(first_iid)
ui.tree.selection_set(first_iid)
ui.tree.focus(first_iid)
def get_size(conn, mode, enc, path, size_all, isFile):
"""
calculate overall size
:param conn: Connection object for sftp/ftp tasks
:type conn: object
:param mode: Connection mode - sftp/ftp
:type mode: str
:param enc: encoding for the current remote login user
:type enc: str
:param path: file or folder to get size from
:type path: str
:param size_all: ref object for the result
:type size_all: dict
:param isFile: flag to indicate file or folder
:type isFile: bool
"""
if mode == "SFTP":
if not isFile:
def recrse(pth, obj, attr, rslt):
if S_ISDIR(attr.permissions) != 0:
with conn.opendir(pjoin(pth, obj)) as dirh_:
for size_, buf_, attrs_ in dirh_.readdir():
o_ = buf_.decode(enc)
if o_ not in [".", ".."]:
recrse(pjoin(pth, obj), o_, attrs_, rslt)
elif S_ISREG(attrs.permissions) != 0:
rslt["size"] += attrs.filesize
with conn.opendir(path) as dirh:
for size, buf, attrs in dirh.readdir():
o = buf.decode(enc)
if o not in [".", ".."]:
recrse(path, o, attrs, size_all)
else:
size_all["size"] += conn.stat(path).filesize
else: # FTP
if not isFile:
def recrse(pth, finf, rslt):
if finf[0] == "d":
data = ftp_file_list(conn, pth)
for x in data.items():
recrse(pjoin(pth, x[0]), x[1], rslt)
elif finf[0] == "-":
rslt["size"] += int(finf.split()[4])
dat = ftp_file_list(conn, path)
for inf in dat.items():
recrse(pjoin(path, inf[0]), inf[1], size_all)
else:
size_all["size"] += conn.size(path)
class Connection:
""" manage all remote work with a ui thread and an thread for remote work """
def __init__(self, mode, encoding, path):
"""
constructor for Connection
:param mode: Connection mode - sftp/ftp
:type mode: str
:param encoding: encoding for remote login user
:type encoding: str
:param path: path on remote server
:type path: str
"""
self.cwd = path
self._mode = mode
self._enc = encoding
self.lock = Lock()
self._worker = None
self._ui_worker = None
self.stop_search = False
def connect(self, mode, host, port, name, password, encoding, path, ui=None):
"""
create or re-create connection (aborts current connection)
:param mode: Connection mode - sftp/ftp
:type mode: str
:param host: host name or ip address for remote server
:type host: str
:param port: port number for remote connection
:type port: int
:param name: user name for remote login
:type name: str
:param password: password for remote login user
:type password: str
:param encoding: encoding for remote login user
:type encoding: str
:param path: path on remote server
:type path: str
:param ui: root Tk object
:type ui: Tk
"""
if self._worker:
self._worker.disconnect(quit=True)
if self._ui_worker:
self._ui_worker.disconnect(quit=True)
self._mode = mode
self._enc = encoding
self.cwd = path
self._worker = ThreadWork(mode, host, port, name, password, encoding, 20, "worker", ui=ui)
self._ui_worker = ThreadWork(mode, host, port, name, password, encoding, 15, "ui_worker", ui=ui)
if ui:
ui.progress.configure(value=0)
self.get_listing(ui, path)
def disconnect(self, callback=None):
"""
disconnect the worker and abort all current tasks
:param callback: function object
:type callback: any
"""
if self._worker:
self._worker.disconnect()
if self._ui_worker:
self._ui_worker.disconnect()
if callback:
callback()
def progress_indeterminate_start(self, ui):
ui.progress.configure(value=0, mode="indeterminate")
ui.progress.start()
def progress_reset(self, ui):
ui.progress.stop()
ui.progress.configure(value=0, mode="determinate")
def _get_listing_worker(self, conn, ui_, path_, enc, sel):
"""
get the content of the defined path and insert it to the root view
:param conn: Connection object for sftp/ftp tasks
:type conn: object
:param ui_: root Tk object
:type ui_: Tk
:param path_: work directory
:type path_: str
:param enc: encoding for the current remote login user
:type enc: str
:param cb: callback function object
:type cb: function
:param sel: selected item
:type sel: str
"""
ui_.update_main_thread_from_thread(self.progress_indeterminate_start)
result = []
if self._mode == "SFTP":
try:
if not path_:
channel = conn.session.open_session()
channel.execute('pwd')
channel.wait_eof()
channel.close()
channel.wait_closed()
self.cwd = channel.read()[1].decode(enc).strip()
else:
self.cwd = path_
with conn.opendir(self.cwd) as dirh:
dat = []
if self.cwd != "/":
dat.append(["..", "", "", "", "", "", True, "", ui_.d_img])
for size, buf, attrs in sorted(dirh.readdir(),
key=(lambda f: (S_ISDIR(f[2].permissions) == 0, f[1].lower()))):
obj = buf.decode(enc)
if obj == "." or obj == "..":
continue
tpe = None
if S_ISDIR(attrs.permissions) != 0:
tpe = ui_.d_img
elif S_ISREG(attrs.permissions) != 0:
tpe = ui_.f_img
elif S_ISLNK(attrs.permissions) != 0:
tpe = ui_.l_img
dat.append([
obj, filemode(attrs.permissions),
datetime.fromtimestamp(attrs.mtime).strftime("%Y-%m-%d %H:%M:%S"),
attrs.filesize, attrs.uid, attrs.gid, attrs.permissions, attrs.mtime, tpe
])
ui_.update_main_thread_from_thread(insert, [dat, sel])
except SocketRecvError:
messagebox.showinfo("Lost connection", "The connection was lost.", parent=ui_)
ui_.update_main_thread_from_thread(self.progress_reset)
return
except (PermissionError, SFTPProtocolError, SFTPHandleError) as e:
messagebox.showwarning(
"Permission Denied",
"You don't have permission to see the content of this folder.",
parent=ui_
)
ui_.update_main_thread_from_thread(self.progress_reset)
return
else: # FTP
ui_data = []
if self.cwd != "/":
ui_data.append(["..", "", "", "", "", "", True, "", ui_.d_img])
if not path_:
self.cwd = conn.pwd()
data = ftp_file_list(conn, self.cwd)
for p in sorted(data.items(), key=lambda x: (x[1][0] != "d", x[0].lower())):
if not self._ui_worker.isConnected():
ui_.update_main_thread_from_thread(self.progress_reset)
return
d = p[1].split()
dt = None
if d[7].isnumeric():
dt = datetime.strptime(f"{d[5]}{d[6]}{d[7]}00:00", "%b%d%Y%H:%M")
else:
dt = datetime.strptime(f"{d[5]}{d[6]}{datetime.now().year}{d[7]}", "%b%d%Y%H:%M")
# if d[0][0] != "d":
# try:
# dt = datetime.strptime(
# conn.voidcmd("MDTM %s" % p[0]).split()[-1],
# "%Y%m%d%H%M%S"
# )
# except Exception as e:
# print(e)
tpe = None
if d[0][0] == "d":
tpe = ui_.d_img
elif d[0][0] == "-":
tpe = ui_.f_img
elif d[0][0] == "l":
tpe = ui_.l_img
ui_data.append([
p[0], d[0],
dt.strftime("%Y-%m-%d %H:%M:%S") if dt else "",
d[4], d[2], d[3], d[0][0] == "d", dt.timestamp() if dt else "", tpe
])
ui_.update_main_thread_from_thread(insert, [ui_data, sel])
ui_.update_main_thread_from_thread(self.progress_reset)
ui_.path.set(self.cwd)
def _cwd_dnl_worker(self, conn, ui_, path_, enc, item_nfo, updatefunc, donefunc):
"""
change into directory or start download of file - executed in separate thread
:param conn: Connection object for sftp/ftp tasks
:type conn: object
:param ui_: root Tk object
:type ui_: Tk
:param path_: file or directory
:type path_: str
:param enc: encoding for the current remote login user
:type enc: str
:param item_nfo: struct with information about path_
:type item_nfo: object
:param updatefunc: callback function for updating the ui (download progress)
:type updatefunc: function
:param donefunc: callback function to inform the user about the end of the download
:type donefunc: function
"""
last = basename(self.cwd)
if self._mode == "SFTP":
inf = None
if not path_:
channel = conn.session.open_session()
channel.execute('pwd')
channel.wait_eof()
channel.close()
channel.wait_closed()
p = channel.read()[1].decode(enc).strip()
if p:
path_ = normpath(p).replace("\\", "/")
self.cwd = path_
try:
inf = conn.stat(path_)
except SFTPProtocolError:
messagebox.showerror("Path Error",
"No such path or no permission to see this path.",
parent=ui_)
return
if S_ISDIR(inf.permissions) != 0:
self.cwd = normpath(path_).replace("\\", "/")
donefunc(refresh=True, path=self.cwd, selected=last)
else:
if S_ISLNK(conn.lstat(path_).permissions) != 0:
messagebox.showerror("Not supported",
"Can't download links yet.",
parent=ui_)
return
if item_nfo[0]:
destination = filedialog.askdirectory(
title="Choose download destination",
parent=ui_,
initialdir=Path.home()
)
if not destination:
return
self.download(
ui_,
pjoin(self.cwd, item_nfo[0]),
item_nfo[0],
(inf.atime, inf.mtime),
updatefunc,
donefunc,
True,
destination,
inf.filesize
)
elif self._mode == "FTP" and conn:
fd = False
if not item_nfo or item_nfo[0] == ".." or item_nfo[1][0] != "-":
try: # Try to change into path. If we can't, then it's either a file or insufficient permissions
conn.cwd(path_)
self.cwd = normpath(path_).replace("\\", "/")
donefunc(refresh=True, message="", path=self.cwd, selected=last)
fd = True
except error_perm:
if item_nfo[1][0] == "l":
messagebox.showerror("Not supported",
"Can't download links yet.",
parent=ui_)
return
elif not item_nfo or item_nfo[1][0] not in ["-", ]:
messagebox.showerror("Path Error",
"No such path or no permission to see this path.",
parent=ui_)
return
except Exception as e:
print(type(e), str(e))
if not item_nfo or item_nfo[1][0] not in ["-", ]:
messagebox.showerror("Path Error",
"No such path or no permission to see this path.",
parent=ui_)
return
if not fd:
ts = datetime.strptime(
item_nfo[2],
"%Y-%m-%d %H:%M:%S").timestamp()
destination = filedialog.askdirectory(
title="Choose download destination",
parent=ui_,
initialdir=Path.home()
)
if not destination:
return
self.download(ui_, self.cwd, item_nfo[0], (ts, ts), updatefunc, donefunc, True, destination, item_nfo[3])
def _search_worker(self, conn, path_, recursive_, depth_, filename_, sensitive_, regex_, resultfunc, donefunc):
"""
search for a file in the current path or in its subfolders - executed in separate thread
:param conn: Connection object for sftp/ftp tasks
:type conn: object
:param path_: file or directory
:type path_: str
:param recursive_: flag to search in subfolders
:type recursive_: bool
:param depth_: maximum depth of path
:type depth_: int
:param filename_: name/pattern to search for
:type filename_: str
:param sensitive_: flag for case sensitivity
:type sensitive_: bool
:param regex_: flag to use regular expressions to search with
:type regex_: bool
:param resultfunc: callback function to return results to UI
:type resultfunc: function
:param donefunc: callback to inform user about the end of search
:type donefunc: function
"""
if self._mode == "SFTP":
def recurse(pth):
current_depth = len(pth[len(path_):].split("/"))
if self.stop_search or (not recursive_ and current_depth > 1) or 0 < depth_ < current_depth:
return
try:
with conn.opendir(pth) as dirh:
for size, buf, attrs in sorted(
dirh.readdir(),
key=(lambda f: (S_ISREG(f[2].permissions) != 0, f[1]))):
obj = buf.decode(self._enc)
if obj in [".", ".."]:
continue
if S_ISDIR(attrs.permissions) != 0:
recurse(pjoin(pth, obj))
elif S_ISREG(attrs.permissions) != 0:
if not regex_ and ((sensitive_ and filename_ in obj) or (
not sensitive_ and filename_.lower() in obj.lower())):
resultfunc(pjoin(pth, obj))
elif regex_ and search(filename_, obj, 0 if sensitive_ else IGNORECASE):
resultfunc(pjoin(pth, obj))
elif S_ISLNK(attrs.permissions) != 0:
recurse(pjoin(pth, obj))
except SocketRecvError as e:
messagebox.showinfo("Lost connection", "The connection was lost.")
except (PermissionError, SFTPProtocolError, SFTPHandleError) as e:
print("error", type(e), str(e))
recurse(path_)
else: # FTP
def recurse(pth):
current_depth = len(pth[len(path_):].split("/"))
if self.stop_search or (not recursive_ and current_depth > 1) or 0 < depth_ < current_depth:
return
try:
data = ftp_file_list(conn, pth)
for p, i in data.items():
d = i.split()
if d[0][0] == "d":
recurse(pjoin(pth, p))
elif d[0][0] == "-":
if not regex_ and ((sensitive_ and filename_ in p) or (
not sensitive_ and filename_.lower() in p.lower())):
resultfunc(pjoin(pth, p))
elif regex_ and search(filename_, p, 0 if sensitive_ else IGNORECASE):
resultfunc(pjoin(pth, p))
elif d[0][0] == "l":
recurse(pjoin(pth, p))
except Exception as e:
print(type(e), str(e))
recurse(path_)
donefunc()
def _download_worker(self, conn, ui_, src_, file_, ts_, updatefunc, donefunc, isFile_=True, destination_="",
size_sum_=None):
"""
download files or folders - executed in separate thread
:param conn: Connection object for sftp/ftp tasks
:type conn: object
:param ui_: root Tk object
:type ui_: Tk
:param src_: original path
:type src_: str
:param file_: name of object (file or folder)
:type file_: str
:param ts_: timestamp tuple (atime, mtime)
:type ts_: tuple
:param updatefunc: callback function to update the UI
:type updatefunc: function
:param donefunc: callback function to inform the user about the end of a download
:type donefunc: function
:param isFile_: flag: true if it's a file else false
:type isFile_: bool
:param destination_: destination to download to
:type destination_: str
:param size_sum_: overall bytes to download
:type size_sum_: int
"""
if self._worker.quitting:
return
if isFile_:
if updatefunc:
updatefunc(maximum=size_sum_ if size_sum_ else 0)
if destination_:
overwrite = True
if exists(ojoin(destination_, file_)):
overwrite = messagebox.askokcancel(
"Overwrite existing file?",
"A file with the same name already exists. Do you want to override it?",
parent=ui_)
if overwrite:
if self._mode == "SFTP":
try:
with conn.open(src_, LIBSSH2_FXF_READ, LIBSSH2_SFTP_S_IRUSR) as inpt:
fstat = inpt.fstat()
self._worker.fileDescriptor = open(ojoin(destination_, file_), "wb", buffering=ui_.buffer_size)
while True:
res, buf = inpt.read(ui_.buffer_size)
if res == LIBSSH2_ERROR_SOCKET_RECV:
raise SocketRecvError
if not buf:
break
else:
self._worker.fileDescriptor.write(buf)
if updatefunc:
updatefunc(step=len(buf))
self._worker.fileDescriptor.close()
self._worker.fileDescriptor = None
utime(ojoin(destination_, file_), (fstat.atime, fstat.mtime))
except SCPProtocolError as e:
if self._worker.fileDescriptor:
self._worker.fileDescriptor.close()
self._worker.fileDescriptor = None
raise Exception("Insufficient Permissions")
# messagebox.showerror("Insufficient Permissions",
# "Could not receive file because of insufficient permissions.",
# parent=ui_)
else:
try:
conn.cwd(self.cwd)
csize = {"s": 0}
def handleDownload(block, fi, size_):
size_["s"] += len(block)
fi.write(block)
if updatefunc:
updatefunc(value=size_["s"])
self._worker.fileDescriptor = open(ojoin(destination_, file_), "wb+", buffering=ui_.buffer_size)
conn.retrbinary("RETR %s" % pjoin(src_, file_),
lambda blk: handleDownload(blk, self._worker.fileDescriptor, csize),
blocksize=ui_.buffer_size)
self._worker.fileDescriptor.close()
self._worker.fileDescriptor = None
utime(ojoin(destination_, file_), ts_)
except error_perm:
if self._worker.fileDescriptor:
self._worker.fileDescriptor.close()
self._worker.fileDescriptor = None
messagebox.showerror("Insufficient Permissions",
"Could not receive file because of insufficient permissions.",
parent=ui_)
remove(ojoin(destination_, file_))
else:
if destination_:
overwrite = True
if exists(ojoin(destination_, file_)):
overwrite = messagebox.askokcancel(
"Overwrite existing files?",
"A folder with the same name already exists. Do you want to override all contained files?",
parent=ui_)
else:
makedirs(ojoin(destination_, file_), exist_ok=True)
if overwrite:
if self._mode == "SFTP":
def recurse(orig, path, fi):
if self._worker.quitting:
return
if S_ISDIR(fi[1].permissions) != 0:
makedirs(path, exist_ok=True)
with conn.opendir(orig) as dirh_:
for size_, buf_, attrs_ in dirh_.readdir():
o_ = buf_.decode(self._enc)
if o_ not in [".", ".."]:
recurse(pjoin(orig, o_), pjoin(path, o_), (o_, attrs_))
elif S_ISREG(fi[1].permissions) != 0:
try:
with conn.open(src_, LIBSSH2_FXF_READ, LIBSSH2_SFTP_S_IRUSR) as inpt:
fstat = inpt.fstat()
self._worker.fileDescriptor = open(ojoin(destination_, file_), "wb", buffering=ui_.buffer_size)
while True:
res, buf = inpt.read(ui_.buffer_size)
if res == LIBSSH2_ERROR_SOCKET_RECV:
raise SocketRecvError
if not buf:
break
else:
self._worker.fileDescriptor.write(buf)
if updatefunc:
updatefunc(step=len(buf))
self._worker.fileDescriptor.close()
self._worker.fileDescriptor = None
utime(ojoin(destination_, file_), (fstat.atime, fstat.mtime))
except SCPProtocolError:
if self._worker.fileDescriptor:
self._worker.fileDescriptor.close()
self._worker.fileDescriptor = None
raise Exception("Insufficient Permissions")
# messagebox.showerror("Insufficient Permissions",
# "Could not receive file because of insufficient permissions.",
# parent=ui_)
size_all = {"size": size_sum_ if size_sum_ is not None else 0}
if size_sum_ is None:
if updatefunc:
updatefunc(mode="indeterminate", start=True, maximum=100)
get_size(conn, self._mode, self._enc, src_, size_all, isFile=False)
updatefunc(mode="determinate", stop=True, maximum=size_all["size"], value=0)
with conn.opendir(src_) as dirh:
for size, buf, attrs in dirh.readdir():
o = buf.decode(self._enc)
if o not in [".", ".."]:
recurse(pjoin(src_, o), pjoin(destination_, file_, o), (o, attrs))
else: # FTP
conn.cwd(self.cwd)
def recurse(path, fi):
if self._worker.quitting:
return
# print(path, fi)
if fi[0] == "d":
makedirs(ojoin(destination_, path[len(src_) + 1:]), exist_ok=True)
data = ftp_file_list(conn, path)
for x in data.items():
recurse(pjoin(path, x[0]), x[1])
elif fi[0] == "-":
# print("local", pjoin(destination, file, basename(path)))
# print("remote", path)
csize = {"": 0}
def handleDownload(block, fi, size_):
fi.write(block)
size_[""] += len(block)
if updatefunc:
updatefunc(value=size_[""])
self._worker.fileDescriptor = open(ojoin(destination_, path[len(src_) + 1:]), "wb+", buffering=ui_.buffer_size)
conn.retrbinary("RETR %s" % path,
lambda blk: handleDownload(blk, self._worker.fileDescriptor, csize),
blocksize=ui_.buffer_size)
try:
dt = None
if ":" in fi[-5:]:
dt = datetime.strptime(
datetime.now().strftime("%Y") + " ".join(fi.split()[-3:]), "%Y%b %d %H:%M")
else:
dt = datetime.strptime(" ".join(fi.split()[-3:]), "%b %d %Y")
self._worker.fileDescriptor.close()
self._worker.fileDescriptor = None
utime(ojoin(destination_, path[len(src_) + 1:]), (dt.timestamp(), dt.timestamp()))
except Exception as e:
if self._worker.fileDescriptor:
self._worker.fileDescriptor.close()
self._worker.fileDescriptor = None
print(type(e), e, path)
size_all = {"size": size_sum_ if size_sum_ is not None else 0}
if size_sum_ is None:
if updatefunc:
updatefunc(mode="indeterminate", start=True, maximum=100)
get_size(conn, self._mode, self._enc, pjoin(src_, file_), size_all, isFile=False)
updatefunc(mode="determinate", stop=True, maximum=size_all["size"], value=0)
dat = ftp_file_list(conn, pjoin(src_, file_))
for inf in dat.items():
recurse(pjoin(src_, file_, inf[0]), inf[1])
if not self._worker.quitting and donefunc:
donefunc(message="Download done!")
def _download_multi_worker(self, conn, ui_, sel, updatefunc, donefunc):
"""
download multiple objects from selected items - executed in separate thread
:param conn: Connection object for sftp/ftp tasks
:type conn: object
:param ui_: root Tk object
:type ui_: Tk
:param sel: list of selected item objects (including metadata)
:type sel: list of objects
:param updatefunc: callback function to update the UI
:type updatefunc: function
:param donefunc: callback function to inform the user about the end of all downloads
:type donefunc: function
"""
destination = filedialog.askdirectory(
title="Choose download destination", initialdir=Path.home())
if not destination:
return
updatefunc(value=0, maximum=100, mode="indeterminate", start=True)
size_all = {"size": 0}
for item in sel:
isFile = item["values"][0][0] == "-"
get_size(conn, self._mode, self._enc, pjoin(self.cwd, item["text"]), size_all, isFile)
updatefunc(mode="determinate", stop=True, maximum=size_all["size"], value=0)
for item in sel:
if item["values"][0][0] == "l":
messagebox.showwarning("Not supported",
"Can't download links yet. Skipping link.",
parent=ui_)
continue
isFile = item["values"][0][0] == "-"
if self._mode == "SFTP":
nfo = conn.lstat(pjoin(self.cwd, item["text"])) # Do not follow links
self.download(ui_, pjoin(self.cwd, item["text"]), item["text"], (nfo.atime, nfo.mtime),
updatefunc, donefunc, isFile, destination, size_all["size"])
else:
ts = None
if item["values"][-2]:
try:
ts = datetime.strptime(
conn.voidcmd("MDTM %s" % pjoin(self.cwd, item["text"])).split()[-1],
"%Y%m%d%H%M%S"
).timestamp()
except:
pass
self.download(ui_, self.cwd, item["text"], (ts, ts),
updatefunc, donefunc, isFile, destination, size_all["size"])
def _upload_files_worker(self, conn, ui_, files_, destination, updatefunc, donefunc):
"""
upload multiple local files - executed in separate thread
:param conn: Connection object for sftp/ftp tasks
:type conn: object
:param ui_: root Tk object
:type ui_: Tk
:param files_: files to upload
:type files_: list of str
:param destination: remote destination path
:type destination: str
:param updatefunc: callback function to update the UI
:type updatefunc: function
:param donefunc: callback function to inform the user about the end of all uploads
:type donefunc: function
"""
if files_ and len(files_) > 0 and destination:
if self._mode == "SFTP":
# dat = []
for file in files_:
if self._worker.quitting:
return
fifo = stat(file)
# chan = conn.session.scp_send64(
# pjoin(destination.strip(), basename(file)),
# fifo.st_mode & 0o777,
# fifo.st_size,
# fifo.st_mtime, fifo.st_atime)
# with open(file, 'rb') as lofi:
# while True:
# data = lofi.read(10 * 1024 * 1024)
# if not data:
# break
# else:
# _, sz = chan.write(data)
# if updatefunc:
# updatefunc(step=sz)
mode = LIBSSH2_SFTP_S_IRUSR | \
LIBSSH2_SFTP_S_IWUSR | \
LIBSSH2_SFTP_S_IRGRP | \
LIBSSH2_SFTP_S_IROTH
f_flags = LIBSSH2_FXF_CREAT | LIBSSH2_FXF_WRITE | LIBSSH2_FXF_TRUNC
self._worker.fileDescriptor = open(file, 'rb', buffering=ui_.buffer_size)
try:
with conn.open(pjoin(destination.strip(), basename(file)), f_flags, mode) as remfi:
while True:
data = self._worker.fileDescriptor.read(ui_.buffer_size)
if not data:
break
else:
_, sz = remfi.write(data)
if updatefunc:
updatefunc(step=sz)
attrs = SFTPAttributes()
attrs.flags = LIBSSH2_SFTP_ATTR_ACMODTIME | LIBSSH2_SFTP_ATTR_PERMISSIONS
attrs.atime = fifo.st_atime
attrs.mtime = fifo.st_mtime
attrs.permissions = fifo.st_mode
attrs.gid = fifo.st_gid
attrs.uid = fifo.st_uid
remfi.fsetstat(attrs)
except SFTPProtocolError:
raise Exception("Insufficient Permissions")
finally:
if self._worker.fileDescriptor:
self._worker.fileDescriptor.close()
self._worker.fileDescriptor = None
else:
conn.cwd(self.cwd)
# dat = []
for file in files_:
# fifo = stat(file)
if self._worker.quitting:
return
try:
def handl(blk):
if updatefunc:
updatefunc(step=len(blk))
self._worker.fileDescriptor = open(file, "rb", buffering=ui_.buffer_size)
conn.storbinary(
"STOR %s" % pjoin(destination, basename(file)), self._worker.fileDescriptor,
blocksize=ui_.buffer_size, callback=handl
)
conn.voidcmd("MFMT %s %s" % (
datetime.fromtimestamp(
getmtime(file)
).strftime("%Y%m%d%H%M%S"),
file
))
except Exception as e:
print(type(e), str(e))
finally:
if self._worker.fileDescriptor:
self._worker.fileDescriptor.close()
self._worker.fileDescriptor = None
if not self._worker.quitting and donefunc:
donefunc(message="Upload done!", refresh=True)
def _upload_folder_worker(self, conn, ui_, folder_, destination_, updatefunc, donefunc):
"""
upload local folder - executed in separate thread
:param conn: Connection object for sftp/ftp tasks
:type conn: object
:param ui_: root Tk object
:type ui_: Tk
:param folder_: local folder to upload
:type folder_: str
:param destination_: remote destination path
:type destination_: str
:param updatefunc: callback function to update the UI
:type updatefunc: function
:param donefunc: callback function to inform the user about the end of uploads
:type donefunc: function
"""
size_all = {"size": 0}
if folder_:
updatefunc(mode="indeterminate", value=100, start=True)
def recrse(pth, rslt):
for f in listdir(pth):
fp = ojoin(pth, f)
if isfile(fp) and not islink(fp):
rslt["size"] += getsize(fp)
elif isdir(fp) and not islink(fp):
recrse(fp, rslt)
recrse(folder_, size_all)
updatefunc(mode="determinate", maximum=size_all["size"], value=0, stop=True)
def recurse(dest, target):
if self._mode == "SFTP":
if islink(target):
return
elif isdir(target):
try:
flgs = LIBSSH2_FXF_CREAT | LIBSSH2_SFTP_S_IRWXU | \
LIBSSH2_SFTP_S_IRWXG | LIBSSH2_SFTP_S_IXOTH | \
LIBSSH2_SFTP_S_IROTH
conn.mkdir(pjoin(dest, basename(target)), flgs)
for f in listdir(target):
recurse(pjoin(dest, basename(target)),
pjoin(target, basename(f)))
except Exception as e:
print(target, type(e), str(e))
elif isfile(target):
fifo = stat(target)
mode = LIBSSH2_SFTP_S_IRUSR | \
LIBSSH2_SFTP_S_IWUSR | \
LIBSSH2_SFTP_S_IRGRP | \
LIBSSH2_SFTP_S_IROTH
f_flags = LIBSSH2_FXF_CREAT | LIBSSH2_FXF_WRITE | LIBSSH2_FXF_TRUNC
self._worker.fileDescriptor = open(target, 'rb')
# print("target", target)
# print("dest", pjoin(dest.strip(), basename(target)))
with conn.open(
pjoin(dest.strip(), basename(target)),
f_flags, mode) as remfi:
while True:
data = self._worker.fileDescriptor.read(1024 * 1024 * 10)
if not data:
break
else:
remfi.write(data)
updatefunc(step=len(data))
attrs = SFTPAttributes()
attrs.flags = LIBSSH2_SFTP_ATTR_ACMODTIME | LIBSSH2_SFTP_ATTR_PERMISSIONS
attrs.atime = fifo.st_atime
attrs.mtime = fifo.st_mtime
attrs.permissions = fifo.st_mode
attrs.gid = fifo.st_gid
attrs.uid = fifo.st_uid
remfi.fsetstat(attrs)
self._worker.fileDescriptor.close()
self._worker.fileDescriptor = None
else:
conn.cwd(self.cwd)
if islink(target):
return
elif isdir(target):
conn.mkd(
pjoin(dest, basename(target))
)
for f in listdir(target):
recurse(pjoin(dest, basename(target)),
pjoin(target, basename(f)))
elif isfile(target):
try:
def handl(blk):
updatefunc(step=len(blk))
self._worker.fileDescriptor = open(target, "rb")
conn.storbinary(
"STOR %s" % pjoin(dest, basename(target)),
self._worker.fileDescriptor, blocksize=ui_.buffer_size, callback=handl
)
conn.voidcmd(
"MDTM %s %s" % (
datetime.fromtimestamp(
getmtime(target)
).strftime("%Y%m%d%H%M%S"),
pjoin(dest, basename(target))
)
)
except Exception as e:
print(type(e), str(e))
finally:
if self._worker.fileDescriptor:
self._worker.fileDescriptor.close()
self._worker.fileDescriptor = None
if folder_ and destination_:
if self._mode == "SFTP":
try:
p = self.cwd
tmp = ""
if p in destination_:
tmp += destination_[len(p) + 1:] # +1 to remove slash