-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathclient.py
1230 lines (1040 loc) · 49.5 KB
/
client.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
import logging
import math
import os
import json
import shutil
import zlib
import base64
import urllib.parse
import urllib.request
import urllib.error
import platform
from datetime import datetime, timezone
import dateutil.parser
import ssl
from enum import Enum, auto
import re
import typing
import warnings
from .common import ClientError, LoginError, InvalidProject, ErrorCode
from .merginproject import MerginProject
from .client_pull import (
download_file_finalize,
download_project_async,
download_file_async,
download_files_async,
download_files_finalize,
download_diffs_async,
download_project_finalize,
download_project_wait,
download_diffs_finalize,
)
from .client_pull import pull_project_async, pull_project_wait, pull_project_finalize
from .client_push import push_project_async, push_project_wait, push_project_finalize
from .utils import DateTimeEncoder, get_versions_with_file_changes, int_version, is_version_acceptable
from .version import __version__
this_dir = os.path.dirname(os.path.realpath(__file__))
class TokenError(Exception):
pass
class ServerType(Enum):
OLD = auto() # Server is old and does not support workspaces
CE = auto() # Server is Community Edition
EE = auto() # Server is Enterprise Edition
SAAS = auto() # Server is SaaS
def decode_token_data(token):
token_prefix = "Bearer ."
if not token.startswith(token_prefix):
raise TokenError(f"Token doesn't start with 'Bearer .': {token}")
try:
data = token[len(token_prefix) :].split(".")[0]
# add proper base64 padding"
data += "=" * (-len(data) % 4)
decoded = zlib.decompress(base64.urlsafe_b64decode(data))
return json.loads(decoded)
except (IndexError, TypeError, ValueError, zlib.error):
raise TokenError(f"Invalid token data: {token}")
class MerginClient:
"""
Client for Mergin Maps service.
:param url: String, Mergin Maps service URL.
:param auth_token: String, Mergin Maps authorization token.
:param login: String, login for Mergin Maps service.
:param password: String, password for Mergin Maps service.
:param plugin_version: String, info about plugin and QGIS version.
:param proxy_config: Dictionary, proxy settings to use when connecting to Mergin Maps service. At least url and port
of the server should be provided. Expected keys: "url", "port", "user", "password".
Currently, only HTTP proxies are supported.
"""
def __init__(self, url=None, auth_token=None, login=None, password=None, plugin_version=None, proxy_config=None):
self.url = url if url is not None else MerginClient.default_url()
self._auth_params = None
self._auth_session = None
self._user_info = None
self._server_type = None
self._server_version = None
self.client_version = "Python-client/" + __version__
if plugin_version is not None: # this could be e.g. "Plugin/2020.1 QGIS/3.14"
self.client_version += " " + plugin_version
self.setup_logging()
if auth_token:
try:
token_data = decode_token_data(auth_token)
self._auth_session = {"token": auth_token, "expire": dateutil.parser.parse(token_data["expire"])}
self._user_info = {"username": token_data["username"]}
except TokenError as e:
self.log.error(e)
raise ClientError("Auth token error: " + str(e))
handlers = []
# Create handlers for proxy, if needed
if proxy_config is not None:
proxy_url_parsed = urllib.parse.urlparse(proxy_config["url"])
proxy_url = proxy_url_parsed.path
if proxy_config["user"] and proxy_config["password"]:
handlers.append(
urllib.request.ProxyHandler(
{
"https": f"{proxy_config['user']}:{proxy_config['password']}@{proxy_url}:{proxy_config['port']}"
}
)
)
handlers.append(urllib.request.HTTPBasicAuthHandler())
else:
handlers.append(urllib.request.ProxyHandler({"https": f"{proxy_url}:{proxy_config['port']}"}))
# fix for wrong macos installation of python certificates,
# see https://github.com/lutraconsulting/qgis-mergin-plugin/issues/70
# remove when https://github.com/qgis/QGIS-Mac-Packager/issues/32
# is fixed.
default_capath = ssl.get_default_verify_paths().openssl_capath
if os.path.exists(default_capath):
self.opener = urllib.request.build_opener(*handlers, urllib.request.HTTPSHandler())
else:
cafile = os.path.join(this_dir, "cert.pem")
if not os.path.exists(cafile):
raise Exception("missing " + cafile)
ctx = ssl.SSLContext()
ctx.load_verify_locations(cafile)
https_handler = urllib.request.HTTPSHandler(context=ctx)
self.opener = urllib.request.build_opener(*handlers, https_handler)
urllib.request.install_opener(self.opener)
if login and not password:
raise ClientError("Unable to log in: no password provided for '{}'".format(login))
if password and not login:
raise ClientError("Unable to log in: password provided but no username/email")
if login and password:
self._auth_params = {"login": login, "password": password}
if not self._auth_session:
self.login(login, password)
def setup_logging(self):
"""Setup Mergin Maps client logging."""
client_log_file = os.environ.get("MERGIN_CLIENT_LOG", None)
self.log = logging.getLogger("mergin.client")
self.log.setLevel(logging.DEBUG) # log everything (it would otherwise log just warnings+errors)
if not self.log.handlers:
if client_log_file:
log_handler = logging.FileHandler(client_log_file)
log_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s"))
self.log.addHandler(log_handler)
else:
# no Mergin Maps log path in the environment - create a null handler that does nothing
null_logger = logging.NullHandler()
self.log.addHandler(null_logger)
@staticmethod
def default_url():
"""Returns URL of the public instance of Mergin Maps"""
return "https://app.merginmaps.com"
def user_agent_info(self):
"""Returns string as it is sent as User-Agent http header to the server"""
system_version = "Unknown"
if platform.system() == "Linux":
try:
from pip._vendor import distro
system_version = distro.id().capitalize()
except ModuleNotFoundError: # pip may not be installed...
system_version = "Linux"
elif platform.system() == "Windows":
system_version = platform.win32_ver()[0]
elif platform.system() in ["Mac", "Darwin"]:
system_version = platform.mac_ver()[0]
return f"{self.client_version} ({platform.system()}/{system_version})"
def _check_token(f):
"""Wrapper for creating/renewing authorization token."""
def wrapper(self, *args):
if self._auth_params:
if self._auth_session:
# Refresh auth token if it expired or will expire very soon
delta = self._auth_session["expire"] - datetime.now(timezone.utc)
if delta.total_seconds() < 5:
self.log.info("Token has expired - refreshing...")
self.login(self._auth_params["login"], self._auth_params["password"])
else:
# Create a new authorization token
self.log.info(f"No token - login user: {self._auth_params['login']}")
self.login(self._auth_params["login"], self._auth_params["password"])
return f(self, *args)
return wrapper
@_check_token
def _do_request(self, request):
"""General server request method."""
if self._auth_session:
request.add_header("Authorization", self._auth_session["token"])
request.add_header("User-Agent", self.user_agent_info())
try:
return self.opener.open(request)
except urllib.error.HTTPError as e:
server_response = json.load(e)
# We first to try to get the value from the response otherwise we set a default value
err_detail = server_response.get("detail", e.read().decode("utf-8"))
server_code = server_response.get("code", None)
raise ClientError(
detail=err_detail,
url=request.get_full_url(),
server_code=server_code,
server_response=server_response,
http_error=e.code,
http_method=request.get_method(),
)
except urllib.error.URLError as e:
# e.g. when DNS resolution fails (no internet connection?)
raise ClientError("Error requesting " + request.full_url + ": " + str(e))
def get(self, path, data=None, headers={}):
url = urllib.parse.urljoin(self.url, urllib.parse.quote(path))
if data:
url += "?" + urllib.parse.urlencode(data)
request = urllib.request.Request(url, headers=headers)
return self._do_request(request)
def post(self, path, data=None, headers={}):
url = urllib.parse.urljoin(self.url, urllib.parse.quote(path))
if headers.get("Content-Type", None) == "application/json":
data = json.dumps(data, cls=DateTimeEncoder).encode("utf-8")
request = urllib.request.Request(url, data, headers, method="POST")
return self._do_request(request)
def patch(self, path, data=None, headers={}):
url = urllib.parse.urljoin(self.url, urllib.parse.quote(path))
if headers.get("Content-Type", None) == "application/json":
data = json.dumps(data, cls=DateTimeEncoder).encode("utf-8")
request = urllib.request.Request(url, data, headers, method="PATCH")
return self._do_request(request)
def login(self, login, password):
"""
Authenticate login credentials and store session token
:param login: User's username of email address
:type login: String
:param password: User's password
:type password: String
"""
params = {"login": login, "password": password}
self._auth_session = None
self.log.info(f"Going to log in user {login}")
try:
self._auth_params = params
url = urllib.parse.urljoin(self.url, urllib.parse.quote("/v1/auth/login"))
data = json.dumps(self._auth_params, cls=DateTimeEncoder).encode("utf-8")
request = urllib.request.Request(url, data, {"Content-Type": "application/json"}, method="POST")
request.add_header("User-Agent", self.user_agent_info())
resp = self.opener.open(request)
data = json.load(resp)
session = data["session"]
except urllib.error.HTTPError as e:
if e.headers.get("Content-Type", "") == "application/problem+json":
info = json.load(e)
self.log.info(f"Login problem: {info.get('detail')}")
raise LoginError(info.get("detail"))
self.log.info(f"Login problem: {e.read().decode('utf-8')}")
raise LoginError(e.read().decode("utf-8"))
except urllib.error.URLError as e:
# e.g. when DNS resolution fails (no internet connection?)
raise ClientError("failure reason: " + str(e.reason))
self._auth_session = {
"token": "Bearer %s" % session["token"],
"expire": dateutil.parser.parse(session["expire"]),
}
self._user_info = {"username": data["username"]}
self.log.info(f"User {data['username']} successfully logged in.")
return session
def username(self):
"""Returns user name used in this session or None if not authenticated"""
if not self._user_info:
return None # not authenticated
return self._user_info["username"]
def workspace_service(self, workspace_id):
"""
This Requests information about a workspace service from /workspace/{id}/service endpoint,
if such exists in self.url server.
Returns response from server as JSON dict or None if endpoint is not found
"""
resp = self.get(f"/v1/workspace/{workspace_id}/service")
return json.load(resp)
def workspace_usage(self, workspace_id):
"""
This Requests information about a workspace usage from /workspace/{id}/usage endpoint,
if such exists in self.url server.
Returns response from server as JSON dict or None if endpoint is not found
"""
resp = self.get(f"/v1/workspace/{workspace_id}/usage")
return json.load(resp)
def server_type(self):
"""
Returns the deployment type of the server
The value is cached for self's lifetime
:returns: ServerType of server deployment
:rtype: ServerType
"""
if not self._server_type:
try:
resp = self.get("/config")
config = json.load(resp)
if config["server_type"] == "ce":
self._server_type = ServerType.CE
elif config["server_type"] == "ee":
self._server_type = ServerType.EE
elif config["server_type"] == "saas":
self._server_type = ServerType.SAAS
except (ClientError, KeyError):
self._server_type = ServerType.OLD
return self._server_type
def server_version(self):
"""
Returns version of the server
:returns: Version string, e.g. "2023.5.0". For old servers (pre-2023) this may be empty string.
:rtype: str
"""
if self._server_version is None:
try:
resp = self.get("/config")
config = json.load(resp)
self._server_version = config["version"]
except (ClientError, KeyError):
self._server_version = ""
return self._server_version
def workspaces_list(self):
"""
Find all available workspaces
:rtype: List[Dict]
"""
resp = self.get("/v1/workspaces")
workspaces = json.load(resp)
return workspaces
def create_workspace(self, workspace_name):
"""
Create new workspace for currently active user.
:param workspace_name: Workspace name to create
:type workspace_name: String
"""
if not self._user_info:
raise Exception("Authentication required")
params = {"name": workspace_name}
try:
self.post("/v1/workspace", params, {"Content-Type": "application/json"})
except ClientError as e:
e.extra = f"Workspace name: {workspace_name}"
raise e
def create_project(self, project_name, is_public=False, namespace=None):
"""
Create new project repository in user namespace on Mergin Maps server.
Optionally initialized from given local directory.
:param project_name: Project's full name (<namespace>/<name>)
:type project_name: String
:param is_public: Flag for public/private project, defaults to False
:type is_public: Boolean
:param namespace: Deprecated. project_name should be full project name. Optional namespace for a new project. If empty username is used.
:type namespace: String
"""
if not self._user_info:
raise Exception("Authentication required")
if namespace and "/" not in project_name:
warnings.warn(
"The usage of `namespace` parameter in `create_project()` is deprecated."
"Specify `project_name` as full name (<namespace>/<name>) instead.",
category=DeprecationWarning,
)
if "/" in project_name:
if namespace:
warnings.warn(
"Parameter `namespace` specified with full project name (<namespace>/<name>)."
"The parameter will be ignored."
)
namespace, project_name = project_name.split("/")
elif namespace is None:
warnings.warn(
"The use of only project name in `create_project()` is deprecated."
"The `project_name` should be full name (<namespace>/<name>).",
category=DeprecationWarning,
)
params = {"name": project_name, "public": is_public}
if namespace is None:
namespace = self.username()
try:
self.post(f"/v1/project/{namespace}", params, {"Content-Type": "application/json"})
except ClientError as e:
e.extra = f"Namespace: {namespace}, project name: {project_name}"
raise e
def create_project_and_push(self, project_name, directory, is_public=False, namespace=None):
"""
Convenience method to create project and push the initial version right after that.
:param project_name: Project's full name (<namespace>/<name>)
:type project_name: String
:param namespace: Deprecated. project_name should be full project name. Optional namespace for a new project. If empty username is used.
:type namespace: String
"""
if os.path.exists(os.path.join(directory, ".mergin")):
raise ClientError("Directory is already assigned to a Mergin Maps project (contains .mergin sub-dir)")
if namespace and "/" not in project_name:
warnings.warn(
"The usage of `namespace` parameter in `create_project_and_push()` is deprecated."
"Specify `project_name` as full name (<namespace>/<name>) instead.",
category=DeprecationWarning,
)
project_name = f"{namespace}/{project_name}"
if "/" in project_name:
if namespace:
warnings.warn(
"Parameter `namespace` specified with full project name (<namespace>/<name>)."
"The parameter will be ignored."
)
elif namespace is None:
warnings.warn(
"The use of only project name in `create_project()` is deprecated."
"The `project_name` should be full name (<namespace>/<name>).",
category=DeprecationWarning,
)
namespace = self.username()
project_name = f"{namespace}/{project_name}"
self.create_project(project_name, is_public)
if directory:
project_info = self.project_info(project_name)
MerginProject.write_metadata(directory, project_info)
mp = MerginProject(directory)
if mp.inspect_files():
self.push_project(directory)
def paginated_projects_list(
self,
page=1,
per_page=50,
tags=None,
user=None,
flag=None,
name=None,
only_namespace=None,
namespace=None,
order_params=None,
only_public=None,
):
"""
Find all available Mergin Maps projects.
:param tags: Filter projects by tags ('valid_qgis', 'mappin_use', input_use')
:type tags: List
:param user: Username for 'flag' filter. If not provided, it means user executing request.
:type user: String
:param flag: Predefined filter flag ('created', 'shared')
:type flag: String
:param name: Filter projects with name like name
:type name: String
:param only_namespace: Filter projects with namespace exactly equal to namespace
:type namespace: String
:param namespace: Filter projects with namespace like namespace
:type namespace: String
:param page: Page number for paginated projects list
:type page: Integer
:param per_page: Number of projects fetched per page, max 100 (restriction set by server)
:type per_page: Integer
:param order_params: optional attributes for sorting the list. It should be a comma separated attribute names
with _asc or _desc appended for sorting direction. For example: "namespace_asc,disk_usage_desc".
Available attrs: namespace, name, created, updated, disk_usage, creator
:type order_params: String
:param only_public: Only fetch public projects
:type only_public: Bool
:rtype: List[Dict]
"""
params = {}
if tags:
params["tags"] = ",".join(tags)
if user:
params["user"] = user
if flag:
params["flag"] = flag
if name:
params["name"] = name
if only_namespace:
params["only_namespace"] = only_namespace
elif namespace:
params["namespace"] = namespace
if only_public:
params["only_public"] = only_public
params["page"] = page
params["per_page"] = per_page
if order_params is not None:
params["order_params"] = order_params
resp = self.get("/v1/project/paginated", params)
projects = json.load(resp)
return projects
def projects_list(
self,
tags=None,
user=None,
flag=None,
name=None,
only_namespace=None,
namespace=None,
order_params=None,
only_public=None,
):
"""
Find all available Mergin Maps projects.
Calls paginated_projects_list for all pages. Can take significant time to fetch all pages.
:param tags: Filter projects by tags ('valid_qgis', 'mappin_use', input_use')
:type tags: List
:param user: Username for 'flag' filter. If not provided, it means user executing request.
:type user: String
:param flag: Predefined filter flag ('created', 'shared')
:type flag: String
:param name: Filter projects with name like name
:type name: String
:param only_namespace: Filter projects with namespace exactly equal to namespace
:type namespace: String
:param namespace: Filter projects with namespace like namespace
:type namespace: String
:param order_params: optional attributes for sorting the list. It should be a comma separated attribute names
with _asc or _desc appended for sorting direction. For example: "namespace_asc,disk_usage_desc".
Available attrs: namespace, name, created, updated, disk_usage, creator
:type order_params: String
:param only_public: Only fetch public projects
:type only_public: Bool
:rtype: List[Dict]
"""
projects = []
page_i = 1
fetched_projects = 0
while True:
resp = self.paginated_projects_list(
page=page_i,
per_page=50,
tags=tags,
user=user,
flag=flag,
name=name,
only_namespace=only_namespace,
namespace=namespace,
order_params=order_params,
only_public=only_public,
)
fetched_projects += len(resp["projects"])
count = resp["count"]
projects += resp["projects"]
if fetched_projects < count:
page_i += 1
else:
break
return projects
def project_info(self, project_path_or_id, since=None, version=None):
"""
Fetch info about project.
:param project_path_or_id: Project's full name (<namespace>/<name>) or id
:type project_path_or_id: String
:param since: Version to track history of geodiff files from
:type since: String
:param version: Project version to get details for (particularly list of files)
:type version: String
:rtype: Dict
"""
params = {"since": since} if since else {}
# since and version are mutually exclusive
if version:
params = {"version": version}
if re.match("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", project_path_or_id):
resp = self.get("/v1/project/by_uuid/{}".format(project_path_or_id), params)
else:
resp = self.get("/v1/project/{}".format(project_path_or_id), params)
return json.load(resp)
def paginated_project_versions(self, project_path, page, per_page=100, descending=False):
"""
Get records of project's versions (history) using calculated pagination.
wrapper around the /v1/project/versions/paginated/{} API end point
:param project_path: Project's full name (<namespace>/<name>)
:type project_path: String | Int
:param page: page number
:type page: Int
:param per_page: number of results per page default 100
:type per_page: Int
:param descending: order of sorting
:type descending: Bool
:rtype: List[Dict], Int
"""
params = {"page": page, "per_page": per_page, "descending": descending}
resp = self.get("/v1/project/versions/paginated/{}".format(project_path), params)
resp_json = json.load(resp)
return resp_json["versions"], resp_json["count"]
def project_versions_count(self, project_path):
"""
return the total count of versions
To note we fetch only one page and one item as we only need the "count" response
:param project_path_or_id: Project's full name (<namespace>/<name>) or id
:type project_path_or_id: String
:rtype: Int
"""
params = {"page": 1, "per_page": 1, "descending": False}
resp = self.get("/v1/project/versions/paginated/{}".format(project_path), params)
resp_json = json.load(resp)
return resp_json["count"]
def project_versions(self, project_path, since=1, to=None):
"""
Get records of project's versions (history) in ascending order.
If neither 'since' nor 'to' is specified it will return all versions.
:param project_path: Project's full name (<namespace>/<name>)
:type project_path: String
:param since: Version to track project history from
:type since: String | Int
:param to: Version to track project history to
:type to: String | Int
:rtype: List[Dict]
"""
versions = []
per_page = 100 # server limit
if type(since) == str:
num_since = int_version(since)
else:
# keep the since parameter as is
num_since = since
if type(to) == str:
num_to = int_version(to)
else:
# keep the to parameter as is
num_to = to
start_page = math.ceil(num_since / per_page)
if not num_to:
# let's get first page and count
versions, num_to = self.paginated_project_versions(project_path, start_page, per_page)
latest_version = int_version(versions[-1]["name"])
if latest_version < num_to:
versions += self.project_versions(project_path, f"v{latest_version+1}", f"v{num_to}")
else:
end_page = math.ceil(num_to / per_page)
for page in range(start_page, end_page + 1):
page_versions, _ = self.paginated_project_versions(project_path, page, per_page)
versions += page_versions
# filter out versions not within range
filtered_versions = list(filter(lambda v: (num_since <= int_version(v["name"]) <= num_to), versions))
return filtered_versions
def download_project(self, project_path, directory, version=None):
"""
Download project into given directory. If version is not specified, latest version is downloaded
:param project_path: Project's full name (<namespace>/<name>)
:type project_path: String
:param version: Project version to download, e.g. v42
:type version: String
:param directory: Target directory
:type directory: String
"""
job = download_project_async(self, project_path, directory, version)
download_project_wait(job)
download_project_finalize(job)
def user_info(self):
server_type = self.server_type()
if server_type == ServerType.OLD:
resp = self.get("/v1/user/" + self.username())
else:
resp = self.get("/v1/user/profile")
return json.load(resp)
def set_project_access(self, project_path, access):
"""
Updates access for given project.
:param project_path: project full name (<namespace>/<name>)
:param access: dict <readersnames, editorsnames, writersnames, ownersnames> -> list of str username we want to give access to (editorsnames are only supported on servers at version 2024.4.0 or later)
"""
if "editorsnames" in access and not self.has_editor_support():
raise NotImplementedError("Editors are only supported on servers at version 2024.4.0 or later")
if not self._user_info:
raise Exception("Authentication required")
params = {"access": access}
path = "/v1/project/%s" % project_path
url = urllib.parse.urljoin(self.url, urllib.parse.quote(path))
json_headers = {"Content-Type": "application/json"}
try:
request = urllib.request.Request(url, data=json.dumps(params).encode(), headers=json_headers, method="PUT")
self._do_request(request)
except ClientError as e:
e.extra = f"Project path: {project_path}"
raise e
def add_user_permissions_to_project(self, project_path, usernames, permission_level):
"""
Add specified permissions to specified users to project
:param project_path: project full name (<namespace>/<name>)
:param usernames: list of usernames to be granted specified permission level
:param permission_level: string (reader, editor, writer, owner)
Editor permission_level is only supported on servers at version 2024.4.0 or later.
"""
if permission_level not in ["owner", "reader", "writer", "editor"] or (
permission_level == "editor" and not self.has_editor_support()
):
raise ClientError("Unsupported permission level")
project_info = self.project_info(project_path)
access = project_info.get("access")
for name in usernames:
if permission_level == "owner":
access.get("ownersnames").append(name)
if permission_level in ("writer", "owner"):
access.get("writersnames").append(name)
if permission_level in ("writer", "owner", "editor") and "editorsnames" in access:
access.get("editorsnames").append(name)
if permission_level in ("writer", "owner", "editor", "reader"):
access.get("readersnames").append(name)
self.set_project_access(project_path, access)
def remove_user_permissions_from_project(self, project_path, usernames):
"""
Removes specified users from project
:param project_path: project full name (<namespace>/<name>)
:param usernames: list of usernames to be granted specified permission level
"""
project_info = self.project_info(project_path)
access = project_info.get("access")
for name in usernames:
if name in access.get("ownersnames", []):
access.get("ownersnames").remove(name)
if name in access.get("writersnames", []):
access.get("writersnames").remove(name)
if name in access.get("editorsnames", []):
access.get("editorsnames").remove(name)
if name in access.get("readersnames", []):
access.get("readersnames").remove(name)
self.set_project_access(project_path, access)
def project_user_permissions(self, project_path):
"""
Returns permissions for project
:param project_path: project full name (<namespace>/<name>)
:return dict("owners": list(usernames),
"writers": list(usernames),
"editors": list(usernames) - only on servers at version 2024.4.0 or later,
"readers": list(usernames))
"""
project_info = self.project_info(project_path)
access = project_info.get("access")
result = {}
if "editorsnames" in access:
result["editors"] = access.get("editorsnames", [])
result["owners"] = access.get("ownersnames", [])
result["writers"] = access.get("writersnames", [])
result["readers"] = access.get("readersnames", [])
return result
def push_project(self, directory):
"""
Upload local changes to the repository.
:param directory: Project's directory
:type directory: String
"""
job = push_project_async(self, directory)
if job is None:
return # there is nothing to push (or we only deleted some files)
push_project_wait(job)
push_project_finalize(job)
def pull_project(self, directory):
"""
Fetch and apply changes from repository.
:param directory: Project's directory
:type directory: String
"""
job = pull_project_async(self, directory)
if job is None:
return # project is up to date
pull_project_wait(job)
return pull_project_finalize(job)
def clone_project(self, source_project_path, cloned_project_name, cloned_project_namespace=None):
"""
Clone project on server.
:param source_project_path: Project's full name (<namespace>/<name>)
:type source_project_path: String
:param cloned_project_name: Cloned project's full name (<namespace>/<name>)
:type cloned_project_name: String
:param cloned_project_namespace: Deprecated. cloned_project_name should be full project name. Cloned project's namespace, username is used if not defined
:type cloned_project_namespace: String
"""
if cloned_project_namespace and "/" not in cloned_project_name:
warnings.warn(
"The usage of `cloned_project_namespace` parameter in `clone_project()` is deprecated."
"Specify `cloned_project_name` as full name (<namespace>/<name>) instead.",
category=DeprecationWarning,
)
if "/" in cloned_project_name:
if cloned_project_namespace:
warnings.warn(
"Parameter `cloned_project_namespace` specified with full cloned project name (<namespace>/<name>)."
"The parameter will be ignored."
)
cloned_project_namespace, cloned_project_name = cloned_project_name.split("/")
elif cloned_project_namespace is None:
warnings.warn(
"The use of only project name as `cloned_project_name` in `clone_project()` is deprecated."
"The `cloned_project_name` should be full name (<namespace>/<name>).",
category=DeprecationWarning,
)
path = f"/v1/project/clone/{source_project_path}"
url = urllib.parse.urljoin(self.url, urllib.parse.quote(path))
json_headers = {"Content-Type": "application/json", "Accept": "application/json"}
data = {
"namespace": cloned_project_namespace if cloned_project_namespace else self.username(),
"project": cloned_project_name,
}
request = urllib.request.Request(url, data=json.dumps(data).encode(), headers=json_headers, method="POST")
self._do_request(request)
def delete_project_now(self, project_path):
"""
Delete project repository on server immediately.
This should be typically in development, e.g. auto tests, where we
do not want scheduled project deletes as done by delete_project().
:param project_path: Project's full name (<namespace>/<name>)
:type project_path: String
"""
# TODO: this version check should be replaced by checking against the list
# of endpoints that server publishes in /config (once implemented)
if not is_version_acceptable(self.server_version(), "2023.5"):
raise NotImplementedError("This needs server at version 2023.5 or later")
project_info = self.project_info(project_path)
project_id = project_info["id"]
path = "/v2/projects/" + project_id
url = urllib.parse.urljoin(self.url, urllib.parse.quote(path))
request = urllib.request.Request(url, method="DELETE")
self._do_request(request)
def delete_project(self, project_path):
"""
Delete project repository on server. Newer servers since 2023
will schedule deletion of the project, but not fully remove it immediately.
This is the preferred way when the removal is user initiated, so that
it is not possible to replace the project with another one with the same
name, which would confuse clients that do not use project IDs yet.
There is also delete_project_now() on newer servers which deletes projects
immediately.
:param project_path: Project's full name (<namespace>/<name>)
:type project_path: String
"""
# TODO: newer server version (since 2023.5.0) have a new endpoint
# (POST /v2/projects/<id>/scheduleDelete) that does the same thing,
# but using project ID instead of the name. At some point we may
# want to migrate to it.
path = "/v1/project/%s" % project_path
url = urllib.parse.urljoin(self.url, urllib.parse.quote(path))
request = urllib.request.Request(url, method="DELETE")
self._do_request(request)
def project_status(self, directory):
"""
Get project status, e.g. server and local changes.
:param directory: Project's directory
:type directory: String
:returns: changes metadata for files modified on server, and for those modified locally
:rtype: dict, dict
"""
mp = MerginProject(directory)
server_info = self.project_info(mp.project_full_name(), since=mp.version())
pull_changes = mp.get_pull_changes(server_info["files"])
push_changes = mp.get_push_changes()
push_changes_summary = mp.get_list_of_push_changes(push_changes)
return pull_changes, push_changes, push_changes_summary
def project_version_info(self, project_id, version):
"""Returns JSON with detailed information about a single project version"""
resp = self.get(f"/v1/project/version/{project_id}/{version}")
return json.load(resp)
def project_file_history_info(self, project_path, file_path):
"""Returns JSON with full history of a single file within a project"""
params = {"path": file_path}
resp = self.get("/v1/resource/history/{}".format(project_path), params)
return json.load(resp)
def project_file_changeset_info(self, project_path, file_path, version):
"""Returns JSON with changeset details of a particular version of a file within a project"""
params = {"path": file_path}
resp = self.get("/v1/resource/changesets/{}/{}".format(project_path, version), params)
return json.load(resp)
def get_projects_by_names(self, projects):
"""Returns JSON with projects' info for list of required projects.
The schema of the returned information is the same as the response from projects_list().
This is useful when we have a couple of Mergin Maps projects available locally and we want to
find out their status at once (e.g. whether there is a new version on the server).
:param projects: list of projects in the form 'namespace/project_name'