-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCode.lua
More file actions
961 lines (721 loc) · 31.8 KB
/
Code.lua
File metadata and controls
961 lines (721 loc) · 31.8 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
--[[
JsonParser.lua
Usage:
The function ParseJSON (jsonString) accepts a
string representation of a JSON object or array
and returns the object or array as a Lua table
with the same structure. Individual properties
can be referenced using either the dot notation
or the array notation.
Notes:
All null values in the original JSON stream will
be stored in the output table as JsonParser.NIL.
This is a necessary convention, because Lua
tables cannot store nil values and it may be
desirable to have a stored null value versus
not having the key present.
Requires:
Newtonsoft.Json
--]]
luanet.load_assembly("System")
luanet.load_assembly("Newtonsoft.Json")
luanet.load_assembly("log4net")
JsonParser = {}
JsonParser.__index = JsonParser
JsonParser.NIL = {}
JsonParser.Types = {}
JsonParser.Types["StringReader"] = luanet.import_type("System.IO.StringReader")
JsonParser.Types["JsonToken"] = luanet.import_type("Newtonsoft.Json.JsonToken")
JsonParser.Types["JsonTextReader"] = luanet.import_type("Newtonsoft.Json.JsonTextReader")
JsonParser.rootLogger = "AtlasSystems.Addons.SierraServerAddon"
JsonParser.Log = luanet.import_type("log4net.LogManager").GetLogger(JsonParser.rootLogger)
function JsonParser:ParseJSON (jsonString)
--[[
Parses an input JSON string and outputs a
lua table representation of the contained
JSON data. JSON properties that contain
null will be represented as JsonParser.NIL.
Supports nested objects and arrays.
]]
local stringReader = JsonParser.Types["StringReader"](jsonString)
local reader = JsonParser.Types["JsonTextReader"](stringReader)
local outputTable = ""
if (reader:Read()) then
if (reader.TokenType == JsonParser.Types["JsonToken"].StartObject) then
outputTable = JsonParser:BuildFromJsonObject(reader)
elseif (reader.TokenType == JsonParser.Types["JsonToken"].StartArray) then
outputTable = JsonParser:BuildFromJsonArray(reader)
elseif (jsonString == nil) then
outputTable = ""
else
outputTable = jsonString
end
end
return outputTable
end
function JsonParser:BuildFromJsonObject (reader)
--[[
Uses the provided JsonTextReader to build a lua table
from a JSON object. Not meant to be called from outside
this module.
]]
local array = {}
while (reader:Read()) do
if (reader.TokenType == JsonParser.Types["JsonToken"].EndObject) then
return array
end
if (reader.TokenType == JsonParser.Types["JsonToken"].PropertyName) then
local propertyName = reader.Value
if (reader:Read()) then
if (reader.TokenType == JsonParser.Types["JsonToken"].StartObject) then
array[propertyName] = JsonParser:BuildFromJsonObject(reader)
elseif (reader.TokenType == JsonParser.Types["JsonToken"].StartArray) then
array[propertyName] = JsonParser:BuildFromJsonArray(reader)
elseif (reader.Value == nil) then
array[propertyName] = JsonParser.NIL
else
array[propertyName] = reader.Value
end
end
end
end
return array
end
function JsonParser:BuildFromJsonArray (reader)
--[[
Uses the provided JsonTextReader to build a lua table
from a JSON array. Not meant to be called from outside
this module.
]]
local array = {}
while (reader:Read()) do
if (reader.TokenType == JsonParser.Types["JsonToken"].EndArray) then
return array
elseif (reader.TokenType == JsonParser.Types["JsonToken"].StartArray) then
table.insert(array, JsonParser:BuildFromJsonArray(reader))
elseif (reader.TokenType == JsonParser.Types["JsonToken"].StartObject) then
table.insert(array, JsonParser:BuildFromJsonObject(reader))
elseif (reader.Value == nil) then
table.insert(array, JsonParser.NIL)
else
table.insert(array, reader.Value)
end
end
return array
end
--[[
Utilities
Usage:
This section contains useful functions for
the rest of the solution
]]
Utility = {}
Utility.__index = Utility
function Utility.Trim(s)
return (s:gsub("^%s*(.-)%s*$", "%1"));
end
--[[
SierraApi.lua
Usage:
This file contains the SierraApi class,
which contains methods related to interacting
with the Sierra V3 API.
Requires:
Requires the Atlas Systems functionality: JsonParser.lua
]]
luanet.load_assembly("System")
luanet.load_assembly("log4net")
SierraApi = {}
SierraApi.__index = SierraApi
SierraApi.Types = {}
SierraApi.Types["Convert"] = luanet.import_type("System.Convert")
SierraApi.Types["Encoding"] = luanet.import_type("System.Text.Encoding")
SierraApi.Types["WebClient"] = luanet.import_type("System.Net.WebClient")
SierraApi.Types["NameValueCollection"] = luanet.import_type("System.Collections.Specialized.NameValueCollection")
SierraApi.Types["System.Type"] = luanet.import_type("System.Type")
SierraApi.Types["StreamReader"] = luanet.import_type("System.IO.StreamReader");
SierraApi.Types["System.Type"] = luanet.import_type("System.Type");
SierraApi.Types["System.Array"] = luanet.import_type("System.Array");
SierraApi.Types["System.Reflection.Assembly"] = luanet.import_type("System.Reflection.Assembly");
local Base64Converter = SierraApi.Types["System.Reflection.Assembly"].LoadFile(AddonInfo.Directory .. "\\Base64Converter.dll"):GetType("Base64Converter.Base64Converter");
SierraApi.UrlSuffixes = {}
SierraApi.UrlSuffixes.Token = "/token"
SierraApi.UrlSuffixes.ItemsQueryItemFields = "?fields=default,fixedFields,varFields"
SierraApi.UrlSuffixes.ItemsBibIds = "/items?bibIds=%s&fields=default,fixedFields,varFields"
SierraApi.ApiEndpoints = {
--[[
Enumeration for determining
the API that was used when
formatting error messages.
API endpoints that are not
yet needed have not been
added.
]]
info = 0,
items = 1,
itemsQuery = 2
}
SierraApi.rootLogger = "AtlasSystems.Addons.SierraServerAddon"
SierraApi.Log = luanet.import_type("log4net.LogManager").GetLogger(SierraApi.rootLogger)
function SierraApi:Create(apiUrl, userAgent)
--[[
Initializes a SierraApi object.
]]
if (not type(apiUrl) == "string") or apiUrl == "" then
error({ Message = "Cannot initialize Sierra API web client without an API URL." })
end
SierraApi.Log:DebugFormat("Initializing SierraApi Client with URL: {0}", apiUrl)
local sierraApi = {}
setmetatable(sierraApi, SierraApi)
-- Strips off the last / if one is present
if (string.sub(apiUrl, -1) == "/") then
apiUrl = string.sub(apiUrl, 1, -2)
end
sierraApi.ApiUrl = apiUrl
sierraApi.AccessToken = ""
sierraApi.UserAgent = userAgent or false
return sierraApi
end
function SierraApi:UpdateAccessToken(clientKey, clientSecret)
--[[
Retrieves and stores the access_token
under self.AccessToken. Also returns
the access_token.
]]
local accessToken = self:GetAccessToken(clientKey, clientSecret)
SierraApi.Log:DebugFormat("Updated Access Token: {0}", accessToken)
self.AccessToken = accessToken
return accessToken
end
function SierraApi:GetAccessToken (clientKey, clientSecret)
--[[
Returns only the access_token from the
/token API response.
]]
return self:GetAccessTokenResponse(clientKey, clientSecret).access_token
end
function SierraApi:GetAccessTokenResponse (clientKey, clientSecret)
--[[
Parses the JSON response from the Sierra
/token API and returns the response as a
Lua table.
Output:
{
access_token = <string>,
token_type = <string>,
expires_in = <int>
}
]]
if (not type(clientKey) == "string") or clientKey == "" then
error({ Message = "Client Key must be a non-empty string." })
elseif (not type(clientSecret) == "string") or clientSecret == "" then
error({ Message = "Client Secret must be a non-empty string." })
end
SierraApi.Log:Info("Getting Client Credentials")
local credentialWebClient = SierraApi.Types["WebClient"]()
local encodedKeyAndSecret = SierraApi:Base64Encode(
string.format("%s:%s", clientKey, clientSecret)
)
local authTokenUrl = self.ApiUrl .. SierraApi.UrlSuffixes.Token
local uploadMethod = "POST"
local uploadBody = "grant_type=client_credentials"
credentialWebClient.Headers:Clear()
credentialWebClient.Headers:Add("Authorization", "Basic " .. encodedKeyAndSecret)
credentialWebClient.Headers:Add("Content-Type", "application/x-www-form-urlencoded")
local authUploadSuccess, authUploadResult = pcall(function()
SierraApi.Log:DebugFormat("Encoded Client Key and Secret: {0}", encodedKeyAndSecret)
SierraApi.Log:DebugFormat("Posting to URL: {0}", authTokenUrl)
return credentialWebClient:UploadString(authTokenUrl, uploadMethod, uploadBody)
end)
credentialWebClient:Dispose();
if (not authUploadSuccess) then
SierraApi.Log:Warn("Failure occurred while obtaining access token.")
error(authUploadResult)
else
SierraApi.Log:DebugFormat("Access Token Response: {0}", authUploadResult)
end
local parsedAuthResult = JsonParser:ParseJSON(authUploadResult)
if parsedAuthResult.code and not parsedAuthResult.access_token then
local message = "Bad authorization result returned from Sierra authorization."
SierraApi.Log:Warn(message)
if parsedAuthResult.name then
SierraApi.Log:WarnFormat("Auth Response Name: {0}", parsedAuthResult.name)
message = message .. string.format(" (Name: %s)", parsedAuthResult.name)
end
if parsedAuthResult.description then
SierraApi.Log:WarnFormat("Auth Response Desc: {0}", parsedAuthResult.description)
message = message .. string.format(" (Description: %s)", parsedAuthResult.description)
end
error({ Code = parsedAuthResult.code or -1, Message = message })
end
return parsedAuthResult
end
function SierraApi:GetItems (bibId, volume, exact)
--[[
Uses Sierra's /items API to get all of
the items that match the specified bibId
and volume.
Requires a bibId.
exact is a boolean value that will determine whether
or not to match the string exactly.
Note:
This method will check each item that was
returned for the specified bibId to see if
that item has a volume and if the volume is
1) a substring of the given volume if exact
is false to support sites that have volume
information concatenated with other information,
or 2) an exact trimmed string.
]]
if (not type(bibId) == "string") or bibId == "" then
error({ Message = "bibId must be a non-empty string" });
end
SierraApi.Log:Info("Getting Items using Sierra Items API")
SierraApi.Log:DebugFormat("Item bibId : \"{0}\"", bibId)
SierraApi.Log:DebugFormat("Item volume: \"{0}\"", volume)
local queryUrl = self.ApiUrl .. string.format(SierraApi.UrlSuffixes.ItemsBibIds, bibId)
SierraApi.Log:DebugFormat("Getting item data using API url: {0}", queryUrl)
local webClient = self:BuildItemsWebClient();
local querySucceeded, queryResult = pcall(function()
return webClient:DownloadString(queryUrl)
end)
webClient:Dispose();
local matchingItems = {};
if not querySucceeded then
SierraApi.Log:ErrorFormat("Unsuccessful Items API call using url: {0}", queryUrl);
local errorMessage = SierraApi:HandleUploadError(queryResult);
SierraApi.Log:Debug(errorMessage);
else
SierraApi.Log:DebugFormat("Sierra Items API Response: {0}", queryResult)
local parsedResult = JsonParser:ParseJSON(queryResult)
for i_entry, v_entry in ipairs(parsedResult.entries or {}) do
-- i_entry == index
-- v_entry == value
local entryId = v_entry.id or ""
local v_volume = SierraApi:GetVarFieldValue(v_entry, "v")
if v_volume and v_volume ~= "" and volume and volume ~= "" then
if exact then
if Utility.Trim(volume) == Utility.Trim(v_volume) then
SierraApi.Log:DebugFormat("Sierra item record \"{0}\" matches specified bibId and volume (exact).", entryId);
table.insert(matchingItems, v_entry)
end
else
if string.find(volume, v_volume, 1, true) then
SierraApi.Log:DebugFormat("Sierra item record \"{0}\" matches specified bibId and volume (substring).", entryId);
table.insert(matchingItems, v_entry)
end
end
elseif (not volume or volume == "") and (not v_volume or v_volume == "") then
SierraApi.Log:DebugFormat("Sierra item record \"{0}\" matches specified bibId.", entryId);
table.insert(matchingItems, v_entry);
end
end
end
return matchingItems;
end
function SierraApi:GetVarFieldValue (itemRecord, varField, subField)
--[[
Gets the value of a particular varField
from a particular item record. Can grab
the varField's subField if a subField tag
is supplied and is present in the item
record.
subField is not required.
Returns single values.
Returns nil if no content is found for the
supplied query information.
]]
if not type(varField) == "string" then
error({ Message = "varField argument must be a string" })
elseif not itemRecord then
error({ Message = "Sierra item record cannot be nil or false" })
elseif not itemRecord.varFields then
error({ Message = "Sierra item record does not contain varFields" })
end
local itemRecordId = itemRecord.id or ""
for i_vf, v_varField in ipairs(itemRecord.varFields or {}) do
if v_varField and v_varField.fieldTag == varField then
if subField and subField ~= "" then
for i_sf, v_subField in ipairs(v_varField.subFields or {}) do
if v_subField and v_subField.tag == subField then
if v_subField.content then
local content = v_subField.content
SierraApi.Log:DebugFormat(
"Sierra item record \"{0}\" varField \"{1}\" subField \"{2}\" contains \"{3}\".",
itemRecordId, varField, subField, content)
return content
else
SierraApi.Log:WarnFormat(
"Sierra item record \"{0}\" varField \"{1}\" subField \"{2}\" has no \"content\" property.",
itemRecordId, varField, subField)
return nil
end
end
end
SierraApi.Log:WarnFormat(
"Sierra item record \"{0}\" varField \"{1}\" has no subFields with tag \"{2}\".",
itemRecordId, varField, subField)
return nil
end
if v_varField.content then
local content = v_varField.content
SierraApi.Log:DebugFormat(
"Sierra item record \"{0}\" varField \"{1}\" contains \"{2}\".",
itemRecordId, varField, content)
return content
else
SierraApi.Log:WarnFormat(
"Sierra item record \"{0}\" varField \"{1}\" has no \"content\" property.",
itemRecordId, varField)
return nil
end
end
end
SierraApi.Log:DebugFormat(
"Sierra item record \"{0}\" does not contain varField \"{1}\"",
itemRecordId, varField)
return nil
end
function SierraApi:GetVarFieldMarcData (itemRecord, varField)
--[[
Gets the marcTag, ind1, and ind2 values from
a varField, if available. Returns the results
as a table:
{
marcTag = "100",
ind1 = "1",
ind2 = " "
}
If a value is not available, the output table
will store nil as the value, which will cause
the key to not be present in the output.
If the varField cannot be found, nil will be
returned instead of a table.
]]
if not type(varField) == "string" then
error({ Message = "varField argument must be a string" })
elseif not itemRecord then
error({ Message = "Item record cannot be nil or false." })
elseif not itemRecord.varFields then
error({ Message = "Item record does not contain varFields" })
end
local itemRecordId = itemRecord.id or ""
for i_vf, v_varField in ipairs(itemRecord.varFields or {}) do
if v_varField and v_varField.fieldTag == varField then
SierraApi.Log:DebugFormat(
"Found varField \"{0}\" for item record \"{1}\". Returning its MARC data.",
varField, itemRecordId)
return {
marcTag = v_varField.marcTag,
ind1 = v_varField.ind1,
ind2 = v_varField.ind2
}
end
end
SierraApi.Log:DebugFormat(
"Could not find varField \"{0}\" under item record \"{1}\".",
varField, itemRecordId)
return nil
end
function SierraApi:GetFixedField (itemRecord, fixedField)
--[[
Gets a particular fixedField from a particular item
record. Returns nil if no matching fixedField is
found for the specified fixedField identifier.
Fixed fields contain a few properties, so the
output will be returned as a table. Below is
an example of the output data format. The
display property is not always available.
{
label = "LANG",
value = "eng",
display = "English"
}
]]
if not type(fixedField) == "string" then
error({ Message = "fixedField argument must be a string" })
elseif not itemRecord then
error({ Message = "Item record argument must be initialized" })
elseif not itemRecord.fixedFields then
error({ Message = "Item record does not contain fixedFields" })
end
if not itemRecord.fixedFields[fixedField] then
SierraApi.Log:WarnFormat(
"Item Record \"{0}\" does not contain fixedField \"{1}\"",
itemRecord.id,
fixedField)
return nil
end
return itemRecord.fixedFields[fixedField]
end
function SierraApi:BuildItemsWebClient ()
--[[
Builds a WebClient that has headers which are needed
for the items API of the Sierra API.
]]
if not (type(self.AccessToken) == "string") or self.AccessToken == "" then
error({ Message = "Cannot create Sierra API Web Client. Access token is blank." })
end
local webClient = SierraApi.Types["WebClient"]()
webClient.Headers:Clear()
webClient.Headers:Add("Authorization", "Bearer " .. self.AccessToken)
if self.UserAgent and self.UserAgent ~= "" then
webClient.Headers:Add("User-Agent", self.UserAgent)
end
return webClient
end
function SierraApi:HandleUploadError(returnedError)
local message = "";
if returnedError and returnedError.Message then
message = returnedError.Message;
if (returnedError.InnerException) then
message = message .. "\r\n" .. self:HandleUploadError(returnedError.InnerException);
if returnedError.InnerException.Response and returnedError.InnerException.Response ~= "Response" then
-- This is necessary to get the response body from exceptions thrown by WebClients.
local streamReader = SierraApi.Types["StreamReader"](returnedError.InnerException.Response:GetResponseStream());
local responseContent = streamReader:ReadToEnd();
local response = JsonParser:ParseJSON(tostring(responseContent));
message = message .. "\r\nDetails: " .. (response["httpStatus"] or "") .. " - " .. (response["code"] or "") .. " - " .. (response["name"] or "") .. " - " .. (response["description"] or "");
end
end
elseif returnedError then
message = returnedError;
end
return message;
end
function SierraApi:Base64Encode (plainText)
--[[
Encodes the input text in base64.
]]
if not type(plainText) == "string" then
error({ Message = "plainText argument must be a string." });
end
-- Due to the NLua Byte array bug, this code doesn't work in Aeon 5.2. We do the conversion in a .NET assembly instead.
-- local textUTF8 = SierraApi.Types["Encoding"].UTF8:GetBytes(plainText)
-- local textBase64 = SierraApi.Types["Convert"].ToBase64String(textUTF8)
-- Arguments passed to Invoke must be in an object array.
local objectArray = SierraApi.Types["System.Array"].CreateInstance(SierraApi.Types["System.Type"].GetType("System.Object"), 1);
objectArray[0] = plainText;
--[[
StringToBase64 is the following C# method:
public static string StringToBase64(string input)
{
byte[] bytes = Encoding.UTF8.GetBytes(input);
return Convert.ToBase64String(bytes);
}
]]
local textBase64 = Base64Converter:GetMethod("StringToBase64"):Invoke(nil, objectArray);
return textBase64;
end
function SierraApi:IsType (o, t)
--[[
Determines if the specified object "o" is of
.NET type "t". t should be a string of the full
name of the .NET type, such as "System.DateTime"
]]
if ((o and type(o) == "userdata") and (t and type(t) == "string")) then
local comparisonType = SierraApi.Types["System.Type"].GetType(t)
SierraApi.Log:Debug(o:GetType().FullName)
if (comparisonType) then
-- The comparison type was successfully loaded so we can do a check
-- that the object can be assigned to the comparison type.
return comparisonType:IsAssignableFrom(o:GetType()), true
else
-- The comparison type was could not be loaded so we can only check
-- based on the names of the types.
return (o:GetType().FullName == t), false
end
end
return false, false
end
-- =========================================================
-- Load settings and .NET Assemblies
-- =========================================================
local Settings = {}
Settings.RequestMonitorQueue = GetSetting("RequestMonitorQueue")
Settings.SuccessRouteQueue = GetSetting("SuccessRouteQueue")
Settings.ErrorRouteQueue = GetSetting("ErrorRouteQueue")
Settings.SierraApiUrl = GetSetting("SierraApiUrl")
Settings.ClientKey = GetSetting("ClientKey")
Settings.ClientSecret = GetSetting("ClientSecret")
Settings.UserAgent = GetSetting("UserAgent")
Settings.BibIdSourceField = GetSetting("BibIdSourceField")
Settings.VolumeSourceField = GetSetting("VolumeSourceField")
Settings.CleanUpVolumeSourceField = GetSetting("CleanUpVolumeSourceField")
Settings.VolumeDestinationField = GetSetting("VolumeDestinationField")
Settings.BarcodeDestinationField = GetSetting("BarcodeDestinationField")
Settings.VolumeSourceFieldRegularExpression = GetSetting("VolumeSourceFieldRegularExpression")
Settings.ExactSearch = GetSetting("ExactSearch")
Settings.ReplaceVolumeWhenNotNull = GetSetting("ReplaceVolumeWhenNotNull")
luanet.load_assembly("System")
luanet.load_assembly("log4net")
luanet.load_assembly("Mscorlib")
local Types = {}
Types["System.Type"] = luanet.import_type("System.Type")
Types["WebClient"] = luanet.import_type("System.Net.WebClient")
Types["StreamReader"] = luanet.import_type("System.IO.StreamReader")
Types["NameValueCollection"] = luanet.import_type("System.Collections.Specialized.NameValueCollection")
Types["Encoding"] = luanet.import_type("System.Text.Encoding")
Types["LogManager"] = luanet.import_type("log4net.LogManager")
Types["Regex"] = luanet.import_type("System.Text.RegularExpressions.Regex")
-- =========================================================
-- Main
-- =========================================================
local isCurrentlyProcessing = false
local sierraApi = nil
local Log = Types["LogManager"].GetLogger(JsonParser.rootLogger)
function Init ()
RegisterSystemEventHandler("SystemTimerElapsed", "TimerElapsed")
end
function TimerElapsed (eventArgs)
--[[
Function that is called whenever the
system manager triggers server addon
execution.
]]
if (not isCurrentlyProcessing) then
isCurrentlyProcessing = true
Log:Debug("Addon Settings: ")
for settingKey, settingValue in pairs(Settings) do
Log:DebugFormat("{0}: {1}", settingKey, settingValue)
end
local successfulAddonExecution, error = pcall(function()
local successfulAddonExecution, error = pcall(function()
if not sierraApi then
sierraApi = SierraApi:Create(Settings.SierraApiUrl)
end
local accessToken = sierraApi:UpdateAccessToken(Settings.ClientKey, Settings.ClientSecret)
Log:DebugFormat("Generated Access Token: {0}", accessToken)
ProcessDataContexts("TransactionStatus", Settings.RequestMonitorQueue, "HandleRequests")
end)
if not successfulAddonExecution then
SierraApi:HandleUploadError(error)
end
end)
if not successfulAddonExecution then
Log:Error("Unsuccessful addon execution.")
Log:Error(error.Message or error)
end
isCurrentlyProcessing = false
else
Log:Debug("Addon is still executing.")
end
end
-- =========================================================
-- ProcessDataContext functionality
-- =========================================================
function HandleRequests ()
--[[
Must be called from a ProcessDataContexts function.
Runs for every transaction that meets the criteria specified
by the ProcessDataContexts function.
]]
local tn = GetFieldValue("Transaction", "TransactionNumber")
Log:DebugFormat("Found transaction number {0} in \"{1}\"", tn, Settings.RequestMonitorQueue)
local regex
if Settings.VolumeSourceFieldRegularExpressionn and Settings.VolumeSourceFieldRegularExpression ~= "" then
regex = Types["Regex"](Settings.VolumeSourceFieldRegularExpression)
Log:DebugFormat("Found Regex \"{0}\" for VolumeSourceField.", Settings.VolumeSourceFieldRegularExpression)
else
Log:Debug("No Regex found.")
end
local success, result = pcall(
function()
local fieldFetchSuccess, transactionBibId, transactionVolume = pcall(
function()
Log:DebugFormat("Getting BibID from transaction.{0}", Settings.BibIdSourceField)
local transactionBibId = GetFieldValue("Transaction", Settings.BibIdSourceField)
transactionBibId = transactionBibId:gsub("%D", "")
local transactionVolume
if regex ~= nil then
match = regex:Match(GetFieldValue("Transaction", Settings.VolumeSourceField))
if match.Success then
Log:DebugFormat("Using Regex for volume source field {0} results in match \"{1}\"",
Settings.VolumeSourceField, match.Value)
transactionVolume = match.Value
end
else
Log:DebugFormat("Getting volume source field {0}", Settings.VolumeSourceField)
transactionVolume = GetFieldValue("Transaction", Settings.VolumeSourceField)
end
return transactionBibId, transactionVolume
end
)
if not(fieldFetchSuccess) then
Log:ErrorFormat("Error fetching BibID and Volume fields from Transaction {0}.", tn)
error({ Message = "Error fetching BibID and Volume fields from the Transactions table." })
end
Log:DebugFormat("BibID : {0}", transactionBibId)
Log:DebugFormat("Volume: {0}", transactionVolume)
Log:Info("Searching for Sierra records.")
local sierraRecords = sierraApi:GetItems(transactionBibId, transactionVolume, Settings.ExactSearch)
if #sierraRecords <= 0 then
error({ Message = "No Sierra records were returned for the specified bibId and volume" })
elseif #sierraRecords > 1 then
error({ Message = "Too many Sierra records were returned for the specified bibId and volume" })
end
local _, sierraRecord = next(sierraRecords, nil)
local sierraRecordVolume = SierraApi:GetVarFieldValue(sierraRecord, "v")
if Settings.CleanUpVolumeSourceField then
local volStartIndex, volEndIndex =
transactionVolume:find(sierraRecordVolume, 1, true)
local nextTransactionVol =
transactionVolume:sub(1, volStartIndex - 1) ..
transactionVolume:sub(volEndIndex + 1)
Log:DebugFormat(
"Cleaning up VolumeSourceField. (Before: \"{0}\") (After: \"{1}\")",
transactionVolume,
nextTransactionVol)
SetFieldValue("Transaction", Settings.VolumeSourceField, nextTransactionVol);
SaveDataSource("Transaction")
end
if Settings.VolumeDestinationField and Settings.VolumeDestinationField ~= "" then
local currentVolumeDestinationField = GetFieldValue("Transaction", Settings.VolumeDestinationField)
if (Settings.ReplaceVolumeWhenNotNull or (not currentVolumeDestinationField) or currentVolumeDestinationField == "") then
Log:Debug("Populating volume destination field")
SetFieldValue("Transaction", Settings.VolumeDestinationField, sierraRecordVolume)
SaveDataSource("Transaction")
end
end
if Settings.BarcodeDestinationField and Settings.BarcodeDestinationField ~= "" then
Log:Debug("Populating barcode destination field")
if (not type(sierraRecord.barcode) == "string") or sierraRecord.barcode == "" then
error({ Message = "Cannot populate barcode from Sierra. Barcode is either missing or blank." })
end
SetFieldValue("Transaction", Settings.BarcodeDestinationField, sierraRecord.barcode)
SaveDataSource("Transaction")
end
return nil
end
)
if success then
Log:InfoFormat("Addon successfully populated Transaction {0} with data from Sierra", tn)
ExecuteCommand("Route", { tn, Settings.SuccessRouteQueue })
else
Log:ErrorFormat("Failed to populate transaction {0} with data from Sierra. Routing transaction to \"{1}\".", tn, Settings.ErrorRouteQueue)
Log:Error(result.Message or result)
ExecuteCommand("AddNote", { tn, result.Message or result })
ExecuteCommand("Route", { tn, Settings.ErrorRouteQueue })
end
end
function TraverseError(err)
if not err.GetType then
-- Not a .NET type
return nil;
else
if not err.Message then
-- Not a .NET exception
Log:Info(tostring(err));
return nil;
end
end
Log:Debug(err.Message);
if err.InnerException then
return TraverseError(err.InnerException);
else
return err.Message;
end
end
function OnError(err)
TraverseError(err);
end