-
Notifications
You must be signed in to change notification settings - Fork 1
/
sartopo_python.py
2501 lines (2352 loc) · 120 KB
/
sartopo_python.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
# #############################################################################
#
# sartopo_python.py - python interfaces to the sartopo API
#
# developed for Nevada County Sheriff's Search and Rescue
# Copyright (c) 2020 Tom Grundy
#
# Sartopo / 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 sartopo
# interface to other applications.
#
# This python code is in no way supported or maintained by caltopo LLC
# or the authors of caltopo.com or sartopo.com.
#
# www.github.com/ncssar/sartopo_python
#
# Contact the author at [email protected]
# Attribution, feedback, bug reports and feature requests are appreciated
#
############################################################
#
# EXAMPLES:
#
# from sartopo_python import SartopoSession
# import time
#
# sts=SartopoSession('localhost:8080','<offlineMapID>')
# fid=sts.addFolder('MyFolder')
# sts.addMarker(39,-120,'stuff')
# sts.addMarker(39.01,-120.01,'myStuff',folderId=fid)
# r=sts.getFeatures('Marker')
# print('r:'+str(r))
# print('moving the marker after a pause:'+r[0]['id'])
# time.sleep(5)
# sts.addMarker(39.02,-120.02,r[0]['properties']['title'],existingId=r[0]['id'])
#
# sts2=SartopoSession(
# 'sartopo.com',
# '<onlineMapID>',
# configpath='../../sts.ini',
# account='<accountName>')
# fid2=sts2.addFolder('MyOnlineFolder')
# sts2.addMarker(39,-120,'onlineStuff')
# sts2.addMarker(39.01,-119.99,'onlineStuff2',folderId=fid2)
# r2=sts2.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'])
# sts2.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?
#
#
# REVISION HISTORY
#-----------------------------------------------------------------------------
# DATE | AUTHOR | NOTES
#-----------------------------------------------------------------------------
# 8-29-18 TMG First version - creates folders and markers
# 10-7-18 TMG allow session on network other than localhost; allow
# three-character mapID; overhaul to work with
# significant api changes in v4151 of sar.jar -
# probably not backwards compatible; will require
# changes to code that calls these functions
# 11-19-18 TMG clean up for first package release
# 6-29-19 TMG add getFeatures to return a list of map features with IDs;
# move an existing marker by specifying existing marker ID
# 7-3-19 TMG return folderId, if it exists, with each feature returned
# by getFeatures, to allow filtering by folder; modify
# setupSession to only return API version 1 if the
# API is version 1 AND the map ID is valid
# 3-30-20 TMG fix #3: v1.0.6: change the return value structure from getFeatures
# to return the entire json structure for each feature;
# this enables preservation of marker-symbol when moving
# an existing marker
# 5-30-20 TMG fix #2: v1.1.0: send signed requests to sartopo.com (online)
# 6-2-20 TMG v1.1.1: fix #5 (use correct meaning of 'expires');
# fix #6 (__init__ returns None on failure)
# 4-5-21 TMG sync (fix #17)
# 6-15-21 TMG add geometry operations cut, expand, crop
# 6-27-21 TMG stop sync when main thread terminates (fix #19)
# 6-28-21 TMG remove spurs to fix self-intersecting polygons (fix #20)
# 6-29-21 TMG return gracefully if shapes do not intersect (fix #21)
# 6-30-21 TMG fix #26; various error handling and logging improvements
# 6-30-21 TMG do an initial since(0) request even if sync=False (fix #25)
# 7-4-21 TMG preserve complex lines during crop (fix #29); other cleanup
# 8-8-21 TMG sync and getFeature/s overhaul: sync iteratively instead of
# recursively; handle cache refreshing such that downstream
# apps should never need to access .mapData, but should only
# make calls to getFeature/s (fix #23)
# 8-9-21 TMG add new objects to .mapData immediately (fix #28)
#-----------------------------------------------------------------------------
import hmac
import base64
import requests
import json
import configparser
import os
import time
import logging
import sys
import threading
import copy
# import objgraph
# import psutil
# process=psutil.Process(os.getpid())
# syncing=False
# shapely.geometry improts 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 STSException(BaseException):
pass
class SartopoSession():
def __init__(self,
domainAndPort='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 sartopo.com/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()
self.s=requests.session()
self.apiVersion=-1
if not mapID or not isinstance(mapID,str) or len(mapID)<3:
logging.warning('WARNING: you must specify a three-or-more-character sartopo map ID string (end of the URL) when opening a SartopoSession object.')
raise STSException
self.mapID=mapID
self.domainAndPort=domainAndPort
# configpath, account, id, and key are used to build
# signed requests for sartopo.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
if not self.setupSession():
raise STSException
def setupSession(self):
# 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("sartopo session is invalid: 'id' must be specified for online maps")
return False
if self.key is None:
logging.error("sartopo session is invalid: 'key' must be specified for online maps")
return False
# # by default, do not assume any sartopo 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
# self.apiUrlMid="/invalid/"
# url="http://"+self.domainAndPort+"/api/v1/map/"
# logging.info("searching for API v1: sending get to "+url)
# try:
# r=self.s.get(url,timeout=10)
# except:
# logging.error("no response from first get request; aborting; should get a response of 400 at this point for api v0")
# return False
# else:
# logging.info("response code = "+str(r.status_code))
# if r.status_code==200:
# # now validate the mapID, since the initial test doesn't care about mapID
# mapUrl="http://"+self.domainAndPort+"/m/"+self.mapID
# try:
# r=self.s.get(mapUrl,timeout=10)
# except:
# logging.error("API version 1 detected, but the get request timed out so the mapID is not valid: "+mapUrl)
# return False
# else:
# if r.status_code==200:
# # now we know the API is valid and the mapID is valid
# self.apiVersion=1
# self.apiUrlMid="/api/v1/map/[MAPID]/"
# else:
# logging.error("API version 1 detected, but the map-specific URL '"+self.mapID+"' returned a code of "+str(r.status_code)+" so this session is not valid.")
# return False
# else:
# url="http://"+self.domainAndPort+"/rest/marker/"
# logging.info("searching for API v0: sending get to "+url)
# try:
# r=self.s.get(url,timeout=10)
# except:
# logging.info("no response from second get request")
# else:
# logging.info("response code = "+str(r.status_code))
# if r.status_code==200:
# self.apiVersion=0
# self.apiUrlMid="/rest/"
# # for v0, send a get to the map URL to authenticate the session
# url="http://"+self.domainAndPort+"/m/"+self.mapID
# logging.info("sending API v0 authentication request to url "+url)
# try:
# r=self.s.get(url,timeout=10)
# except:
# logging.info("no response during authentication for API v0")
# else:
# logging.info("response code = "+str(r.status_code))
# if r.status_code==200:
# logging.info("API v0 session is now authenticated")
# 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
# new map requested
# 1. send a POST request to /map - payload (tested on CTD 4225; won't work with <4221) =
if self.mapID=='[NEW]':
j={}
j['properties']={
'mapConfig':json.dumps({'activeLayers':[['mbt',1]]}),
'cfgLocked':True,
'title':'new',
'mode':'sar' # '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':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(id='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 caseMatch(self,a,b):
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):
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)
def doSync(self):
# logging.info('sync marker: '+self.mapID+' begin')
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 sartopo "since" request...')
rj=self.sendRequest('get','since/'+str(max(0,self.lastSuccessfulSyncTimestamp-500)),None,returnJson='ALL',timeout=self.syncTimeout)
if rj and rj['status']=='ok':
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 sartopo sync: timestamp='+str(self.lastSuccessfulSyncTimestamp))
if self.syncCallback:
self.syncCallback()
rjr=rj['result']
rjrsf=rjr['state']['features']
# 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,blocking=False,forceImmediate=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'
# logging.info(msg)
def __del__(self):
logging.info('SartopoSession instance deleted for map '+self.mapID+'.')
if self.sync:
self.stop()
def start(self):
self.sync=True
if self.syncThreadStarted:
logging.info('Sartopo sync is already running for map '+self.mapID+'.')
else:
threading.Thread(target=self._syncLoop).start()
logging.info('Sartopo syncing initiated for map '+self.mapID+'.')
self.syncThreadStarted=True
def stop(self):
logging.info('Sartopo sync terminating for map '+self.mapID+'.')
self.sync=False
def pause(self):
logging.info('Pausing sync for map '+self.mapID+'...')
self.syncPauseManual=True
def resume(self):
logging.info('Resuming sync for map '+self.mapID+'.')
self.syncPauseManual=False
# _syncLoop - should only be called from self.start(), which calls _syncLoop in a new thread.
# This is just a loop that calls doSync. To prevent an endless loop, doSync must be
# able to terminate the thread if the main thread has ended; also note that any other
# code can end sync by setting self.sync to False. This allows doSync to be
# iterative rather than recursive (which would eventually hit recursion limit issues),
# and it allows the blocking sleep call to happen here instead of inside doSync.
def _syncLoop(self):
if self.syncCompletedCount==0:
logging.info('This is the first sync attempt; pausing for the normal sync interval before starting sync.')
time.sleep(self.syncInterval)
while self.sync:
if not self.syncPauseManual:
self.syncPauseMessageGiven=False
while self.syncPause:
if not threading.main_thread().is_alive():
logging.info('Main thread has ended; sync is stopping...')
self.syncPause=False
self.sync=False
if not self.syncPauseMessageGiven:
logging.info(self.mapID+': sync pause begins; sync will not happen until sync pause ends')
self.syncPauseMessageGiven=True
time.sleep(1)
if self.syncPauseMessageGiven:
logging.info(self.mapID+': sync pause ends; resuming sync')
self.syncPauseMessageGiven=False
syncWaited=0
while self.syncing and syncWaited<20: # wait for any current callbacks within doSync() to complete, with timeout of 20 sec
logging.info(' [sync from _syncLoop is waiting for current sync processing to finish, up to '+str(20-syncWaited)+' more seconds...]')
time.sleep(1)
syncWaited+=1
try:
self.doSync()
self.syncCompletedCount+=1
except Exception as e:
logging.exception('Exception during sync of map '+self.mapID+'; stopping sync:') # logging.exception logs details and traceback
# remove sync blockers, to let the thread shut down cleanly, avoiding a zombie loop when sync restart is attempted
self.syncPause=False
self.syncing=False
self.syncThreadStarted=False
self.sync=False
if self.sync: # don't bother with the sleep if sync is no longer True
time.sleep(self.syncInterval)
def sendRequest(self,type,apiUrlEnd,j,id="",returnJson=None,timeout=None,domainAndPort=None):
# objgraph.show_growth()
# logging.info('RAM:'+str(process.memory_info().rss/1024**2)+'MB')
self.syncPause=True
timeout=timeout or self.syncTimeout
newMap='[NEW]' in apiUrlEnd # specific mapID that indicates a new map should be created
if self.apiVersion<0:
logging.error("sendRequest: sartopo session is invalid; request aborted: type="+str(type)+" apiUrlEnd="+str(apiUrlEnd))
return False
mid=self.apiUrlMid
if 'api/' in apiUrlEnd.lower():
mid='/'
else:
apiUrlEnd=apiUrlEnd.lower()
if self.apiVersion>0:
apiUrlEnd=apiUrlEnd.capitalize()
if apiUrlEnd.startswith("Since"): # 'since' must be lowercase even in API v1
apiUrlEnd=apiUrlEnd.lower()
# append id (if any) to apiUrlEnd so that it is a part of the request
# destination and also a part of the pre-hashed data for signed requests
if id and id!="": # sending online request with slash at the end causes failure
apiUrlEnd=apiUrlEnd+"/"+id
mid=mid.replace("[MAPID]",self.mapID)
apiUrlEnd=apiUrlEnd.replace("[MAPID]",self.mapID)
domainAndPort=domainAndPort or self.domainAndPort # use arg value if specified
if not domainAndPort:
logging.error("sendRequest was attempted but no valid domainAndPort was specified.")
return False
prefix='http://'
# set a flag: is this an internet request?
accountId=self.accountId
internet=domainAndPort.lower() in ['sartopo.com','caltopo.com']
if internet:
if self.accountIdInternet:
accountId=self.accountIdInternet
else:
logging.warning('A request is about to be sent to the internet, but accountIdInternet was not specified. The request will use accountId, but will fail if that ID does not have valid permissions at the internet host.')
prefix='https://'
if not self.key or not self.id:
logging.error("There was an attempt to send an internet request, but 'id' and/or 'key' was not specified for this session. The request will not be sent.")
return False
url=prefix+domainAndPort+mid+apiUrlEnd
wrapInJsonKey=True
if newMap:
url=prefix+domainAndPort+'/api/v1/acct/'+accountId+'/CollaborativeMap' # works for CTD 4221 and up
if '/since/' not in url:
logging.info("sending "+str(type)+" to "+url)
if type=="post":
if wrapInJsonKey:
params={}
params["json"]=json.dumps(j)
else:
params=j
if internet:
expires=int(time.time()*1000)+120000 # 2 minutes from current time, in milliseconds
data="POST "+mid+apiUrlEnd+"\n"+str(expires)+"\n"+json.dumps(j)
# logging.info("pre-hashed data:"+data)
token=hmac.new(base64.b64decode(self.key),data.encode(),'sha256').digest()
token=base64.b64encode(token).decode()
# logging.info("hashed data:"+str(token))
params["id"]=self.id
params["expires"]=expires
params["signature"]=token
paramsPrint=copy.deepcopy(params)
paramsPrint['id']='.....'
paramsPrint['signature']='.....'
else:
paramsPrint=params
# logging.info("SENDING POST to '"+url+"':")
# logging.info(json.dumps(paramsPrint,indent=3))
# don't print the entire PDF generation request - upstream code can print a PDF data summary
if 'PDFLink' not in url:
logging.info(jsonForLog(paramsPrint))
r=self.s.post(url,data=params,timeout=timeout,proxies=self.proxyDict,allow_redirects=False)
elif type=="get": # no need for json in GET; sending null JSON causes downstream error
# logging.info("SENDING GET to '"+url+"':")
r=self.s.get(url,timeout=timeout,proxies=self.proxyDict)
elif type=="delete":
params={}
if "sartopo.com" in self.domainAndPort.lower():
expires=int(time.time()*1000)+120000 # 2 minutes from current time, in milliseconds
data="DELETE "+mid+apiUrlEnd+"\n"+str(expires)+"\n" #last newline needed as placeholder for json
# logging.info("pre-hashed data:"+data)
token=hmac.new(base64.b64decode(self.key),data.encode(),'sha256').digest()
token=base64.b64encode(token).decode()
# logging.info("hashed data:"+str(token))
params["json"]='' # no body, but is required
params["id"]=self.id
params["expires"]=expires
params["signature"]=token
# paramsPrint=copy.deepcopy(params)
# paramsPrint['id']='.....'
# paramsPrint['signature']='.....'
# else:
# paramsPrint=params
# logging.info("SENDING DELETE to '"+url+"':")
# logging.info(json.dumps(paramsPrint,indent=3))
# logging.info("Key:"+str(self.key))
r=self.s.delete(url,params=params,timeout=timeout,proxies=self.proxyDict) ## use params for query vs data for body data
# logging.info("URL:"+str(url))
# logging.info("Ris:"+str(r))
else:
logging.error("sendRequest: Unrecognized request type:"+str(type))
self.syncPause=False
return False
if r.status_code!=200:
logging.info("response code = "+str(r.status_code))
if newMap:
# for CTD 4221 and newer, and internet, a new map request should return 200, and the response data
# should contain the new map ID in response['result']['id']
# for CTD 4214, a new map request should return 3xx response (redirect); if allow_redirects=False is
# in the response, the redirect target will appear as the 'Location' response header.
if r.status_code==200:
try:
rj=r.json()
except:
logging.error('New map request failed: response had do decodable json:'+str(r.status_code)+':'+r.text)
self.syncPause=False
return False
else:
rjr=rj.get('result')
newUrl=None
if rjr:
newUrl=rjr['id']
if newUrl:
logging.info('New map URL:'+newUrl)
self.syncPause=False
return newUrl
else:
logging.error('No new map URL was returned in the response json:'+str(r.status_code)+':'+json.dumps(rj))
self.syncPause=False
return False
else:
logging.error('New map request failed:'+str(r.status_code)+':'+r.text)
self.syncPause=False
return False
# old redirect method worked with CTD 4214:
# if url.endswith('/map'):
# if 300<=r.status_code<=399:
# # logging.info("response headers:"+str(json.dumps(dict(r.headers),indent=3)))
# newUrl=r.headers.get('Location',None)
# if newUrl:
# logging.info('New map URL:'+newUrl)
# self.syncPause=False
# return newUrl
# else:
# logging.info('No new map URL was returned in the response header.')
# self.syncPause=False
# return False
# else:
# logging.info('Unexpected response from new map request:'+str(r.status_code)+':'+r.text)
# return False
# else:
# if r.status_code==200:
# logging.info('200 response from new map request:'+r.text)
# return False
# else:
# logging.info('Unexpected response from new map request:'+str(r.status_code)+':'+r.text)
# return False
else:
if returnJson:
# logging.info('response:'+str(r))
try:
rj=r.json()
except:
logging.error("sendRequest: response had no decodable json:"+str(r))
self.syncPause=False
return False
else:
if 'status' in rj and rj['status'].lower()!='ok':
msg='response status other than "ok"'
if 'message' in rj and 'error saving object' in rj['message'].lower():
msg+='; maybe the user does not have necessary permissions on this map'
msg+=': '+str(rj)
logging.warning(msg)
self.syncPause=False
return False
if returnJson=="ID":
id=None
if 'result' in rj and 'id' in rj['result']:
id=rj['result']['id']
elif 'id' in rj:
id=rj['id']
elif not rj['result']['state']['features']: # response if no new info
self.syncPause=False
return 0
elif 'result' in rj and 'id' in rj['result']['state']['features'][0]:
id=rj['result']['state']['features'][0]['id']
else:
logging.info("sendRequest: No valid ID was returned from the request:")
logging.info(json.dumps(rj,indent=3))
self.syncPause=False
return id
if returnJson=="ALL":
# since CTD 4221 returns 'title' as an empty string for all assignments,
# set 'title' to <letter><space><number> for all assignments here
# this code looks fairly resource intensive; for a map with 50 assignments, initial sync
# is about 6.5% slower with this if clause than without, but it would be good to profile
# memory consumption too - is this calling .keys() and creating new lists each time?
# maybe better to wrap it all in try/except, but, would that iterate over all features?
if 'result' in rj.keys() and 'state' in rj['result'].keys() and 'features' in rj['result']['state'].keys():
alist=[f for f in rj['result']['state']['features'] if 'properties' in f.keys() and 'class' in f['properties'].keys() and f['properties']['class'].lower()=='assignment']
for a in alist:
a['properties']['title']=str(a['properties'].get('letter',''))+' '+str(a['properties'].get('number',''))
self.syncPause=False
return rj
self.syncPause=False
def addFolder(self,
label="New Folder",
timeout=None,
queue=False):
j={}
j['properties']={}
j['properties']['title']=label
j['properties']['folder-visibility']='visible'
if queue:
self.queue.setdefault('folder',[]).append(j)
return 0
else:
# return self.sendRequest("post","folder",j,returnJson="ID")
# add to .mapData immediately
rj=self.sendRequest('post','folder',j,returnJson='ALL',timeout=timeout)
if rj:
rjr=rj['result']
id=rjr['id']
self.mapData['ids'].setdefault('Folder',[]).append(id)
self.mapData['state']['features'].append(rjr)
return id
else:
return False
def addMarker(self,
lat,
lon,
title='New Marker',
description='',
color='#FF0000',
symbol='point',
rotation=None,
folderId=None,
existingId=None,
update=0,
size=1,