-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcaltopo_python.py
More file actions
3710 lines (3476 loc) · 189 KB
/
caltopo_python.py
File metadata and controls
3710 lines (3476 loc) · 189 KB
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
# #############################################################################
#
# caltopo_python.py - python interfaces to the caltopo API
#
# developed for Nevada County Sheriff's Search and Rescue
# Copyright (c) 2024 Tom Grundy
#
# Caltopo currently does not have a publicly available API;
# this code calls the non-publicized API that could change at any time.
#
# This module is intended to provide a simple, API-version-agnostic caltopo
# interface to other applications.
#
# This python code is in no way supported or maintained by caltopo LLC
# or the authors of caltopo.com.
#
# Earlier versions are still available as 'sartopo_python'.
#
# www.github.com/ncssar/caltopo_python
#
# Contact the author at nccaves@yahoo.com
# Attribution, feedback, bug reports and feature requests are appreciated
#
############################################################
#
# EXAMPLES:
#
# from caltopo_python import CaltopoSession
# import time
#
# cts=CaltopoSession('localhost:8080','<offlineMapID>')
# fid=cts.addFolder('MyFolder')
# cts.addMarker(39,-120,'stuff')
# cts.addMarker(39.01,-120.01,'myStuff',folderId=fid)
# r=cts.getFeatures('Marker')
# print('r:'+str(r))
# print('moving the marker after a pause:'+r[0]['id'])
# time.sleep(5)
# cts.addMarker(39.02,-120.02,r[0]['properties']['title'],existingId=r[0]['id'])
#
# cts2=CaltopoSession(
# 'caltopo.com',
# '<onlineMapID>',
# configpath='../../cts.ini',
# account='<accountName>')
# fid2=cts2.addFolder('MyOnlineFolder')
# cts2.addMarker(39,-120,'onlineStuff')
# cts2.addMarker(39.01,-119.99,'onlineStuff2',folderId=fid2)
# r2=cts2.getFeatures('Marker')
# print('return value from getFeatures('Marker'):')
# print(json.dumps(r2,indent=3))
# time.sleep(15)
# print('moving online after a pause:'+r2[0]['id'])
# cts2.addMarker(39.02,-119.98,r2[0]['properties']['title'],existingId=r2[0]['id'])
#
#
# Threading
#
# When self.sync is True, we want to call _doSync, then wait n seconds after
# the response, then call _doSync again, etc. This is not strictly the same
# as calling _doSync every n seconds, since it may take several seconds for
# the response to be completed, for large data or slow connection or both.
#
# We could use the timer object (a subclass of Threading), but that
# would cause a new thread to be spawned for each iteration, which might
# cause python resource or memory issues after a long time. So, instead,
# we use one thread for syncing, which does a blocking sleep of n
# seconds after each completed response. This sync thread is separate
# from the main thread, so that its blocking sleeps (or slow responses) do
# not block the rest of the program.
#
# The sync thread is created by calling self._start(). A call to self._stop()
# simply sets self.sync to False, which causes the sync thread to end itself
# after the next request/response.
#
# Since self._doSync is called repeatedly if self.sync is True, the sync
# thread would stay alive forever, even after the calling program ends; so,
# at the end of each sync iteration, self._doSync checks to see if the main
# thread is still alive, and terminates the sync thread if the main thread
# is no longer alive.
#
# To avoid the recursion limit, _doSync is called iteratively rather than
# recursivley, in _syncLoop which is only meant to be called from start().
#
# To prevent main-thread requests from being sent while a sync request is
# in process, _doSync sets self.syncing just before sending the 'since'
# request, and leaves it set until the sync response is processed.
# TO DO: If a main-thread request wants to be sent while self.syncing is
# set, the request is queued, and is sent after the next sync response is
# processed.
#
# NOTE : is this block-and-queue necessary? Since the http requests
# and responses should be able to synchronize themselves, maybe it's not
# needed here?
#
import hmac
import base64
import requests
import json
import configparser
import os
import time
import logging
import sys
import threading
import copy
import asyncio
from concurrent.futures import ThreadPoolExecutor
import functools
# import objgraph
# import psutil
# process=psutil.Process(os.getpid())
# syncing=False
# shapely.geometry imports will generate a logging message if numpy is not installed;
# numpy is not actually required
from shapely.geometry import LineString,Point,Polygon,MultiLineString,MultiPolygon,GeometryCollection
from shapely.ops import split,unary_union
# silent exception class to be raised during __init__ and handlded by the caller,
# since __init__ should always return None: https://stackoverflow.com/questions/20059766
class CTSException(BaseException):
pass
class CaltopoSession():
def __init__(self,
domainAndPort: str='localhost:8080',
mapID=None,
configpath=None,
account=None,
id=None, # 12-character credential ID
key=None, # credential key
accountId=None, # 6-character accountId
accountIdInternet=None, # in case CTD requires a different accountId than caltopo.com
sync=True,
syncInterval=5,
syncTimeout=10,
syncDumpFile=None,
cacheDumpFile=None,
propertyUpdateCallback=None,
geometryUpdateCallback=None,
newFeatureCallback=None,
deletedFeatureCallback=None,
syncCallback=None,
useFiddlerProxy=False,
caseSensitiveComparisons=False, # case-insensitive comparisons by default, see _caseMatch()
validatePoints='modify'):
"""The core session object.
:param domainAndPort: Domain-and-port portion of the URL; defaults to 'localhost:8080'; common values are 'caltopo.com' for the web interface, and 'localhost:8080' (or different hostname or port as needed) for CalTopo Desktop
:type domainAndPort: str, optional
:param mapID: 3-to-7-character map ID, or [NEW] followed by new map specification (see .openMap documentation); omit this argument during initialization to create a 'mapless' session; defaults to None
:type mapID: str, optional
:param configpath: Configuration file path (full file name); defaults to None
:type configpath: str, optional
:param account: Account name; used to reference a section of the config file; defaults to None
:type account: str, optional
:param id: 12-character credential ID; specify here to override value from config file; defaults to None
:type id: _type_, optional
:param key: Credential key; specify here to override value from config file; defaults to None
:type key: str, optional
:param accountId: 6-character account ID; specify here to override value from config file; defaults to None
:type accountId: str, optional
:param accountIdInternet: 6-character internet-specific account ID; specify here to override value from config file; defaults to None
:type accountIdInternet: str, optional
:param sync: If True, the session will use multi-threaded background sync to keep the local cache in sync with the specified hosted map; defaults to True
:type sync: bool, optional
:param syncInterval: Sync interval in seconds; defaults to 5
:type syncInterval: int, optional
:param syncTimeout: Sync timeout in seconds; defaults to 10
:type syncTimeout: int, optional
:param syncDumpFile: Base filename (will be appended by timestamp) to dump the results of each sync call; defaults to None
:type syncDumpFile: str, optional
:param cacheDumpFile: Base filename (will be appended by timestamp) to dump the local cache contents on each sync call; defaults to None
:type cacheDumpFile: str, optional
:param propertyUpdateCallback: Function to call when any feature's property has changed during sync; the function will be called with the affected feature object as the only argument; defaults to None
:type propertyUpdateCallback: function, optional
:param geometryUpdateCallback: Function to call when any feature's geometry has changed during sync; the function will be called with the affected feature object as the only argument; defaults to None
:type geometryUpdateCallback: function, optional
:param newFeatureCallback: Function to call when a new feature was added to the local cache during sync; the function will be called with the new feature object as the only argument; defaults to None
:type newFeatureCallback: function, optional
:param deletedFeatureCallback: Function to call when a feature was deleted from the local cache during sync; the function will be called with the deleted feature object as the only argument; defaults to None
:type deletedFeatureCallback: function, optional
:param syncCallback: Function to call on each successful sync; the function will be called with no arguments; defaults to None
:type syncCallback: function, optional
:param useFiddlerProxy: If True, all requests for this session will be sent through the Fiddler proxy, which allows Fiddler to watch outgoing network traffic for debug purposes; defaults to False
:type useFiddlerProxy: bool, optional
:param caseSensitiveComparisons: If True, various string comparisons will be done in a case-sensitive manner; see ._caseMatch; defaults to False
:type caseSensitiveComparisons: bool, optional
:param validatePoints: one of 'modify', 'warn', or False: should coordinates be checked or modified for correct longitude-then-latitide sequence as requests are sent; defaults to 'modify'; setting to False disables calls to ._validatePoints from ._sendRequest
:type validatePoints: optional
"""
self.s=requests.session()
self.apiVersion=-1
self.mapID=mapID
self.domainAndPort=domainAndPort
# configpath, account, id, and key are used to build
# signed requests for caltopo.com
self.configpath=configpath
self.account=account
self.queue={}
self.mapData={'ids':{},'state':{'features':[]}}
self.id=id
self.key=key
self.accountId=accountId
self.accountIdInternet=accountIdInternet
self.sync=sync
self.syncTimeout=syncTimeout
self.syncPause=False
self.propertyUpdateCallback=propertyUpdateCallback
self.geometryUpdateCallback=geometryUpdateCallback
self.newFeatureCallback=newFeatureCallback
self.deletedFeatureCallback=deletedFeatureCallback
self.syncCallback=syncCallback
self.syncInterval=syncInterval
self.syncCompletedCount=0
self.lastSuccessfulSyncTimestamp=0 # the server's integer milliseconds 'sincce' request completion time
self.lastSuccessfulSyncTSLocal=0 # this object's integer milliseconds sync completion time
self.syncDumpFile=syncDumpFile
self.cacheDumpFile=cacheDumpFile
self.useFiddlerProxy=useFiddlerProxy
self.syncing=False
self.caseSensitiveComparisons=caseSensitiveComparisons
self.validatePoints=validatePoints
self.accountData=None
# call _setupSession even if this is a mapless session, to read the config file, setup fidddler proxy, get userdata/cookies, etc.
if not self._setupSession():
raise CTSException
# if a map is specified, open it (or create it if '[NEW'])
if self.mapID:
if not self.openMap(self.mapID):
raise CTSException
else:
logging.info('Opening a CaltopoSession object with no associated map. Use .openMap(<mapID>) later to associate a map with this session.')
def openMap(self,mapID: str='') -> bool:
"""Open a map for usage in the current session.
This is automatically called during session initialization (by _setupSession) if mapID was specified when the session was created, but can be called later from your code if the session was initially 'mapless'.
If mapID starts with '[NEW]', a new map will be created and opened for use in the current session. You can follow the [NEW] keyword by the new map's mode and title in the format *[sar:]<title>*
- [NEW] - creates a new map with the default title 'newMap'
- [NEW]myOtherMap - creates a new map with the title 'myOtherMap'
- [NEW]sar:mySARMap - creates a new SAR-mode map with the title 'mySARMap'
The new map's ID will be stored in the session's .mapID varaiable.
NOTE: New map creation only works with CalTopo Desktop in this version of the module. It does not currently work for caltopo.com.
:param mapID: 3-to-7-character Map ID, or '[NEW]' with specification described above; defaults to ''
:type mapID: str, optional
:return: True if map was opened successfully; False otherwise.
:rtype: bool
"""
if self.mapID and self.lastSuccessfulSyncTimestamp>0:
logging.warning('WARNING: this CaltopoSession object is already connected to map '+self.mapID+'. Call to openMap ignored.')
return
if not mapID or not isinstance(mapID,str) or ((len(mapID)<3 or len(mapID)>7) and not mapID.startswith('[NEW]')):
logging.warning('WARNING: map ID must be a three-to-seven-character caltopo map ID string (end of the URL). No map will be opened for this CaltopoSession object.')
raise CTSException
self.mapID=mapID
# new map requested
# 1. send a POST request to /map - payload (tested on CTD 4225; won't work with <4221) =
if mapID.startswith('[NEW]'):
if self.domainAndPort.lower() in ['caltopo.com','sartopo.com']:
logging.error("New map creation only works with CalTopo Desktop in this version of caltopo_python.")
return False
title='newMap'
mode='cal'
if len(mapID)>5:
newMapTailParse=mapID[5:].split(':')
if len(newMapTailParse)>1 and newMapTailParse[1]!='':
title=newMapTailParse[1]
mode=newMapTailParse[0].lower()
if mode!='sar':
logging.warning('new map specification '+str(mapID)+' did not parse correctly; using mode "cal" for recreation mode')
mode='cal'
else:
title=newMapTailParse[0]
logging.info('about to create a new map with title "'+title+'" and mode "'+mode+'"')
j={}
j['properties']={
'mapConfig':json.dumps({'activeLayers':[['mbt',1]]}),
'cfgLocked':True,
'title':title,
'mode':mode # 'cal' for recreation, 'sar' for SAR
}
j['state']={
'type':'FeatureCollection',
'features':[
# At least one feature must exist to set the 'updated' field of the map;
# otherwise it always shows up at the bottom of the map list when sorted
# chronologically. Definitely best to have it show up adjacent to the
# incident map.
{
'geometry': {
'coordinates': [-120,39,0,0],
'type':'Point'
},
'id':'11111111-1111-1111-1111-111111111111',
'type':'Feature',
'properties':{
'creator':self.accountId,
'title':'NewMapDummyMarker',
'class':'Marker'
}
}
]
}
# logging.info('dap='+str(self.domainAndPort))
# logging.info('payload='+str(json.dumps(j,indent=3)))
r=self._sendRequest('post','[NEW]',j,domainAndPort=self.domainAndPort)
if r:
self.mapID=r.rstrip('/').split('/')[-1]
self.s=requests.session()
self._sendUserdata() # to get session cookies for new session
time.sleep(1) # to avoid a 401 on the subsequent get request
self.delMarker('11111111-1111-1111-1111-111111111111')
else:
logging.info('New map request failed. See the log for details.')
return False
# logging.info("API version:"+str(self.apiVersion))
# sync needs to be done here instead of in the caller, so that
# edit functions can have access to the full json
self.syncThreadStarted=False
self.syncPauseManual=False
# regardless of whether sync is specified, we need to do the initial cache population
# here in the main thread, so that mapData is populated right away
logging.info('Initial cache population begins.')
self._doSync()
logging.info('Initial cache population complete.')
if self.sync:
self._start()
return True
def _setupSession(self) -> bool:
"""Called internally from __init__, regardless of whether this is a mapless session. Reads account information from the config file and takes care of various other setup tasks.
:return: True if setup was successful; False otherwise (which will raise CTSException from __init__).
:rtype: bool
"""
# set a flag: is this an internet session?
# if so, id and key are strictly required, and accountId is needed to print
# if not, all three are only needed in order to print
internet=self.domainAndPort and self.domainAndPort.lower() in ['sartopo.com','caltopo.com']
id=None
key=None
accountId=None
accountIdInternet=None
# if configpath and account are specified,
# conigpath must be the full pathname of a configparser-compliant
# config file, and account must be the name of a section within it,
# containing keys 'id' and 'key'.
# otherwise, those parameters must have been specified in this object's
# constructor.
# if both are specified, first the config section is read and then
# any parameters of this object are used to override the config file
# values.
# if any of those three values are still not specified, abort.
if self.configpath is not None:
if os.path.isfile(self.configpath):
if self.account is None:
logging.error("config file '"+self.configpath+"' is specified, but no account name is specified.")
return False
config=configparser.ConfigParser()
config.read(self.configpath)
if self.account not in config.sections():
logging.error("specified account '"+self.account+"' has no entry in config file '"+self.configpath+"'.")
return False
section=config[self.account]
id=section.get("id",None)
key=section.get("key",None)
accountId=section.get("accountId",None)
accountIdInternet=section.get("accountIdInternet",None)
if internet:
if id is None or key is None:
logging.error("account entry '"+self.account+"' in config file '"+self.configpath+"' is not complete:\n it must specify 'id' and 'key'.")
return False
if accountId is None:
logging.warning("account entry '"+self.account+"' in config file '"+self.configpath+"' does not specify 'accountId': you will not be able to generate PDF files from this session.")
else:
if id is None or key is None or accountId is None:
logging.warning("account entry '"+self.account+"' in config file '"+self.configpath+"' is not complete:\n it must specify 'id', 'key', and 'accountId' if you want to generate PDF files from this session.")
if accountIdInternet is None:
logging.warning("account entry '"+self.account+"' in config file '"+self.configpath+"' does not specify 'accountIdInternet': if a different accountId is required for caltopo.com/saratopo.com vs. for CalTopo Desktop, you will not be able to send PDF generation jobs to the internet from this session.")
else:
logging.error("specified config file '"+self.configpath+"' does not exist.")
return False
# now allow values specified in constructor to override config file values
if self.id is not None:
id=self.id
if self.key is not None:
key=self.key
if self.accountId is not None:
accountId=self.accountId
if self.accountIdInternet is not None:
accountIdInternet=self.accountIdInternet
# finally, save them back as parameters of this object
self.id=id
self.key=key
self.accountId=accountId
self.accountIdInternet=accountIdInternet
if internet:
if self.id is None:
logging.error("caltopo session is invalid: 'id' must be specified for online maps")
return False
if self.key is None:
logging.error("caltopo session is invalid: 'key' must be specified for online maps")
return False
# # by default, do not assume any caltopo session is running;
# # send a GET request to http://localhost:8080/api/v1/map/
# # response code 200 = new API
# # otherwise:
# # send a GET request to http://localhost:8080/rest/
# # response code 200 = old API
# try these hardcodes, instead of the above dummy-request, to see if it avoids the NPE's
self.apiVersion=1
self.apiUrlMid="/api/v1/map/[MAPID]/"
# To enable Fiddler support, so Fiddler can see outgoing requests sent from this code,
# add 'proxies=self.proxyDict' argument to request calls and use locahost port 8888
# (the default Fiddler proxy port number - configurable in Fiddler connection settings).
# Note that if Fiddler is NOT running, but the proxies are set, this would throw
# an exception each time. So, if Fiddler proxies are requested, confirm here first.
self.proxyDict=None
if self.useFiddlerProxy:
logging.info('This session was requested to use the Fiddler proxy. Verifying that the proxy host is running...')
try:
r=requests.get('http://127.0.0.1:8888')
except:
logging.warning('Fiddler proxy host does not appear to be running. This session will not use Fiddler proxies.')
else:
logging.info(' Fiddler ping response appears valid; setting the proxies: r='+str(r))
self.proxyDict={
'http':'http://127.0.0.1:8888',
'https':'https://127.0.0.1:8888',
'ftp':'ftp://127.0.0.1:8888'
}
# self._sendUserdata() # to get session cookies, in case this client has not connected in a long time
# but this requires a mapID to form the signature in the post request, so won't work for a mapless session
# maybe the getMapData request is sufficient to get the cookies?
return True
def _caseMatch(self,a:str,b:str) -> bool:
"""Compare two input strings to see if they are equal, based on the value of .caseSensitiveComparisons.
:param a: First string to compare.
:type a: str
:param b: Second string to compare.
:type b: str
:return: If .caseSensitiveComparisons is True, 'ABC' will not match 'Abc', and the return value will be False. \n
If .caseSensitiveComparisons is False, 'ABC' will match 'Abc', and the return value will be True. \n
Regardless of the value of .caseSensitiveComparisons, 'ABC' will match 'ABC', and the return value will be True.
:rtype: bool
"""
if isinstance(a,str) and isinstance(b,str) and not self.caseSensitiveComparisons:
a=a.upper()
b=b.upper()
return a==b
def _sendUserdata(self,activeLayers=[['mbt',1]],center=[-120,39],zoom=13):
"""Send a POST request to /api/v0/userdata with initial map center and zoom; this might actually no longer be needed; only called during creation of a new map.
:param activeLayers: initial map layer setup, defaults to [['mbt',1]]
:type activeLayers: list, optional
:param center: initial map center location, defaults to [-120,39]
:type center: list, optional
:param zoom: initial map zoom, defaults to 13
:type zoom: int, optional
"""
j={
'map':{
# 'config':{
# 'activeLayers':activeLayers
# },
'center':center,
'zoom':zoom
}
}
# logging.info('dap='+str(self.domainAndPort))
# logging.info('payload='+str(json.dumps(j,indent=3)))
self._sendRequest('post','api/v0/userdata',j,domainAndPort=self.domainAndPort)
# terminology:
# 'account' means a few different things in CalTopo:
#
# - the 'account' that is currently signed in
# --> this is refered to just by the word 'account' throughout this code
#
# - if the account's properties.subscriptionType value includes the word 'team',
# it's a 'groupAccount' (this includes MAI accounts);
# otherwise, it's a 'personalAccount' - normally there should just be one of these
#
# response structure 2-23-24, confirmed 5-5-24:
# result: dict
# features: list of dicts
# groups: list of dicts
# ids: dict of lists
# accounts: list of dicts
# timestamp: int # of msec
# rels: list of dicts
# status: str
# timestamp: int # of msec
#
# - maps (not bookmarks) are in the 'features' list, with type:Feature and properties.class:CollaborativeMap
# - bookmarks (not maps) are in the 'rels' list, with properties.class:UserAccountMapRel
def getAccountData(self) -> dict:
"""Get all account data for the session account. Populates .accountData, .groupAccounts, and .personalAccounts.
:return: value of .accountData
:rtype: dict
"""
logging.info('Getting account data:')
fromFileName=False # hardcoded for production; set to a filename for debug
if fromFileName:
self.accoundData={}
with open(fromFileName) as j:
print('reading account data from file "'+fromFileName+'"')
self.accountData=json.load(j)
if 'result' in self.accountData.keys():
self.accountData=self.accountData['result']
else:
url='/api/v1/acct/'+self.accountId+'/since/0'
# logging.info(' sending GET request 2 to '+url)
rj=self._sendRequest('get',url,j=None,returnJson='ALL')
self.accountData=rj['result']
# with open('acct_since_0.json','w') as outfile:
# outfile.write(json.dumps(rj,indent=3))
# self.groupAccounts=[x for x in self.accountData.get('accounts',{})
# if 'properties' in x.keys() and 'team' in x['properties'].get('subscriptionType')]
self.groupAccounts=[]
self.personalAccounts=[]
for account in self.accountData.get('accounts',[]):
if 'properties' in account.keys():
if 'team' in account['properties'].get('subscriptionType',''):
self.groupAccounts.append(account)
else:
self.personalAccounts.append(account)
# logging.info('The signed-in user is a member of these group accounts: '+str([x['properties']['title'] for x in self.groupAccounts]))
return self.accountData
# after getAccountData, all of the required data is available in self.accountData;
# getMapList is just a convenience function that returns a chronologically sorted
# list of map name strings, and corresponding mapIDs, for maps (and optionally
# bookmarks) in a specified group account title; contents of all subfolders of the
# specified group account are returned in the same flat list
# return value is a chronologically-sorted list of dicts (most recently updated first):
# getMapList('SAR Training Data') -->
# [
# {
# "id": ".....",
# "title": "Academy White Cloud 2024 Day 5",
# "updated": 1714957566248,
# "type": "map"
# },
# {
# "id": ".....",
# "title": "Nevada City Enduro 2024",
# "updated": 1714922628438,
# "type": "map"
# },
# ...,
# {
# "id": ".....",
# "title": "Omega Adademy 2024",
# "updated": 1714522622568,
# "type": "bookmark"
# },...]
def getMapList(self,groupAccountTitle: str='',includeBookmarks=True,refresh=False,titlesOnly=False) -> list:
"""Get a list of all maps in the user's personal account, or in the specified group account.
:param groupAccountTitle: Title of the group account to get the map list from; defaults to '', in which case only the personal map list is returned
:type groupAccountTitle: str, optional
:param includeBookmarks: If True, bookmarks will be included in the returned list; defaults to True
:type includeBookmarks: bool, optional
:param refresh: If True, a refresh will be performed before getting the map list; defaults to False
:type refresh: bool, optional
:param titlesOnly: If True, the return value will be a list of strings only; defaults to False
:type titlesOnly: bool, optional
:return: List of dicts, chronologically sorted (most recent first) by the value of 'updated': \n
*id* -> 5-character map ID \n
*title* -> map title \n
*updated* -> timestamp of most recent update to the map \n
*type* -> 'map' or 'bookmark' \n
if type is 'bookmark', another key *permission* will exist, with corresponding value
:rtype: list
"""
if refresh or not self.accountData:
self.getAccountData()
mapLists=[]
rval=[]
if groupAccountTitle:
groupAccountIds=[x['id'] for x in self.groupAccounts if x['properties']['title']==groupAccountTitle]
if type(groupAccountIds)==list:
if len(groupAccountIds)==0:
logging.warning('attempt to get map list for group account "'+groupAccountTitle+'", but the signed-in user is not a member of that group account; returning an empty map list.')
return []
elif len(groupAccountIds)>1:
logging.warning('the signed-in user is a member of more than one group account with the requested name "'+groupAccountTitle+'"; returning an empty list.')
return []
else:
logging.warning('groupAccountIds was not a list; returning an empty list.')
return []
gid=groupAccountIds[0]
maps=[f for f in self.accountData['features']
if 'properties' in f.keys()
and f['properties'].get('class','')=='CollaborativeMap'
and f['properties'].get('accountId','')==gid]
mapLists.append({'id':gid,'title':groupAccountTitle,'maps':maps})
else: # personal maps; allow for the possibility of multiple personal accounts
if len(self.personalAccounts)>1:
logging.info('The currently-signed-in user has more than one personal account; the return value will be a netsted list.')
for personalAccount in self.personalAccounts:
pid=personalAccount['id']
maps=[f for f in self.accountData['features']
if 'properties' in f.keys()
and f['properties'].get('class','')=='CollaborativeMap'
and f['properties'].get('accountId','')==pid]
mapLists.append({'id':pid,'title':[x['properties']['title'] for x in self.accountData['accounts'] if x['id']==pid][0],'maps':maps})
for mapList in mapLists:
theList=[]
for map in mapList['maps']:
mp=map['properties']
md={
'id':map['id'],
'title':mp['title'],
'updated':mp['updated'],
'type':'map'
}
if md not in theList:
theList.append(md)
if includeBookmarks:
bookmarks=[rel for rel in self.accountData['rels']
if 'properties' in rel.keys()
and rel['properties'].get('class','')=='UserAccountMapRel'
and rel['properties'].get('accountId','')==mapList['id']]
for bookmark in bookmarks:
bp=bookmark['properties']
# testing on bookmarks from various QR codes shows that 'type'
# corresponds to permission: 10=read, 16=update, 20=write
t=bp.get('type',0)
if t==10:
permission='read'
elif t==16:
permission='update'
elif t==20:
permission='write'
else:
permission='unknown'
bd={
'id':bp['mapId'],
'title':bp['title'],
'updated':bp['mapUpdated'],
'type':'bookmark',
'permission':permission
}
if bd not in theList:
theList.append(bd)
# chronological sort by update timestamp
theList.sort(key=lambda x: x['updated'],reverse=True)
if titlesOnly:
rval.append([x['title'] for x in theList])
else:
rval.append(theList)
# if there's only one map list, return it as one list; otherwise return a nested list
if len(rval)==1:
rval=rval[0]
return rval
def getAllMapLists(self,includePersonal=False,includeBookmarks=True,refresh=False,titlesOnly=False) -> list:
"""Get a structured list of maps from all group accounts of which the current user is a member. Optionally include the user's personal account(s).
:param includePersonal: If True, the user's personal account(s) will be included in the return value; defaults to False
:type includePersonal: bool, optional
:param includeBookmarks: If True, bookmarks will be included in the returned lists; defaults to True
:type includeBookmarks: bool, optional
:param refresh: If True, a refresh will be performed before getting the map lists; defaults to False
:type refresh: bool, optional
:param titlesOnly: If True, the return value will be a list of strings only; defaults to False
:type titlesOnly: bool, optional
:return: list of dicts: \n
*groupAccountTitle* -> title of the group account \n
-OR- \n
*personalAccountTitle* -> title of the personal account \n
*mapList* -> list of maps for this group account, in the same format as the return value from .getMapList
:rtype: list
"""
if refresh or not self.accountData:
self.getAccountData()
theList=[]
if includePersonal:
personalRval=self.getMapList(includeBookmarks=includeBookmarks,refresh=False,titlesOnly=titlesOnly)
# logging.info('personalRval:'+json.dumps(personalRval,indent=3))
if type(personalRval[0])==dict: # not nested; a list of dicts
theList.append({'personalAccountTitle':self.personalAccounts[0]['properties']['title'],'mapList':personalRval})
else: # nested; multiple personal accounts; a list of lists dicts
n=0 # index to self.personalAccounts; this assumes the sequence will be the same
for personalAcct in personalRval:
theList.append({'personalAccountTitle':self.personalAccounts[n]['properties']['title'],'mapList':personalAcct})
n+=1
for gat in [x['properties']['title'] for x in self.groupAccounts]:
mapList=self.getMapList(gat,includeBookmarks=includeBookmarks,refresh=False,titlesOnly=titlesOnly)
theList.append({'groupAccountTitle':gat,'mapList':mapList})
return theList
def getMapTitle(self,mapID='',refresh=False) -> str:
"""Get the title of a map specified by mapID.
:param mapID: 5-character map ID; defaults to ''
:type mapID: str, optional
:param refresh: If True, a refresh will be performed before getting the map title; defaults to False
:type refresh: bool, optional
:return: Map title
:rtype: str
"""
if refresh or not self.accountData:
self.getAccountData()
mapID=mapID or self.mapID
if not mapID:
logging.warning('getMapTitle was called with no mapID specified, but, the current session has no open map.')
return 'NONE'
titles=[x['properties']['title'] for x in self.accountData['features'] if x.get('id','').lower()==mapID.lower()]
if len(titles)>1:
logging.warning('More than one map have the specified map ID '+str(mapID)+':'+str(titles))
return ''
elif len(titles)==0:
logging.warning('No maps have the specified map ID '+str(mapID))
return ''
else:
return titles[0]
def getGroupAccountTitles(self,refresh=False) -> list:
"""Get the titles of all of the user's group accounts.
:param refresh: If True, a refresh will be performed before getting the account titles; defaults to False
:type refresh: bool, optional
:return: List of account titles
:rtype: list
"""
if refresh or not self.accountData:
self.getAccountData()
return [x['properties']['title'] for x in self.groupAccounts]
def _doSync(self):
"""Internal method to keep the cache (.mapData) in sync with the associated hosted map. **Calling this method directly could cause sync problems.** \n
- called on a regular interval from ._syncLoop in the sync thread \n
- called once from .openMap, when the map is first opened \n
- called as needed from ._refresh
"""
logging.info('sync marker: '+self.mapID+' begin')
if not self.mapID or self.apiVersion<0:
logging.error('sync request invalid: this caltopo session is not associated with a map.')
return False
if self.syncing:
logging.warning('sync-within-sync requested; returning to calling code.')
return False
self.syncing=True
# Keys under 'result':
# 1 - 'ids' will only exist on first sync or after a deletion, so, if 'ids' exists
# then just use it to replace the entire cached 'ids', and also do cleanup later
# by deleting any state->features from the cache whose 'id' value is not in 'ids'
# 2 - state->features is an array of changed existing features, and the array will
# have complete data for 'geometry', 'id', 'type', and 'properties', so, for each
# item in state->features, just replace the entire existing cached feature of
# the same id
# logging.info('Sending caltopo "since" request...')
rj=self._sendRequest('get','since/'+str(max(0,self.lastSuccessfulSyncTimestamp-500)),None,returnJson='ALL',timeout=self.syncTimeout)
logging.info("At request to sync")
if rj and rj['status']=='ok':
logging.info("At request to sync2")
if self.syncDumpFile:
with open(insertBeforeExt(self.syncDumpFile,'.since'+str(max(0,self.lastSuccessfulSyncTimestamp-500))),"w") as f:
f.write(json.dumps(rj,indent=3))
# response timestamp is an integer number of milliseconds; equivalent to
# int(time.time()*1000))
self.lastSuccessfulSyncTimestamp=rj['result']['timestamp']
# logging.info('Successful caltopo sync: timestamp='+str(self.lastSuccessfulSyncTimestamp))
if self.syncCallback:
self.syncCallback()
rjr=rj['result']
rjrsf=rjr['state']['features']
logging.info("At request to sync3:"+str(rjr)+":"+str(rjrsf))
# 1 - if 'ids' exists, use it verbatim; cleanup happens later
idsBefore=None
if 'ids' in rjr.keys():
idsBefore=copy.deepcopy(self.mapData['ids'])
self.mapData['ids']=rjr['ids']
logging.info(' Updating "ids"')
# 2 - update existing features as needed
if len(rjrsf)>0:
logging.info(' processing '+str(len(rjrsf))+' feature(s):'+str([x['id'] for x in rjrsf]))
# logging.info(json.dumps(rj,indent=3))
for f in rjrsf:
rjrfid=f['id']
prop=f['properties']
title=str(prop.get('title',None))
featureClass=str(prop['class'])
processed=False
for i in range(len(self.mapData['state']['features'])):
# only modify existing cache data if id and class are both matches:
# subset apptracks can have the same id as the finished apptrack shape
if self.mapData['state']['features'][i]['id']==rjrfid and self.mapData['state']['features'][i]['properties']['class']==featureClass:
# don't simply overwrite the entire feature entry:
# - if only geometry was changed, indicated by properties['nop']=true,
# then leave properties alone and just overwrite geometry;
# - if only properties were changed, geometry will not be in the response,
# so leave geometry alone
# SO:
# - if f->prop->title exists, replace the entire prop dict
# - if f->geometry exists, replace the entire geometry dict
if 'title' in prop.keys():
if self.mapData['state']['features'][i]['properties']!=prop:
logging.info(' Updating properties for '+featureClass+':'+title)
# logging.info(' old:'+json.dumps(self.mapData['state']['features'][i]['properties']))
# logging.info(' new:'+json.dumps(prop))
self.mapData['state']['features'][i]['properties']=prop
if self.propertyUpdateCallback:
self.propertyUpdateCallback(f)
else:
logging.info(' response contained properties for '+featureClass+':'+title+' but they matched the cache, so no cache update or callback is performed')
if title=='None':
title=self.mapData['state']['features'][i]['properties']['title']
if 'geometry' in f.keys():
if self.mapData['state']['features'][i]['geometry']!=f['geometry']:
logging.info(' Updating geometry for '+featureClass+':'+title)
# if geometry.incremental exists and is true, append new coordinates to existing coordinates
# otherwise, replace the entire geometry value
fg=f['geometry']
mdsfg=self.mapData['state']['features'][i]['geometry']
if fg.get('incremental',None):
mdsfgc=mdsfg['coordinates']
latestExistingTS=mdsfgc[-1][3]
fgc=fg.get('coordinates',[])
# avoid duplicates without walking the entire existing list of points;
# assume that timestamps are strictly increasing in list item sequence
# walk forward through new points:
# if timestamp is more recent than latest existing point, then append the rest of the new point list
for n in range(len(fgc)):
if fgc[n][3]>latestExistingTS:
mdsfgc+=fgc[n:]
break
mdsfg['size']=len(mdsfgc)
else:
self.mapData['state']['features'][i]['geometry']=f['geometry']
if self.geometryUpdateCallback:
self.geometryUpdateCallback(f)
else:
logging.info(' response contained geometry for '+featureClass+':'+title+' but it matched the cache, so no cache update or callback is performed')
processed=True
break
# 2b - otherwise, create it - and add to ids so it doesn't get cleaned
if not processed:
# logging.info('Adding to cache:'+featureClass+':'+title)
self.mapData['state']['features'].append(f)
if f['id'] not in self.mapData['ids'][prop['class']]:
self.mapData['ids'][prop['class']].append(f['id'])
# logging.info('mapData immediate:\n'+json.dumps(self.mapData,indent=3))
if self.newFeatureCallback:
self.newFeatureCallback(f)
# 3 - cleanup - remove features from the cache whose ids are no longer in cached id list
# (ids will be part of the response whenever feature(s) were added or deleted)
# (finishing an apptrack moves the id from AppTracks to Shapes, so the id count is not affected)
# (if the server does not remove the apptrack correctly after finishing, the same id will
# be in AppTracks and in Shapes)
# beforeStr='mapData before cleanup:'+json.dumps(self.mapData,indent=3)
# at this point in the code, the deleted feature has been removed from ids but is still part of state-features
# self.mapIDs=sum(self.mapData['ids'].values(),[])
# mapSFIDsBefore=[f['id'] for f in self.mapData['state']['features']]
# edit the cache directly: https://stackoverflow.com/a/1157174/3577105
if idsBefore:
deletedDict={}
deletedAnythingFlag=False
for c in idsBefore.keys():
for id in idsBefore[c]:
if id not in self.mapData['ids'][c]:
self.mapData['state']['features'][:]=(f for f in self.mapData['state']['features'] if not(f['id']==id and f['properties']['class']==c))
deletedDict.setdefault(c,[]).append(id)
deletedAnythingFlag=True
if self.deletedFeatureCallback:
self.deletedFeatureCallback(id,c)
if deletedAnythingFlag:
logging.info('deleted items have been removed from cache:\n'+json.dumps(deletedDict,indent=3))
# l1=len(self.mapData['state']['features'])
# logging.info('before:'+str(l1)+':'+str(self.mapData['state']['features']))
# self.mapData['state']['features'][:]=(f for f in self.mapData['state']['features'] if f['id'] in self.mapIDs)
# mapSFIDs=[f['id'] for f in self.mapData['state']['features']]
# l2=len(self.mapData['state']['features'])
# logging.info('after:'+str(l1)+':'+str(self.mapData['state']['features']))
# if l2!=l1:
# deletedIds=list(set(mapSFIDsBefore)-set(mapSFIDs))
# logging.info('cleaned up '+str(l1-l2)+' feature(s) from the cache:'+str(deletedIds))
# if self.deletedFeatureCallback:
# for did in deletedIds:
# self.deletedFeatureCallback(did)
# logging.info(beforeStr)
# logging.info('mapData after cleanup:'+json.dumps(self.mapData,indent=3))
# logging.info('mapData:\n'+json.dumps(self.mapData,indent=3))
# logging.info('\n'+self.mapID+':\n mapIDs:'+str(self.mapIDs)+'\nmapSFIDs:'+str(mapSFIDs))
# bug: i is defined as an index into mapSFIDs but is used as an index into self.mapData['state']['features']:
# # for i in range(len(mapSFIDs)):
# # if mapSFIDs[i] not in self.mapIDs:
# # prop=self.mapData['state']['features'][i]['properties']
# # logging.info(' Deleting '+mapSFIDs[i]+':'+str(prop['class'])+':'+str(prop['title']))
# # if self.deletedFeatureCallback:
# # self.deletedFeatureCallback(self.mapData['state']['features'][i])
# # del self.mapData['state']['features'][i]
if self.cacheDumpFile:
with open(insertBeforeExt(self.cacheDumpFile,'.cache'+str(max(0,self.lastSuccessfulSyncTimestamp))),"w") as f:
f.write('sync cleanup:')
f.write(' mapIDs='+str(self.mapID)+'\n\n')
# f.write(' mapSFIDs='+str(mapSFIDs)+'\n\n')
f.write(json.dumps(self.mapData,indent=3))
# self.syncing=False
self.lastSuccessfulSyncTSLocal=int(time.time()*1000)
if self.sync:
if not threading.main_thread().is_alive():
logging.info('Main thread has ended; sync is stopping...')
self.sync=False
# if threading.main_thread().is_alive():
# # this is where the blocking sleep happens, instead of spawning a new thread;
# # normally this function is being called in a separate thread anyway, so
# # the main thread can continue while this thread sleeps
# logging.info(' sleeping for specified sync interval ('+str(self.syncInterval)+' seconds)...')
# time.sleep(self.syncInterval)
# while self.syncPause: # wait until at least one second after sendRequest finishes
# logging.info(' sync is paused - sleeping for one second')
# time.sleep(1)
# self._doSync() # will this trigger the recursion limit eventually? Rethink looping method!
# else:
# logging.info('Main thread has ended; sync is stopping...')
else:
logging.error('Sync returned invalid or no response; sync aborted:'+str(rj))
self.sync=False
self.apiVersion=-1 # downstream tools may use apiVersion as indicator of link status
self.syncing=False
logging.info('sync marker: '+self.mapID+' end')
# _refresh - update the cache (self.mapData) by calling _doSync once;
# only relevant if sync is off; if the latest refresh is within the sync interval value (even when sync is off),
# then don't do a refresh unless forceImmediate is True
# since _doSync() would be called from this thread, it is always blocking
def _refresh(self,forceImmediate=False):
"""Refresh the cache (.mapData). **This method should not need to be called when sync is on.**
:param forceImmediate: If True, the refresh will happen immediately, even if a refresh was already done within the timeout period; defaults to False
:type forceImmediate: bool, optional
"""
if not self.mapID or self.apiVersion<0:
logging.error('refresh request invalid: this caltopo session is not associated with a map.')
return False
msg='refresh requested for map '+self.mapID+': '
if self.syncing:
msg+='sync already in progress'
logging.info(msg)
else:
d=int(time.time()*1000)-self.lastSuccessfulSyncTSLocal # integer ms since last completed sync
msg+=str(d)+'ms since last completed sync; '
if d>(self.syncInterval*1000):
msg+='longer than syncInterval: syncing now'
logging.info(msg)
self._doSync()
else:
msg+='shorter than syncInterval; '
if forceImmediate:
msg+='forceImmediate specified: syncing now'
logging.info(msg)
self._doSync()
else:
msg+='forceImmediate not specified: not syncing now'