-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathremote_lrs.py
More file actions
932 lines (759 loc) · 31.5 KB
/
remote_lrs.py
File metadata and controls
932 lines (759 loc) · 31.5 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
# Copyright 2014 Rustici Software
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import http.client
import json
import base64
import socket
from urllib.parse import urlparse, urlencode
from tincan.lrs_response import LRSResponse
from tincan.http_request import HTTPRequest
from tincan.statement_list import StatementList
from tincan.agent import Agent
from tincan.statement import Statement
from tincan.activity import Activity
from tincan.statements_result import StatementsResult
from tincan.about import About
from tincan.version import Version
from tincan.base import Base
from tincan.documents import (
StateDocument,
ActivityProfileDocument,
AgentProfileDocument
)
"""
.. module:: remote_lrs
:synopsis: The RemoteLRS class implements LRS communication.
"""
class RemoteLRS(Base):
_props_req = [
'version',
'endpoint',
'timeout',
'auth',
]
_props = []
_props.extend(_props_req)
def __init__(self, *args, **kwargs):
"""RemoteLRS Constructor
:param endpoint: lrs endpoint
:type endpoint: str | unicode
:param timeout: Timeout (in seconds) used for lrs communication
:type timeout: float
:param version: Version used for lrs communication
:type version: str | unicode
:param username: Username for lrs. Used to build the authentication string.
:type username: str | unicode
:param password: Password for lrs. Used to build the authentication string.
:type password: str | unicode
:param auth: Authentication string
:type auth: str | unicode
"""
self._version = Version.latest
self._endpoint = None
self._timeout = None
self._auth = None
if "username" in kwargs \
and kwargs["username"] is not None \
and "password" in kwargs \
and kwargs["password"] is not None \
and "auth" not in kwargs:
bytes = (
str(kwargs["username"]) +
":" +
str(kwargs["password"])).encode('ASCII')
auth_string = str.format("Basic {}", base64.b64encode(bytes).decode("utf-8"))
kwargs.pop("username")
kwargs.pop("password")
kwargs["auth"] = auth_string
super(RemoteLRS, self).__init__(*args, **kwargs)
def _send_request(self, request):
"""Establishes connection and returns http response based off of request.
:param request: HTTPRequest object
:type request: :class:`tincan.http_request.HTTPRequest`
:returns: LRS Response object
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
headers = {"X-Experience-API-Version": self.version}
if self.auth is not None:
headers["Authorization"] = self.auth
headers.update(request.headers)
params = request.query_params
params = {k: str(params[k]).encode('utf-8') for k in list(params.keys())}
params = urlencode(params)
if request.resource.startswith('http'):
url = request.resource
else:
url = self.endpoint
url += request.resource
parsed = urlparse(url)
timeout = self.timeout or socket._GLOBAL_DEFAULT_TIMEOUT
if parsed.scheme == "https":
web_req = http.client.HTTPSConnection(parsed.hostname, parsed.port, timeout=timeout)
else:
web_req = http.client.HTTPConnection(parsed.hostname, parsed.port, timeout=timeout)
path = parsed.path
if parsed.query or parsed.path:
path += "?"
if parsed.query:
path += parsed.query
if params:
path += params
if hasattr(request, "content") and request.content is not None:
web_req.request(
method=request.method,
url=path,
body=request.content,
headers=headers,
)
else:
web_req.request(
method=request.method,
url=path,
headers=headers,
)
response = web_req.getresponse()
data = response.read()
web_req.close()
if (200 <= response.status < 300
or (response.status == 404
and hasattr(request, "ignore404")
and request.ignore404)):
success = True
else:
success = False
return LRSResponse(
success=success,
request=request,
response=response,
data=data,
)
def about(self):
"""Gets about response from LRS
:return: LRS Response object with the returned LRS about object as content
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
request = HTTPRequest(
method="GET",
resource="about"
)
lrs_response = self._send_request(request)
if lrs_response.success:
lrs_response.content = About.from_json(lrs_response.data)
return lrs_response
def save_statement(self, statement):
"""Save statement to LRS and update statement id if necessary
:param statement: Statement object to be saved
:type statement: :class:`tincan.statement.Statement`
:return: LRS Response object with the saved statement as content
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
if not isinstance(statement, Statement):
statement = Statement(statement)
request = HTTPRequest(
method="POST",
resource="statements"
)
if statement.id is not None:
request.method = "PUT"
request.query_params["statementId"] = statement.id
request.headers["Content-Type"] = "application/json"
request.content = statement.to_json(self.version)
lrs_response = self._send_request(request)
if lrs_response.success:
if statement.id is None:
statement.id = json.loads(lrs_response.data)[0]
lrs_response.content = statement
return lrs_response
def save_statements(self, statements):
"""Save statements to LRS and update their statement id's
:param statements: A list of statement objects to be saved
:type statements: :class:`StatementList`
:return: LRS Response object with the saved list of statements as content
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
if not isinstance(statements, StatementList):
statements = StatementList(statements)
request = HTTPRequest(
method="POST",
resource="statements"
)
request.headers["Content-Type"] = "application/json"
request.content = statements.to_json()
lrs_response = self._send_request(request)
if lrs_response.success:
id_list = json.loads(lrs_response.data)
for s, statement_id in zip(statements, id_list):
s.id = statement_id
lrs_response.content = statements
return lrs_response
def retrieve_statement(self, statement_id):
"""Retrieve a statement from the server from its id
:param statement_id: The UUID of the desired statement
:type statement_id: str | unicode
:return: LRS Response object with the retrieved statement as content
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
request = HTTPRequest(
method="GET",
resource="statements"
)
request.query_params["statementId"] = statement_id
lrs_response = self._send_request(request)
if lrs_response.success:
lrs_response.content = Statement.from_json(lrs_response.data)
return lrs_response
def retrieve_voided_statement(self, statement_id):
"""Retrieve a voided statement from the server from its id
:param statement_id: The UUID of the desired voided statement
:type statement_id: str | unicode
:return: LRS Response object with the retrieved voided statement as content
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
request = HTTPRequest(
method="GET",
resource="statements"
)
request.query_params["voidedStatementId"] = statement_id
lrs_response = self._send_request(request)
if lrs_response.success:
lrs_response.content = Statement.from_json(lrs_response.data)
return lrs_response
def query_statements(self, query):
"""Query the LRS for statements with specified parameters
:param query: Dictionary of query parameters and their values
:type query: dict
:return: LRS Response object with the returned StatementsResult object as content
:rtype: :class:`tincan.lrs_response.LRSResponse`
.. note::
Optional query parameters are\n
**statementId:** (*str*) ID of the Statement to fetch
**voidedStatementId:** (*str*) ID of the voided Statement to fetch
**agent:** (*Agent* |*Group*) Filter to return Statements for which the
specified Agent or Group is the Actor
**verb:** (*Verb id IRI*) Filter to return Statements matching the verb id
**activity:** (*Activity id IRI*) Filter to return Statements for which the
specified Activity is the Object
**registration:** (*UUID*) Filter to return Statements matching the specified registration ID
**related_activities:** (*bool*) Include Statements for which the Object,
Context Activities or any Sub-Statement
properties match the specified Activity
**related_agents:** (*bool*) Include Statements for which the Actor, Object,
Authority, Instructor, Team, or any Sub-Statement properties match the specified Agent
**since:** (*datetime*) Filter to return Statements stored since the specified datetime
**until:** (*datetime*) Filter to return Statements stored at or before the specified datetime
**limit:** (*positive int*) Allow <limit> Statements to be returned. 0 indicates the
maximum supported by the LRS
**format:** (*str* {"ids"|"exact"|"canonical"}) Manipulates how the LRS handles
importing and returning the statements
**attachments:** (*bool*) If true, the LRS will use multipart responses and include
all attachment data per Statement returned.
Otherwise, application/json is used and no attachment information will be returned
**ascending:** (*bool*) If true, the LRS will return results in ascending order of
stored time (oldest first)
"""
params = {}
param_keys = [
"registration",
"since",
"until",
"limit",
"ascending",
"related_activities",
"related_agents",
"format",
"attachments",
]
for k, v in query.items():
if v is not None:
if k == "agent":
params[k] = v.to_json(self.version)
elif k == "verb" or k == "activity":
params[k] = v.id
elif k in param_keys:
params[k] = v
request = HTTPRequest(
method="GET",
resource="statements"
)
request.query_params = params
lrs_response = self._send_request(request)
if lrs_response.success:
lrs_response.content = StatementsResult.from_json(lrs_response.data)
return lrs_response
def more_statements(self, more_url):
"""Query the LRS for more statements
:param more_url: URL from a StatementsResult object used to retrieve more statements
:type more_url: str | unicode
:return: LRS Response object with the returned StatementsResult object as content
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
if isinstance(more_url, StatementsResult):
more_url = more_url.more
more_url = self.get_endpoint_server_root() + more_url
request = HTTPRequest(
method="GET",
resource=more_url
)
lrs_response = self._send_request(request)
if lrs_response.success:
lrs_response.content = StatementsResult.from_json(lrs_response.data)
return lrs_response
def retrieve_state_ids(self, activity, agent, registration=None, since=None):
"""Retrieve state id's from the LRS with the provided parameters
:param activity: Activity object of desired states
:type activity: :class:`tincan.activity.Activity`
:param agent: Agent object of desired states
:type agent: :class:`tincan.agent.Agent`
:param registration: Registration UUID of desired states
:type registration: str | unicode
:param since: Retrieve state id's since this time
:type since: str | unicode
:return: LRS Response object with the retrieved state id's as content
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
if not isinstance(activity, Activity):
activity = Activity(activity)
if not isinstance(agent, Agent):
agent = Agent(agent)
request = HTTPRequest(
method="GET",
resource="activities/state"
)
request.query_params = {
"activityId": activity.id,
"agent": agent.to_json(self.version)
}
if registration is not None:
request.query_params["registration"] = registration
if since is not None:
request.query_params["since"] = since
lrs_response = self._send_request(request)
if lrs_response.success:
lrs_response.content = json.loads(lrs_response.data)
return lrs_response
def retrieve_state(self, activity, agent, state_id, registration=None):
"""Retrieve state from LRS with the provided parameters
:param activity: Activity object of desired state
:type activity: :class:`tincan.activity.Activity`
:param agent: Agent object of desired state
:type agent: :class:`tincan.agent.Agent`
:param state_id: UUID of desired state
:type state_id: str | unicode
:param registration: registration UUID of desired state
:type registration: str | unicode
:return: LRS Response object with retrieved state document as content
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
if not isinstance(activity, Activity):
activity = Activity(activity)
if not isinstance(agent, Agent):
agent = Agent(agent)
request = HTTPRequest(
method="GET",
resource="activities/state",
ignore404=True
)
request.query_params = {
"activityId": activity.id,
"agent": agent.to_json(self.version),
"stateId": state_id
}
if registration is not None:
request.query_params["registration"] = registration
lrs_response = self._send_request(request)
if lrs_response.success:
doc = StateDocument(
id=state_id,
content=lrs_response.data,
activity=activity,
agent=agent
)
if registration is not None:
doc.registration = registration
headers = lrs_response.response.getheaders()
if "lastModified" in headers and headers["lastModified"] is not None:
doc.timestamp = headers["lastModified"]
if "contentType" in headers and headers["contentType"] is not None:
doc.content_type = headers["contentType"]
if "etag" in headers and headers["etag"] is not None:
doc.etag = headers["etag"]
lrs_response.content = doc
return lrs_response
def save_state(self, state):
"""Save a state doc to the LRS
:param state: State document to be saved
:type state: :class:`tincan.documents.state_document.StateDocument`
:return: LRS Response object with saved state as content
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
request = HTTPRequest(
method="PUT",
resource="activities/state",
content=state.content,
)
if state.content_type is not None:
request.headers["Content-Type"] = state.content_type
else:
request.headers["Content-Type"] = "application/octet-stream"
if state.etag is not None:
request.headers["If-Match"] = state.etag
request.query_params = {
"stateId": state.id,
"activityId": state.activity.id,
"agent": state.agent.to_json(self.version)
}
lrs_response = self._send_request(request)
lrs_response.content = state
return self._send_request(request)
def _delete_state(self, activity, agent, state_id=None, registration=None, etag=None):
"""Private method to delete a specified state from the LRS
:param activity: Activity object of state to be deleted
:type activity: :class:`tincan.activity.Activity`
:param agent: Agent object of state to be deleted
:type agent: :class:`tincan.agent.Agent`
:param state_id: UUID of state to be deleted
:type state_id: str | unicode
:param registration: registration UUID of state to be deleted
:type registration: str | unicode
:param etag: etag of state to be deleted
:type etag: str | unicode
:return: LRS Response object with deleted state as content
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
if not isinstance(activity, Activity):
activity = Activity(activity)
if not isinstance(agent, Agent):
agent = Agent(agent)
request = HTTPRequest(
method="DELETE",
resource="activities/state"
)
if etag is not None:
request.headers["If-Match"] = etag
request.query_params = {
"activityId": activity.id,
"agent": agent.to_json(self.version)
}
if state_id is not None:
request.query_params["stateId"] = state_id
if registration is not None:
request.query_params["registration"] = registration
lrs_response = self._send_request(request)
return lrs_response
def delete_state(self, state):
"""Delete a specified state from the LRS
:param state: State document to be deleted
:type state: :class:`tincan.documents.state_document.StateDocument`
:return: LRS Response object
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
return self._delete_state(
activity=state.activity,
agent=state.agent,
state_id=state.id,
etag=state.etag
)
def clear_state(self, activity, agent, registration=None):
"""Clear state(s) with specified activity and agent
:param activity: Activity object of state(s) to be deleted
:type activity: :class:`tincan.activity.Activity`
:param agent: Agent object of state(s) to be deleted
:type agent: :class:`tincan.agent.Agent`
:param registration: registration UUID of state(s) to be deleted
:type registration: str | unicode
:return: LRS Response object
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
return self._delete_state(
activity=activity,
agent=agent,
registration=registration
)
def retrieve_activity_profile_ids(self, activity, since=None):
"""Retrieve activity profile id(s) with the specified parameters
:param activity: Activity object of desired activity profiles
:type activity: :class:`tincan.activity.Activity`
:param since: Retrieve activity profile id's since this time
:type since: str | unicode
:return: LRS Response object with list of retrieved activity profile id's as content
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
if not isinstance(activity, Activity):
activity = Activity(activity)
request = HTTPRequest(
method="GET",
resource="activities/profile"
)
request.query_params["activityId"] = activity.id
if since is not None:
request.query_params["since"] = since
lrs_response = self._send_request(request)
if lrs_response.success:
lrs_response.content = json.loads(lrs_response.data)
return lrs_response
def retrieve_activity_profile(self, activity, profile_id):
"""Retrieve activity profile with the specified parameters
:param activity: Activity object of the desired activity profile
:type activity: :class:`tincan.activity.Activity`
:param profile_id: UUID of the desired profile
:type profile_id: str | unicode
:return: LRS Response object with an activity profile doc as content
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
if not isinstance(activity, Activity):
activity = Activity(activity)
request = HTTPRequest(
method="GET",
resource="activities/profile",
ignore404=True
)
request.query_params = {
"profileId": profile_id,
"activityId": activity.id
}
lrs_response = self._send_request(request)
if lrs_response.success:
doc = ActivityProfileDocument(
id=profile_id,
content=lrs_response.data,
activity=activity
)
headers = lrs_response.response.getheaders()
if "lastModified" in headers and headers["lastModified"] is not None:
doc.timestamp = headers["lastModified"]
if "contentType" in headers and headers["contentType"] is not None:
doc.content_type = headers["contentType"]
if "etag" in headers and headers["etag"] is not None:
doc.etag = headers["etag"]
lrs_response.content = doc
return lrs_response
def save_activity_profile(self, profile):
"""Save an activity profile doc to the LRS
:param profile: Activity profile doc to be saved
:type profile: :class:`tincan.documents.activity_profile_document.ActivityProfileDocument`
:return: LRS Response object with the saved activity profile doc as content
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
request = HTTPRequest(
method="PUT",
resource="activities/profile",
content=profile.content
)
if profile.content_type is not None:
request.headers["Content-Type"] = profile.content_type
else:
request.headers["Content-Type"] = "application/octet-stream"
if profile.etag is not None:
request.headers["If-Match"] = profile.etag
request.query_params = {
"profileId": profile.id,
"activityId": profile.activity.id
}
lrs_response = self._send_request(request)
lrs_response.content = profile
return lrs_response
def delete_activity_profile(self, profile):
"""Delete activity profile doc from LRS
:param profile: Activity profile document to be deleted
:type profile: :class:`tincan.documents.activity_profile_document.ActivityProfileDocument`
:return: LRS Response object
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
request = HTTPRequest(
method="DELETE",
resource="activities/profile"
)
request.query_params = {
"profileId": profile.id,
"activityId": profile.activity.id
}
if profile.etag is not None:
request.headers["If-Match"] = profile.etag
return self._send_request(request)
def retrieve_agent_profile_ids(self, agent, since=None):
"""Retrieve agent profile id(s) with the specified parameters
:param agent: Agent object of desired agent profiles
:type agent: :class:`tincan.agent.Agent`
:param since: Retrieve agent profile id's since this time
:type since: str | unicode
:return: LRS Response object with list of retrieved agent profile id's as content
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
if not isinstance(agent, Agent):
agent = Agent(agent)
request = HTTPRequest(
method="GET",
resource="agents/profile"
)
request.query_params["agent"] = agent.to_json(self.version)
if since is not None:
request.query_params["since"] = since
lrs_response = self._send_request(request)
if lrs_response.success:
lrs_response.content = json.loads(lrs_response.data)
return lrs_response
def retrieve_agent_profile(self, agent, profile_id):
"""Retrieve agent profile with the specified parameters
:param agent: Agent object of the desired agent profile
:type agent: :class:`tincan.agent.Agent`
:param profile_id: UUID of the desired agent profile
:type profile_id: str | unicode
:return: LRS Response object with an agent profile doc as content
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
if not isinstance(agent, Agent):
agent = Agent(agent)
request = HTTPRequest(
method="GET",
resource="agents/profile",
ignore404=True
)
request.query_params = {
"profileId": profile_id,
"agent": agent.to_json(self.version)
}
lrs_response = self._send_request(request)
if lrs_response.success:
doc = AgentProfileDocument(
id=profile_id,
content=lrs_response.data,
agent=agent
)
headers = lrs_response.response.getheaders()
if "lastModified" in headers and headers["lastModified"] is not None:
doc.timestamp = headers["lastModified"]
if "contentType" in headers and headers["contentType"] is not None:
doc.content_type = headers["contentType"]
if "etag" in headers and headers["etag"] is not None:
doc.etag = headers["etag"]
lrs_response.content = doc
return lrs_response
def save_agent_profile(self, profile):
"""Save an agent profile doc to the LRS
:param profile: Agent profile doc to be saved
:type profile: :class:`tincan.documents.agent_profile_document.AgentProfileDocument`
:return: LRS Response object with the saved agent profile doc as content
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
request = HTTPRequest(
method="PUT",
resource="agents/profile",
content=profile.content,
)
if profile.content_type is not None:
request.headers["Content-Type"] = profile.content_type
else:
request.headers["Content-Type"] = "application/octet-stream"
if profile.etag is not None:
request.headers["If-Match"] = profile.etag
request.query_params = {
"profileId": profile.id,
"agent": profile.agent.to_json(self.version)
}
lrs_response = self._send_request(request)
lrs_response.content = profile
return lrs_response
def delete_agent_profile(self, profile):
"""Delete agent profile doc from LRS
:param profile: Agent profile document to be deleted
:type profile: :class:`tincan.documents.agent_profile_document.AgentProfileDocument`
:return: LRS Response object
:rtype: :class:`tincan.lrs_response.LRSResponse`
"""
request = HTTPRequest(
method="DELETE",
resource="agents/profile"
)
request.query_params = {
"profileId": profile.id,
"agent": profile.agent.to_json(self.version)
}
if profile.etag is not None:
request.headers["If-Match"] = profile.etag
return self._send_request(request)
@property
def endpoint(self):
"""The endpoint of the Remote LRS
:setter: Tries to convert to unicode. Appends a "/" if necessary. Prepends http:// if necessary.
:setter type: str | unicode
:rtype: unicode
"""
return self._endpoint
@endpoint.setter
def endpoint(self, value):
if value is not None:
if not isinstance(value, str):
value = str(value)
if not value.endswith("/"):
value += "/"
if not value.startswith("http"):
value = "http://" + value
self._endpoint = value
@property
def timeout(self):
"""The timeout to use when connecting to the Remote LRS
:setter type: float
:rtype: float
"""
return self._timeout
@timeout.setter
def timeout(self, value):
if value:
if not isinstance(value, float):
value = float(value)
if value < 0:
raise ValueError("Timeout must be positive number", value)
self._timeout = value
@property
def version(self):
"""Version being used for remote LRS communication
:setter: Tries to convert to unicode. Must be a supported
version. Setting to None defaults to the latest version.
:setter type: str | unicode
:rtype: unicode
"""
return self._version
@version.setter
def version(self, value):
if value is not None:
if not isinstance(value, str):
str(value)
if value not in Version.supported:
raise Exception("Unsupported Version")
else:
value = Version.latest
self._version = value
@property
def auth(self):
"""Authority being used for remote LRS communication
:setter: Tries to convert to unicode.
:setter type: str | unicode
:rtype: unicode
"""
return self._auth
@auth.setter
def auth(self, value):
if value is not None and not isinstance(value, str):
str(value)
self._auth = value
def get_endpoint_server_root(self):
"""Parses RemoteLRS object's endpoint and returns its root
:return: Root of the RemoteLRS object endpoint
:rtype: unicode
"""
parsed = urlparse(self._endpoint)
root = parsed.scheme + "://" + parsed.hostname
if parsed.port is not None:
root += ":" + str(parsed.port)
return root