-
Notifications
You must be signed in to change notification settings - Fork 4
/
remote.py
1701 lines (1572 loc) · 75.2 KB
/
remote.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
# -*- coding: utf-8 -*-
# Copyright 2007-2016 Charles du Jeu - Abstrium SAS <team (at) pydio.com>
# This file is part of Pydio.
#
# Pydio 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.
#
# Pydio 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 Pydio. If not, see <http://www.gnu.org/licenses/>.
#
# The latest code can be found at <http://pyd.io/>.
#
import urllib
import json
import hmac
import random
import unicodedata
import platform
from hashlib import sha256
from hashlib import sha1
from urlparse import urlparse
import math
import threading
import websocket
import ssl
from requests.exceptions import ConnectionError, RequestException
from lxml import etree
import keyring
from keyring.errors import PasswordSetError
import xml.etree.ElementTree as ET
from pydio_exceptions import PydioSdkException, PydioSdkBasicAuthException, PydioSdkTokenAuthException, \
PydioSdkQuotaException, PydioSdkPermissionException, PydioSdkTokenAuthNotSupportedException, PydioSdkDefaultException
from util import *
try:
from pydio.utils.functions import hashfile
from pydio import TRANSFER_RATE_SIGNAL, TRANSFER_CALLBACK_SIGNAL
from pydio.utils import i18n
_ = i18n.language.ugettext
except ImportError:
try:
from utils.functions import hashfile
from utils import i18n
_ = i18n.language.ugettext
except ImportError:
from util import hashfile
try:
TRANSFER_RATE_SIGNAL
except NameError:
TRANSFER_RATE_SIGNAL = 'transfer_rate'
TRANSFER_CALLBACK_SIGNAL = 'transfer_callback'
try:
_
except NameError:
def _(message):
""" Fake i18n patch """
return message
""" For request debugging
from httplib import HTTPConnection
HTTPConnection.debuglevel = 1
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
#"""
"""
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
#"""
PYDIO_SDK_MAX_UPLOAD_PIECES = 40 * 1024 * 1024
class PydioSdk():
def __init__(self, url='', ws_id='', remote_folder='', user_id='', auth=(), device_id='python_client',
skip_ssl_verify=False, proxies=None, timeout=20):
self.ws_id = ws_id
self.device_id = device_id
self.verify_ssl = not skip_ssl_verify
if self.verify_ssl and "REQUESTS_CA_BUNDLE" in os.environ:
self.verify_ssl = os.environ["REQUESTS_CA_BUNDLE"]
self.base_url = url.rstrip('/') + '/api/'
self.url = url.rstrip('/') + '/api/' + ws_id
self.remote_folder = remote_folder
self.user_id = user_id
self.interrupt_tasks = False
self.upload_max_size = PYDIO_SDK_MAX_UPLOAD_PIECES
self.rsync_server_support = False
self.stat_slice_number = 200
self.stick_to_basic = False
if user_id:
self.auth = (user_id, keyring.get_password(url, user_id))
else:
self.auth = auth
self.rsync_supported = False
self.proxies = proxies
self.timeout = timeout
# for websockets logic, sdk's state
self.should_fetch_changes = False
self.remote_repo_id = None
self.websocket_server_data = {}
self.waiter = None
def set_server_configs(self, configs):
"""
Server specific capacities and limitations, provided by the server itself
:param configs: dict()
:return:
"""
if 'UPLOAD_MAX_SIZE' in configs and configs['UPLOAD_MAX_SIZE']:
self.upload_max_size = min(int(float(configs['UPLOAD_MAX_SIZE'])), PYDIO_SDK_MAX_UPLOAD_PIECES)
if 'RSYNC_SUPPORTED' in configs and configs['RSYNC_SUPPORTED'] == "true":
self.rsync_server_support = True
#self.upload_max_size = 8*1024*1024;
if 'RSYNC_SUPPORTED' in configs:
self.rsync_supported = configs['RSYNC_SUPPORTED'] == 'true'
pass
def set_interrupt(self):
self.interrupt_tasks = True
def remove_interrupt(self):
self.interrupt_tasks = False
def urlencode_normalized(self, unicode_path):
"""
Make sure the urlencoding is consistent between various platforms
E.g, we force the accented chars to be encoded as one char, not the ascci + accent.
:param unicode_path:
:return:
"""
if platform.system() == 'Darwin':
try:
test = unicodedata.normalize('NFC', unicode_path)
unicode_path = test
except ValueError as e:
logging.exception(e)
pass
return urllib.pathname2url(unicode_path.encode('utf-8'))
def normalize(self, unicode_path):
try:
test = unicodedata.normalize('NFC', unicode_path)
return test
except ValueError as e:
logging.exception(e)
return unicode_path
def normalize_reverse(self, unicode_path):
if platform.system() == 'Darwin':
try:
test = unicodedata.normalize('NFD', unicode_path)
return test
except ValueError as e:
logging.exception(e)
return unicode_path
else:
return unicode_path
def set_tokens(self, tokens):
try:
user = self.user_id + '-token'
password = tokens['t'] + ':' + tokens['p']
keyring.set_password(self.base_url, user, password)
except PasswordSetError as pe:
logging.info("Failed to set_tokens " + self.base_url + " " + self.ws_id)
logging.exception(pe)
logging.error(_("Cannot store tokens in keychain, there might be an OS permission issue!"))
def get_tokens(self, from_keyring=False):
k_tok = keyring.get_password(self.base_url, self.user_id + '-token')
if k_tok:
parts = k_tok.split(':')
tokens = {'t': parts[0], 'p': parts[1]}
return tokens
else:
return False
def basic_authenticate(self):
"""
Use basic-http authenticate to get a key/pair token instead of passing the
users credentials at each requests
:return:dict()
"""
# only authenticate if you're the token latest owner RACE CONDITION of DEATH
tokens = self.get_tokens()
org_tokens = self.get_tokens()
url = self.base_url + 'pydio/keystore_generate_auth_token/' + self.device_id
resp = requests.get(url=url, auth=self.auth, verify=self.verify_ssl, proxies=self.proxies)
if resp.status_code == 401:
raise PydioSdkBasicAuthException(_('Authentication Error'))
# If content is empty (but not error status code), the token based auth may not be active
# We should switch to basic
if resp.content == '':
raise PydioSdkTokenAuthNotSupportedException("token_auth")
try:
tokens = json.loads(resp.content, strict=False)
except ValueError as v:
raise PydioSdkException("basic_auth", "", "Cannot parse JSON result: " + resp.content + "")
keyring_tokens = self.get_tokens() # make sure the token wasn't updated during this update
if not keyring_tokens or (keyring_tokens['t'] == org_tokens['t'] and keyring_tokens['p'] == org_tokens['p']):
self.set_tokens(tokens)
else:
tokens = keyring_tokens
return tokens
def perform_basic(self, url, request_type='get', data=None, files=None, headers=None, stream=False, with_progress=False):
"""
:param headers:
:param url: str url to query
:param request_type: str http method, default is "get"
:param data: dict query parameters
:param files: dict files, described as {'fieldname':'path/to/file'}
:param stream: bool get response as a stream
:param with_progress: dict an object that can be updated with various progress data
:return: Http response
"""
if request_type == 'get':
try:
resp = requests.get(url=url, stream=stream, timeout=self.timeout, verify=self.verify_ssl, headers=headers,
auth=self.auth, proxies=self.proxies)
except ConnectionError as e:
raise
elif request_type == 'post':
if not data:
data = {}
if files:
resp = self.upload_file_with_progress(url, dict(**data), files, stream, with_progress,
max_size=self.upload_max_size, auth=self.auth)
else:
resp = requests.post(
url=url,
data=data,
stream=stream,
timeout=self.timeout,
verify=self.verify_ssl,
headers=headers,
auth=self.auth,
proxies=self.proxies)
else:
raise PydioSdkTokenAuthException(_("Unsupported HTTP method"))
if resp.status_code == 401:
raise PydioSdkTokenAuthException(_("Authentication Exception"))
return resp
def perform_with_tokens(self, token, private, url, request_type='get', data=None, files=None, headers=None, stream=False,
with_progress=False):
"""
:param headers:
:param token: str the token.
:param private: str private key associated to token
:param url: str url to query
:param request_type: str http method, default is "get"
:param data: dict query parameters
:param files: dict files, described as {'fieldname':'path/to/file'}
:param stream: bool get response as a stream
:param with_progress: dict an object that can be updated with various progress data
:return: Http response
"""
nonce = sha1(str(random.random())).hexdigest()
uri = urlparse(url).path.rstrip('/')
msg = uri + ':' + nonce + ':' + private
the_hash = hmac.new(str(token), str(msg), sha256)
auth_hash = nonce + ':' + the_hash.hexdigest()
if request_type == 'get':
auth_string = 'auth_token=' + token + '&auth_hash=' + auth_hash
if '?' in url:
url += '&' + auth_string
else:
url += '?' + auth_string
try:
resp = requests.get(url=url, stream=stream, timeout=self.timeout, verify=self.verify_ssl,
headers=headers, proxies=self.proxies)
except ConnectionError as e:
raise
elif request_type == 'post':
if not data:
data = {}
data['auth_token'] = token
data['auth_hash'] = auth_hash
if files:
resp = self.upload_file_with_progress(url, dict(**data), files, stream, with_progress,
max_size=self.upload_max_size)
else:
resp = requests.post(
url=url,
data=data,
stream=stream,
timeout=self.timeout,
verify=self.verify_ssl,
headers=headers,
proxies=self.proxies)
else:
raise PydioSdkTokenAuthException(_("Unsupported HTTP method"))
if resp.status_code == 401:
raise PydioSdkTokenAuthException(_("Authentication Exception"))
return resp
def perform_request(self, url, type='get', data=None, files=None, headers=None, stream=False, with_progress=False):
"""
Perform an http request.
There's a one-time loop, as it first tries to use the auth tokens. If the the token auth fails, it may just
mean that the token key/pair is expired. So we try once to get fresh new tokens with basic_http auth and
re-run query with new tokens.
:param headers:
:param url: str url to query
:param type: str http method, default is "get"
:param data: dict query parameters
:param files: dict files, described as {'filename':'path/to/file'}
:param stream: bool get response as a stream
:param with_progress: dict an object that can be updated with various progress data
:return:
"""
# We know that token auth is not supported anyway
#logging.info(url)
if self.stick_to_basic:
return self.perform_basic(url, request_type=type, data=data, files=files, headers=headers, stream=stream,
with_progress=with_progress)
tokens = self.get_tokens()
if not tokens:
try:
tokens = self.basic_authenticate()
except PydioSdkTokenAuthNotSupportedException as pne:
logging.info('Switching to permanent basic auth, as tokens were not correctly received. This is not '
'good for performances, but might be necessary for session credential based setups.')
self.stick_to_basic = True
return self.perform_basic(url, request_type=type, data=data, files=files, headers=headers, stream=stream,
with_progress=with_progress)
return self.perform_with_tokens(tokens['t'], tokens['p'], url, type, data, files,
headers=headers, stream=stream)
else:
try:
resp = self.perform_with_tokens(tokens['t'], tokens['p'], url, type, data, files, headers=headers,
stream=stream, with_progress=with_progress)
return resp
except requests.exceptions.ConnectionError:
raise
except PydioSdkTokenAuthException as pTok:
# Token exception -> Authenticate
try:
tokens = self.basic_authenticate()
except PydioSdkTokenAuthNotSupportedException:
self.stick_to_basic = True
logging.info('Switching to permanent basic auth, as tokens were not correctly received. This is not '
'good for performances, but might be necessary for session credential based setups.')
return self.perform_basic(url, request_type=type, data=data, files=files, headers=headers, stream=stream,
with_progress=with_progress)
try:
return self.perform_with_tokens(tokens['t'], tokens['p'], url, type, data, files,
headers=headers, stream=stream, with_progress=with_progress)
except PydioSdkTokenAuthException as secTok:
logging.exception("(2) Token problem " + self.base_url + " " + self.ws_id)
raise secTok
def check_basepath(self):
if self.remote_folder:
stat = self.stat('')
return True if stat else False
else:
return True
def changes(self, last_seq):
"""
Get the list of changes detected on server since a given sequence number
:param last_seq:int
:return:list a list of changes
"""
url = self.url + '/changes/' + str(last_seq)
#logging.info(url)
if self.remote_folder:
url += '?filter=' + self.remote_folder
try:
resp = self.perform_request(url=url)
except requests.exceptions.ConnectionError:
raise
try:
if platform.system() == "Darwin":
return json.loads(self.normalize_reverse(resp.content.decode('unicode_escape')), strict=False)
else:
return json.loads(self.normalize(resp.content.decode('unicode_escape')), strict=False)
except ValueError as v:
logging.exception(v)
raise Exception(_("Invalid JSON value received while getting remote changes. Is the server correctly configured?"))
def changes_stream(self, last_seq, callback):
"""
Get the list of changes detected on server since a given sequence number
:param last_seq:int
:change_store: AbstractChangeStore
:return:list a list of changes
"""
if last_seq == 0:
perform_flattening = "true"
else:
perform_flattening = "false"
url = self.url + '/changes/' + str(last_seq) + '/?stream=true'
if self.remote_folder:
url += '&filter=' + self.remote_folder
url += '&flatten=' + perform_flattening
resp = self.perform_request(url=url, stream=True)
info = dict()
info['max_seq'] = last_seq
for line in resp.iter_lines(chunk_size=512):
if line:
if str(line).startswith('LAST_SEQ'):
#call the merge function with NULL row
callback('remote', None, info)
return int(line.split(':')[1])
else:
try:
if platform.system() == "Darwin":
line = self.normalize_reverse(line.decode('unicode_escape'))
one_change = json.loads(line, strict=False)
node = one_change.pop('node')
one_change = dict(node.items() + one_change.items())
callback('remote', one_change, info)
except ValueError as v:
logging.error('Invalid JSON Response, line was ' + str(line))
raise Exception(_('Invalid JSON value received while getting remote changes'))
except Exception as e:
logging.exception(e)
raise e
def stat(self, path, with_hash=False, partial_hash=None):
"""
Equivalent of the local fstat() on the remote server.
:param path: path of node from the workspace root
:param with_hash: stat result can be enriched with the node hash
:return:dict a list of key like
{
dev: 16777218,
ino: 4062280,
mode: 16895,
nlink: 15,
uid: 70,
gid: 20,
rdev: 0,
size: 510,
atime: 1401915891,
mtime: 1399883020,
ctime: 1399883020,
blksize: 4096,
blocks: 0
}
"""
if self.interrupt_tasks:
raise PydioSdkException("stat", path=path, detail=_('Task interrupted by user'))
path = self.remote_folder + path
action = '/stat_hash' if with_hash else '/stat'
try:
url = self.url + action + self.urlencode_normalized(path)
if partial_hash:
h = {'range': 'bytes=%i-%i' % (partial_hash[0], partial_hash[1])}
resp = self.perform_request(url, headers=h)
else:
resp = self.perform_request(url)
try:
content = resp.content
if platform.system() == "Darwin":
content = self.normalize_reverse(content.decode('unicode_escape'))
data = json.loads(content, strict=False)
except ValueError as ve:
logging.exception(ve)
if content:
logging.info(content)
return False
logging.debug("data: %s" % data)
if not data:
return False
if len(data) > 0 and 'size' in data:
return data
else:
return False
except requests.exceptions.ConnectionError as ce:
logging.error("Connection Error " + str(ce))
except requests.exceptions.Timeout as ce:
logging.error("Timeout Error " + str(ce))
except Exception, ex:
logging.exception(ex)
logging.warning("Stat failed", exc_info=ex)
return False
def bulk_stat(self, pathes, result=None, with_hash=False):
"""
Perform a stat operation (see self.stat()) but on a set of nodes. Very important to use that method instead
of sending tons of small stat requests to server. To keep POST content reasonable, pathes will be sent 200 by
200.
:param pathes: list() of node pathes
:param result: dict() an accumulator for the results
:param with_hash: bool whether to ask for files hash or not (md5)
:return:
"""
if self.interrupt_tasks:
raise PydioSdkException("stat", path=pathes[0], detail=_('Task interrupted by user'))
from requests.exceptions import Timeout
# NORMALIZE PATHES FROM START
pathes = map(lambda p: self.normalize(p), pathes)
action = '/stat_hash' if with_hash else '/stat'
data = dict()
maxlen = min(len(pathes), self.stat_slice_number)
if platform.system() == "Darwin":
clean_pathes = map(lambda t: self.remote_folder + t.replace('\\', '/'), filter(lambda x: self.normalize_reverse(x) != '', pathes[:maxlen]))
else:
clean_pathes = map(lambda t: self.remote_folder + t.replace('\\', '/'), filter(lambda x: x != '', pathes[:maxlen]))
data['nodes[]'] = map(lambda p: self.normalize(p), clean_pathes)
url = self.url + action + self.urlencode_normalized(clean_pathes[0])
try:
resp = self.perform_request(url, type='post', data=data)
except Timeout:
if self.stat_slice_number < 20:
raise
self.stat_slice_number = int(math.floor(self.stat_slice_number / 2))
logging.info('Reduce bulk stat slice number to %d', self.stat_slice_number)
return self.bulk_stat(pathes, result=result, with_hash=with_hash)
rsp_content_type = resp.headers['content-type']
rsp_content = resp.content
if rsp_content_type == 'text/xml; charset=UTF-8':
tree = etree.fromstring(rsp_content)
msg = tree.xpath("/tree/message")[0]
e = PydioSdkException
if msg.get("type") == "ERROR":
if "contains forbidden characters" in msg.text:
data = dict()
valid_pathes = list()
for p in pathes:
st = self.stat(p, with_hash=True)
if st:
data[p] = st
valid_pathes.push(p)
pathes = valid_pathes
#raise e("stat", "", "one of the paths contains unsupported characters [\"]", code=400)
else:
raise e("stat", "", "server returned an unexpected message")
else:
try:
# Possible Composed, Decomposed utf-8 is handled later...
data = json.loads(rsp_content, strict=False)
except ValueError:
logging.debug("url: %s" % url)
logging.info("resp.content: %s" % resp.content)
raise
if len(pathes) == 1:
englob = dict()
englob[self.remote_folder + pathes[0]] = data
data = englob
if result:
replaced = result
else:
replaced = dict()
for (p, stat) in data.items():
if self.remote_folder:
p = p[len(self.remote_folder):]
#replaced[os.path.normpath(p)] = stat
p1 = os.path.normpath(p)
p2 = os.path.normpath(self.normalize_reverse(p))
p3 = p
p4 = self.normalize_reverse(p)
if p2 in pathes:
replaced[p2] = stat
pathes.remove(p2)
elif p1 in pathes:
replaced[p1] = stat
pathes.remove(p1)
elif p3 in pathes:
replaced[p3] = stat
pathes.remove(p3)
elif p4 in pathes:
replaced[p4] = stat
pathes.remove(p4)
else:
#pass
logging.info('Fatal charset error, cannot find files (%s, %s, %s, %s) in %s' % (repr(p1), repr(p2), repr(p3), repr(p4), repr(pathes),))
raise PydioSdkException('bulk_stat', p1, "Encoding problem, failed emptying bulk_stat, "
"exiting to avoid infinite loop")
if len(pathes):
self.bulk_stat(pathes, result=replaced, with_hash=with_hash)
return replaced
def mkdir(self, path):
"""
Create a directory of the server
:param path: path of the new directory to create
:return: result of the server query, see API
"""
url = self.url + '/mkdir' + self.urlencode_normalized((self.remote_folder + path))
resp = self.perform_request(url=url)
self.is_pydio_error_response(resp)
return resp.content
def bulk_mkdir(self, pathes):
"""
Create many directories at once
:param pathes: a set of directories to create
:return: content of the response
"""
data = dict()
data['ignore_exists'] = 'true'
data['nodes[]'] = map(lambda t: self.normalize(self.remote_folder + t), filter(lambda x: x != '', pathes))
url = self.url + '/mkdir' + self.urlencode_normalized(self.remote_folder + pathes[0])
resp = self.perform_request(url=url, type='post', data=data)
self.is_pydio_error_response(resp)
return resp.content
def mkfile(self, path, localstat=None):
"""
Create an empty file on the server
:param path: node path
:return: result of the server query
"""
resp = None
if localstat is not None:
if not self.stat(path) and localstat['size'] == 0:
url = self.url + '/mkfile' + self.urlencode_normalized((self.remote_folder + path)) + '?force=true'
resp = self.perform_request(url=url)
self.is_pydio_error_response(resp)
return resp.content
else:
url = self.url + '/mkfile' + self.urlencode_normalized((self.remote_folder + path)) + '?force=true'
resp = self.perform_request(url=url)
self.is_pydio_error_response(resp)
return resp.content
def rename(self, source, target):
"""
Rename a path to another. Will decide automatically to trigger a rename or a move in the API.
:param source: origin path
:param target: target path
:return: response of the server
"""
if os.path.dirname(source) == os.path.dirname(target):
# logging.debug("[sdk remote] /rename " + source + " to " + target)
url = self.url + '/rename'
data = dict(file=self.normalize(self.remote_folder + source).encode('utf-8'),
dest=self.normalize(self.remote_folder + target).encode('utf-8'))
elif os.path.split(source)[-1] == os.path.split(target)[-1]:
# logging.debug("[sdk remote] /move " + source + " into " + target)
url = self.url + '/move'
data = dict(file=(self.normalize(self.remote_folder + source)).encode('utf-8'),
dest=os.path.dirname((self.normalize(self.remote_folder + target).encode('utf-8'))))
else:
# logging.debug("[remote sdk debug] MOVEANDRENAME " + source + " " + target)
url1 = self.url + '/rename'
url2 = self.url + '/move'
tmpname = os.path.join(self.remote_folder, os.path.join(*os.path.split(source)[:-1]), os.path.split(target)[-1])
data1 = dict(file=self.normalize(self.remote_folder + source).encode('utf-8'),
dest=self.normalize(tmpname).encode('utf-8'))
data2 = dict(file=self.normalize(tmpname).encode('utf-8'),
dest=os.path.dirname((self.normalize(self.remote_folder + target).encode('utf-8'))))
resp1 = self.perform_request(url=url1, type='post', data=data1)
resp2 = self.perform_request(url=url2, type='post', data=data2)
self.is_pydio_error_response(resp1)
self.is_pydio_error_response(resp2)
return resp1.content + resp2.content
resp = self.perform_request(url=url, type='post', data=data)
self.is_pydio_error_response(resp)
return resp.content
def lsync(self, source=None, target=None, copy=False):
"""
Rename a path to another. Will decide automatically to trigger a rename or a move in the API.
:param source: origin path
:param target: target path
:return: response of the server
"""
url = self.url + '/lsync'
data = dict()
if source:
data['from'] = self.normalize(self.remote_folder + source).encode('utf-8')
if target:
data['to'] = self.normalize(self.remote_folder + target).encode('utf-8')
if copy:
data['copy'] = 'true'
resp = self.perform_request(url=url, type='post', data=data)
self.is_pydio_error_response(resp)
return resp.content
def delete(self, path):
"""
Delete a resource on the server
:param path: node path
:return: response of the server
"""
url = self.url + '/delete' + self.urlencode_normalized((self.remote_folder + path))
data = dict(file=self.normalize(self.remote_folder + path).encode('utf-8'))
resp = self.perform_request(url=url, type='post', data=data)
self.is_pydio_error_response(resp)
return resp.content
def load_server_configs(self):
"""
Load the plugins from the registry and parse some of the exposed parameters of the plugins.
Currently supports the uploaders paramaters, and the filehasher.
:return: dict() parsed configs
"""
url = self.base_url + 'pydio/state/plugins?format=json'
#logging.info(url)
resp = self.perform_request(url=url)
server_data = dict()
try:
data = json.loads(resp.content, strict=False)
plugins = data['plugins']
for p in plugins['ajxpcore']:
if p['@id'] == 'core.uploader':
if 'plugin_configs' in p and 'property' in p['plugin_configs']:
properties = p['plugin_configs']['property']
for prop in properties:
server_data[prop['@name']] = prop['$']
if "meta" in plugins:
for p in plugins['meta']:
if p['@id'] == 'meta.filehasher':
if 'plugin_configs' in p and 'property' in p['plugin_configs']:
properties = p['plugin_configs']['property']
if '@name' in properties:
server_data[properties['@name']] = properties['$']
else:
for prop in properties:
server_data[prop['@name']] = prop['$']
#logging.info(json.dumps(data['plugins']['ajxp_plugin'], indent=4))
#logging.info(json.dumps(plugins['ajxp_plugin'], indent=4))
#if hasattr(plugins, 'ajxp_plugin'):
# Get websocket information... #yolo
for p in data['plugins']['ajxp_plugin']:
try:
if p['@id'] == 'core.mq':
for prop in p['plugin_configs']['property']:
if prop['@name'] not in ['BOOSTER_WS_ADVANCED', 'BOOSTER_UPLOAD_ADVANCED']:
self.websocket_server_data[prop['@name']] = prop['$'].replace('\\', '').replace('"', '')
else:
self.websocket_server_data[prop['@name']] = json.loads(prop['$'].replace('\\', ''), strict=False)
except KeyError:
pass
#logging.info(url + " : " + str(self.websocket_server_data))
else:
logging.info("Meta was not found in plugin information.")
except KeyError as e:
logging.exception(e)
return server_data
def upload_url(self, path):
"""
Generate a signed URI to upload to depending on supported server features
:param file_path:
:return: the url on which the file should be uploaded to
"""
# TEMPORARILY DISABLE
return self.url + '/upload/put' + self.urlencode_normalized((self.remote_folder + os.path.dirname(path)))
# BOOSTER_MAIN_SECURE or self.url ?
url = None
file_path = self.urlencode_normalized(path)
try:
host, port, prot = None, None, 'http'
if 'BOOSTER_UPLOAD_ADVANCED' in self.websocket_server_data and \
'UPLOAD_ACTIVE' in self.websocket_server_data and \
self.websocket_server_data['UPLOAD_ACTIVE'] == 'true':
if 'booster_upload_advanced' in self.websocket_server_data['BOOSTER_UPLOAD_ADVANCED'] and \
self.websocket_server_data['BOOSTER_UPLOAD_ADVANCED']['booster_upload_advanced'] == 'custom':
if 'UPLOAD_HOST' in self.websocket_server_data:
host = self.websocket_server_data['UPLOAD_HOST']
if 'UPLOAD_PORT' in self.websocket_server_data:
port = self.websocket_server_data['UPLOAD_PORT']
else:
host = self.websocket_server_data['BOOSTER_MAIN_HOST']
port = self.websocket_server_data['BOOSTER_MAIN_PORT']
if 'BOOSTER_MAIN_SECURE' in self.websocket_server_data and \
self.websocket_server_data['BOOSTER_MAIN_SECURE'] == 'true':
prot = 'https'
if 'UPLOAD_SECURE' in self.websocket_server_data and \
self.websocket_server_data['UPLOAD_SECURE'] == 'true':
prot = 'https'
if self.remote_repo_id is None:
self.remote_repo_id = self.get_user_rep()
nonce = sha1(str(random.random())).hexdigest()
uri = '/api/' + self.remote_repo_id + '/upload/put' + os.path.dirname(file_path)
#logging.info("URI: " + uri)
tokens = self.get_tokens()
msg = uri + ':' + nonce + ':' + tokens['p']
the_hash = hmac.new(str(tokens['t']), str(msg), sha256)
auth_hash = nonce + ':' + the_hash.hexdigest()
mess = 'auth_hash=' + auth_hash + '&auth_token=' + tokens['t']
url = prot + "://" + host + ":" + port + "/" + self.websocket_server_data['UPLOAD_PATH'] + '/' + self.remote_repo_id + file_path + '?' + mess
#logging.info('UPLOAD TYPE 2')
except Exception as e:
logging.exception(e)
url = self.url + '/upload/put' + self.urlencode_normalized((self.remote_folder + os.path.dirname(path)))
return url
def upload_and_hashstat(self, local, local_stat, path, status_handler, callback_dict=None, max_upload_size=-1):
"""
Upload a file to the server.
:param local: file path
:param local_stat: stat of the file
:param path: target path on the server
:param callback_dict: an dict that can be fed with progress data
:param max_upload_size: a known or arbitrary upload max size. If the file file is bigger, it will be
chunked into many POST requests
:return: Server response
"""
if not local_stat:
raise PydioSdkException('upload', path, _('Local file to upload not found!'), 1404)
if local_stat['size'] == 0 and not self.stat(path):
self.mkfile(path)
new = self.stat(path)
if not new or not (new['size'] == local_stat['size']):
raise PydioSdkException('upload', path, _('File not correct after upload (expected size was 0 bytes)'))
return True
# Wait for file size to be stable
with open(local, 'r') as f:
f.seek(0, 2) # end of file
size = f.tell()
while True:
f.seek(0, 2) # end of file
if size == f.tell():
break
else:
logging.info(" Waiting for file write to end...")
time.sleep(.8)
size = f.tell()
existing_part = False
if (self.upload_max_size - 4096) < local_stat['size']:
self.has_disk_space_for_upload(path, local_stat['size'])
existing_part = self.stat(path+'.dlpart', True)
dirpath = os.path.dirname(path)
if dirpath and dirpath != '/':
folder = self.stat(dirpath)
if not folder:
self.mkdir(os.path.dirname(path))
url = self.upload_url(path)
files = {
'userfile_0': local
}
if existing_part:
files['existing_dlpart'] = existing_part
data = {
'force_post': 'true',
'xhr_uploader': 'true',
'urlencoded_filename': self.urlencode_normalized(os.path.basename(path))
}
resp = None
#logging.info(data)
try:
resp = self.perform_request(url=url, type='post', data=data, files=files, with_progress=callback_dict)
except PydioSdkDefaultException as e:
logging.exception(e)
if resp and resp.content:
logging.info(resp.content)
status_handler.update_node_status(path, 'PENDING')
if e.message == '507':
usage, total = self.quota_usage()
raise PydioSdkQuotaException(path, local_stat['size'], usage, total)
if e.message == '412':
raise PydioSdkPermissionException('Cannot upload '+os.path.basename(path)+' in directory '+os.path.dirname(path))
if "(411)" in e.message:
return True
#raise PydioSdkException("stat", path, "contains forbidden characters", 400)
else:
raise e
except RequestException as ce:
status_handler.update_node_status(path, 'PENDING')
raise PydioSdkException("upload", str(path), 'RequestException: ' + str(ce))
new = self.stat(path)
if not new or not (new['size'] == local_stat['size']):
status_handler.update_node_status(path, 'PENDING')
beginning_filename = path.rfind('/')
if beginning_filename > -1 and path[beginning_filename+1] == " ":
raise PydioSdkException('upload', path, _("File beginning with a 'space' shouldn't be uploaded"))
raise PydioSdkException('upload', path, _('File is incorrect after upload'))
return True
def upload(self, local, local_stat, path, callback_dict=None, max_upload_size=-1):
"""
Upload a file to the server.
:param local: file path
:param local_stat: stat of the file
:param path: target path on the server
:param callback_dict: an dict that can be fed with progress data
:param max_upload_size: a known or arbitrary upload max size. If the file file is bigger, it will be
chunked into many POST requests
:return: Server response
"""
if not local_stat:
raise PydioSdkException('upload', path, _('Local file to upload not found!'))
existing_part = False
if (self.upload_max_size - 4096) < local_stat['size']:
self.has_disk_space_for_upload(path, local_stat['size'])
existing_part = self.stat(path+'.dlpart', True)
dirpath = os.path.dirname(path)
if dirpath and dirpath != '/':
folder = self.stat(dirpath)
if not folder:
self.mkdir(os.path.dirname(path))
url = self.url + '/upload/put' + self.urlencode_normalized((self.remote_folder + os.path.dirname(path)))
files = {
'userfile_0': local
}
if existing_part:
files['existing_dlpart'] = existing_part
data = {
'force_post': 'true',
'xhr_uploader': 'true',
'urlencoded_filename': self.urlencode_normalized(os.path.basename(path))
}
try:
self.perform_request(url=url, type='post', data=data, files=files, with_progress=callback_dict)
except PydioSdkDefaultException as e:
if e.message == '507':
usage, total = self.quota_usage()
raise PydioSdkQuotaException(path, local_stat['size'], usage, total)
if e.message == '412':
raise PydioSdkPermissionException('Cannot upload '+os.path.basename(path)+' in directory '+os.path.dirname(path))
else:
raise e
except RequestException as ce:
raise PydioSdkException("upload", str(path), 'RequestException: ' + str(ce.message))
return True
def stat_and_download(self, path, local, callback_dict=None):
"""
Download the content of a server file to a local file.
:param path: node path on the server
:param local: local path on filesystem
:param callback_dict: a dict() than can be updated by with progress data
:return: Server response
"""
orig = self.stat(path)
if not orig:
raise PydioSdkException('download', path, _('Original file was not found on server'), 1404)
url = self.url + '/download' + self.urlencode_normalized((self.remote_folder + path))
local_tmp = local + '.pydio_dl'
headers = None
write_mode = 'wb'
dl = 0
if not os.path.exists(os.path.dirname(local)):
os.makedirs(os.path.dirname(local))
elif os.path.exists(local_tmp):
# A .pydio_dl already exists, maybe it's a chunk of the original?
# Try to get an md5 of the corresponding chunk
current_size = os.path.getsize(local_tmp)
chunk_local_hash = hashfile(open(local_tmp, 'rb'), hashlib.md5())
chunk_remote_stat = self.stat(path, True, partial_hash=[0, current_size])
if chunk_remote_stat and chunk_local_hash == chunk_remote_stat['hash']:
headers = {'range':'bytes=%i-%i' % (current_size, chunk_remote_stat['size'])}
write_mode = 'a+'
dl = current_size
if callback_dict:
callback_dict['bytes_sent'] = float(current_size)
callback_dict['total_bytes_sent'] = float(current_size)
callback_dict['total_size'] = float(chunk_remote_stat['size'])
callback_dict['transfer_rate'] = 0
dispatcher.send(signal=TRANSFER_CALLBACK_SIGNAL, send=self, change=callback_dict)
else:
os.unlink(local_tmp)
try:
with open(local_tmp, write_mode) as fd:
start = time.clock()
r = self.perform_request(url=url, stream=True, headers=headers)
total_length = r.headers.get('content-length')
if total_length is None: # no content length header
fd.write(r.content)
else:
previous_done = 0