-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathApiExplorer.scala
More file actions
1934 lines (1602 loc) · 90.2 KB
/
ApiExplorer.scala
File metadata and controls
1934 lines (1602 loc) · 90.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package code.snippet
import code.lib.ObpAPI._
import code.lib.ObpJson._
import code.lib.{ObpAPI, ObpGet, _}
import code.util.Helper
import code.util.Helper.{MdcLoggable, covertObpOperationIdToWebpageId}
import net.liftweb.json
import net.liftweb.util.{CssSel, Html5}
import java.net.URL
import net.liftweb.http.js.JE.JsRaw
import net.liftweb.http.js.JsExp
import scala.collection.immutable.{List, Nil}
import net.liftweb.http.{S, SHtml}
import net.liftweb.json.JsonAST.JValue
import net.liftweb.json.{Extraction, JsonParser}
import scala.xml.{NodeSeq, Text}
// for compact render
import code.lib.ObpAPI.{allBanks, getEntitlementRequestsV300, getEntitlementsV300,
getGlossaryItemsJson, getMessageDocsJson,
getAllResourceDocsJson,
getOneBankLevelResourceDocsJson,
getStaticAndAllBankLevelDynamicResourceDocs,
isLoggedIn}
import net.liftweb.common._
import net.liftweb.http.CurrentReq
import net.liftweb.http.SHtml.{ajaxSelect, text}
import net.liftweb.http.js.JsCmd
import net.liftweb.http.js.JsCmds.{Run, SetHtml}
import net.liftweb.json.Serialization.writePretty
import net.liftweb.json._
import net.liftweb.util.Helpers._
// see https://simply.liftweb.net/index-7.10.html on css selectors
/*
Present a list of OBP resource URLs
*/
class ApiExplorer extends MdcLoggable {
/*
WIP to add comments on resource docs. This code copied from Sofit.
val commentDateFormat = new SimpleDateFormat("kk:mm:ss EEE MMM dd yyyy")
val NOOP_SELECTOR = "#i_am_an_id_that_should_never_exist" #> ""
val user = MinimalUserJsonV300(
user_id = "Asdf",
username = "simonredfern",
provider = "google.com"
)
def showComments = {
val commentJsons = List(
ResourceDocCommentJsonV300(
id = Some("123"),
text = Some("abc"),
user = Some(user),
date = Some(now),
reply_to_id = None)
)
def showComments(comments: List[ResourceDocCommentJsonV300]) = {
def orderByDateDescending =
(comment1: ResourceDocCommentJsonV300, comment2: ResourceDocCommentJsonV300) =>
comment1.date.getOrElse(now).before(comment2.date.getOrElse(now))
".commentsContainer" #> {
"#noComments" #> "" &
".comment" #> comments.sortWith(orderByDateDescending).zipWithIndex.map {
case (commentJson, position) => commentCssSel(commentJson, position + 1)
}
}
}
}
def commentCssSel(commentJson: ResourceDocCommentJsonV300, displayPosition : Int) = {
def commentDate: CssSel = {
commentJson.date.map(d => {
".commentDate *" #> commentDateFormat.format(d)
}) getOrElse
".commentDate" #> ""
}
def userInfo: CssSel = {
commentJson.user.map(u => {
".userInfo *" #> {
" -- " + u.username
}
}) getOrElse
".userInfo" #> ""
}
".text *" #> commentJson.text.getOrElse("") &
".commentLink * " #> { "#" + displayPosition } &
".commentLink [id]" #> displayPosition &
commentDate &
userInfo
}
*/
// In case we use Extraction.decompose
implicit val formats = net.liftweb.json.DefaultFormats
// Get entitlements for the logged in user
def getEntitlementsForCurrentUser: List[Entitlement] = getEntitlementsV300 match {
case Full(x) => x.list.map(i => Entitlement(entitlementId = i.entitlement_id, roleName = i.role_name, bankId = i.bank_id))
case _ => List()
}
def getUserEntitlementRequests: List[UserEntitlementRequests] = {
val result = getEntitlementRequestsV300 match {
case Full(x) => x.entitlement_requests.map(i => UserEntitlementRequests(
entitlementRequestId = i.entitlement_request_id,
roleName = i.role_name,
bankId = i.bank_id,
username = i.user.username)
)
case _ => List()
}
logger.debug(s"getUserEntitlementRequests will return: $result" )
result
}
val listAllBanks = S.param("list-all-banks").getOrElse("false").toBoolean
logger.info(s"all_banks in url param is $listAllBanks")
val currentGitCommit = gitCommit
logger.info(s"currentGitCommit $currentGitCommit")
val currentOperationId = S.param("operation_id").getOrElse("OBPv3_1_0-config")
val presetBankId = S.param("bank_id").getOrElse("")
logger.info(s"bank_id in url param is $presetBankId")
val presetAccountId = S.param("account_id").getOrElse("")
logger.info(s"account_id in url param is $presetAccountId")
val presetViewId = S.param("view_id").getOrElse("")
logger.info(s"account_id in url param is $presetViewId")
val presetCounterpartyId = S.param("counterparty_id").getOrElse("")
logger.info(s"counterparty_id in url param is $presetCounterpartyId")
val presetTransactionId = S.param("transaction_id").getOrElse("")
logger.info(s"transaction_id in url param is $presetTransactionId")
val presetConnector = S.param("connector").getOrElse("rabbitmq_vOct2024")
logger.info(s"connector in url param is $presetConnector")
val queryString = S.queryString
def stringToOptBoolean (x: String) : Option[Boolean] = x.toLowerCase match {
case "true" | "yes" | "1" | "-1" => Some(true)
case "false" | "no" | "0" => Some(false)
case _ => Empty
}
/** native is a query parameter to filter endpoints by implementedBy
* Used to list newly implemented or updated functionality
* native = true means only show endpoints that are implemented in the version we are calling.
* native = false means only show endpoints that are not implemented in the version we are calling
* native = None means ignore this filter, show everything in the version.
*/
val nativeParam: Option[Boolean] = for {
x <- S.param("native")
y <- stringToOptBoolean(x)
} yield y
logger.info(s"nativeParam is $nativeParam")
def apiCollectionIdParam = S.param(ApiCollectionId)
logger.info(s"apiCollectionIdParam is $apiCollectionIdParam")
val rawTagsParam = S.param("tags")
logger.info(s"rawTagsParam is $rawTagsParam")
val localeParam = S.param("locale")
logger.info(s"localeParam is $localeParam")
def apiCollectionIdParamString = if (apiCollectionIdParam.isEmpty) "" else "&api-collection-id=" + apiCollectionIdParam.mkString(",")
logger.info(s"apiCollectionIdParamString is $apiCollectionIdParamString")
val tagsParamString = if (rawTagsParam.isEmpty) "" else "&tags=" + rawTagsParam.mkString(",")
logger.info(s"tagsParamString is $rawTagsParam")
val localeParamString = if (localeParam.isEmpty) "" else "&locale=" + localeParam.mkString(",")
logger.info(s"localeParamString is $localeParamString")
val rawContentParam = S.param("content")
logger.info(s"contentParam is $rawContentParam")
val contentParamString = if (rawContentParam.isEmpty) "" else "&content=" + rawContentParam.mkString(",")
logger.info(s"contentParamString is $contentParamString")
val tagsParam: Option[List[String]] = rawTagsParam match {
// if tags= is supplied in the url we want to ignore it
case Full("") => None
case _ => {
for {
x <- rawTagsParam
y <- Some(x.trim().split(",").toList)
} yield {
y
}
}
}
logger.info(s"tags are $tagsParam")
def apiCollectionId : String = apiCollectionIdParam match {
case Full(x) => x
case _ => ""
}
val tagsHeadline : String = tagsParam match {
case Some(x) if (x.length == 1) => "filtered by tag: " + x.mkString(", ")
case Some(x) if (x.length > 1)=> s"filtered by tags: ${x.head} ..."
case _ => ""
}
val contentHeadline : String = rawContentParam match {
case Full(x) => x
case _ => ""
}
val implementedHereHeadline : String = nativeParam match {
case Some(true) => "(those added or modified in this version)"
case Some(false) => "(those inherited from previous versions)"
case _ => ""
}
def stringToNodeSeq(html : String) : NodeSeq = {
// Note! scala.xml.XML.loadString fails to parse "--" (double hyphen)
val newHtmlString = tryo {scala.xml.XML.loadString("<div>" + html + "</div>").toString()} match {
case Full(htmlString) =>
htmlString
case _ =>
logger.error(s"stringToNodeSeq says: I cannot parse the following html plus div with scala.xml.XML.loadString:" )
logger.error(html)
""
}
//Note: `parse` method: We much enclose the div, otherwise only the first element is returned.
Html5.parse(newHtmlString) match {
case Full(parsedHtml) =>
parsedHtml
case _ =>
logger.error("stringToNodeSeq says: I cannot Html5.parse the following html:")
logger.error(newHtmlString)
NodeSeq.Empty
}
}
def modifiedRequestUrl(url: String, baseVersionUrl: String, presetBankId: String, presetAccountId: String) = {
//For OBP, only use there bits, eg: v3.1.0, but for PolishAPI it used four bits: v2.1.1.1
val versionPattern = "v([0-9].[0-9].[0-9].[0-9])".r
val versionInUrl = (versionPattern findFirstIn url).getOrElse(baseVersionUrl)
// replace the version in URL, the user will see it change when they click the version.
// Only need to modify the first version in the url.
val url1: String = url.replaceFirst(versionInUrl, baseVersionUrl)
// Potentially replace BANK_ID
val url2: String = presetBankId match {
case "" => url1
case _ => url1.replaceAll("BANK_ID", presetBankId)
}
// Potentially replace ACCOUNT_ID
val url3: String = presetAccountId match {
case "" => url2
case _ => url2.replaceAll("/ACCOUNT_ID", s"/$presetAccountId") // so we don't change OTHER_ACCOUNT_ID
}
// Potentially replace VIEW_ID
val url4: String = presetViewId match {
case "" => url3
case _ => url3.replaceAll("VIEW_ID", presetViewId)
}
// Potentially replace OTHER_ACCOUNT_ID
val url5: String = presetCounterpartyId match {
case "" => url4
case _ => url4.replaceAll("OTHER_ACCOUNT_ID", presetCounterpartyId).replaceAll("COUNTERPARTY_ID",presetCounterpartyId)
}
// Potentially replace TRANSACTION_ID
val url6: String = presetTransactionId match {
case "" => url5
case _ => url5.replaceAll("TRANSACTION_ID", presetTransactionId)
}
url6
}
//val myPrivateAccounts = privateAccountsCache
case class BankId(val value : String) {
override def toString = value
}
object BankId {
def unapply(id : String) = Some(BankId(id))
}
// Get a list of BankIds that are relevant to the logged in user i.e. banks where the user has at least one non public account
val myBankIds: List[BankId] = for {
allAccountsJson <- if(isLoggedIn) ObpAPI.privateAccounts.toList else List() //No need call api for anonymous user.
barebonesAccountJson <- allAccountsJson.accounts.toList.flatten
bankId <- barebonesAccountJson.bank_id
} yield BankId(bankId)
val defaultVersion: String = Helper.getPropsValue("default.version") match {
case Full(v) => v
case _ => OBPVersionV510
}
// Get the requested version from the url parameter and default if none
val apiVersionRequested = S.param("version").getOrElse(defaultVersion)
// Possible OBP Versions
val obpVersionsSupported = List(OBPVersionV400, OBPVersionV500)
val otherVersionsSupported = List(BGVersionV13, UKVersionV31)
// This is basically all versions supported
val allSupportedVersionsInDropdownMenu = List(
"OBPv1.2.1",
"OBPv1.3.0",
"OBPv1.4.0",
"OBPv2.0.0",
"OBPv2.1.0",
"OBPv2.2.0",
"OBPv3.0.0",
"OBPv3.1.0",
OBPVersionV400,
OBPVersionV500,
OBPVersionV510,
UKVersionV31,
BGVersionV13,
STETv14,
PAPIVersionV2111,
AUv100,
BahrainOBFVersionV100,
"0.6v1",
CNBV9v100
)
// Set the version to use.
val apiVersion: String = {
if (obpVersionsSupported.contains(apiVersionRequested)
|| otherVersionsSupported.contains(apiVersionRequested)
|| allSupportedVersionsInDropdownMenu.contains(apiVersionRequested)) { // Prefix with v (for OBP versions because they come just with number from API Explorer)
// Note: We want to get rid of this "v" prefix ASAP.s
s"$apiVersionRequested"
} else {
S.notice(s"Note: Requested version $apiVersionRequested is not currently supported. Set to v$defaultVersion")
s"$defaultVersion"
}
}
val apiVersionParamString = "&version=" + apiVersion
logger.info(s"apiVersionParamString is $apiVersionParamString")
val isObpVersion: Boolean = {
obpVersionsSupported.contains(apiVersionRequested)
}
logger.info(s"apiVersion is: $apiVersion")
// To link to API home page (this is duplicated in OAuthClient)
val baseUrl = Helper.getPropsValue("api_hostname", S.hostName)
//
val apiPortalHostname = Helper.getPropsValue("api_portal_hostname", baseUrl)
/**
* https://demo.openbankproject.com/
* https://demo-manager.openbankproject.com/
*
* Here is the example for api_manager, will generate the url from api_host, just added the `-manager` to the first part.
*
*/
private val hostParts: Array[String] = baseUrl.split("\\.")
private val defaultApiManagerUrl = (Array(hostParts.head+"-manager")++ hostParts.drop(1)).mkString(".")
val apiManagerUrl = Helper.getPropsValue("api_manager_url", defaultApiManagerUrl)
val apiCreationAndManagementTags = Helper.getPropsValue("api_creation_and_management_tags",
"API,Dynamic-Entity-Manage,Dynamic-Swagger-Doc-Manage,Dynamic-Resource-Doc-Manage,Aggregate-Metrics," +
"Metric,Documentation,Method-Routing,Dynamic-Message-Doc-Manage,Api-Collection," +
"Connector-Method,JSON-Schema-Validation,Authentication-Type-Validation,Dynamic-Entity-Manage,Endpoint-Mapping-Manage")
val userManagementTags = Helper.getPropsValue("user_management_tags", "User,Role,Entitlement," +
"Consent,Onboarding")
val obpBankingModelTags = Helper.getPropsValue("obp_banking_model_tags", "Bank,Account,Transaction," +
"FX,Customer-Message,Product-Collection,Product,ATM,Branch,Card,Person,User,Customer," +
"" +
"KYC,Counterparty,Transaction-Metadata,Transaction,Account-Access,Transaction-Request")
// Use to show the developer the current base version url
val baseVersionUrl = s"${OAuthClient.currentApiBaseUrl}"
// Link to the API endpoint for the resource docs json TODO change apiVersion so it doesn't have a "v" prefix
val resourceDocsPath = s"${OAuthClient.currentApiBaseUrl}/obp/v1.4.0/resource-docs/${apiVersion.stripPrefix("v")}/obp?${tagsParamString}${localeParamString}${contentParamString}"
// Link to the API endpoint for the swagger json
val swaggerPath = s"${OAuthClient.currentApiBaseUrl}/obp/v1.4.0/resource-docs/${apiVersion.stripPrefix("v")}/swagger?${tagsParamString}${localeParamString}${contentParamString}"
val chineseVersionPath = "?locale=zh_CN"
val allPartialFunctions = s"/partial-functions.html?${apiVersionParamString}${tagsParamString}${localeParamString}${contentParamString}"
//Note > this method is only for partial-functions.html .
def showPartialFunctions = {
// Get a list of resource docs from the API server
// This will throw an exception if resource_docs key is not populated
// Convert the json representation to ResourceDoc (pretty much a one to one mapping)
// The overview contains html. Just need to convert it to a NodeSeq so the template will render it as such
val allResources: List[ResourceDocJson] = for {
rs <- getAllResourceDocsJson(apiVersion).openOrThrowException("Resource docs can not be empty here!")
} yield rs
// The list generated here might be used by an administrator as a white or black list of API calls for the API itself.
val commaSeparatedListOfResources = allResources.map(_.operation_id).mkString("[", ", ", "]")
"#all-partial-functions" #> commaSeparatedListOfResources
}
def wrapLocaleParameter (url: String) = {
val localeString = S.locale.toString
// Note the Props value might contain a query parameter e.g. ?psd2=true
// hack (we should use url operators instead) so we can add further query parameters if one is already included in the the baseUrl
url.contains("?") match {
case true => url + s"&locale=$localeString" // ? found so add & instead
case false => url + s"?locale=$localeString" // ? not found so add it.
}
}
def getResponse (url : String, resourceVerb: String, json : JValue, customRequestHeader: String = "") : (String, String, String) = {
// version is now included in the url
val urlWithVersion = s"$url"
val urlWithVersionAndLocale = wrapLocaleParameter(urlWithVersion)
val requestHeader = customRequestHeader.trim.isEmpty match {
case true => Nil
case false =>
customRequestHeader.split(":::").map(_.trim).map {
i =>
val key = i.split("::").toList.head
val value = i.split("::").toList.reverse.head
Header(key, value)
}.toList
}
var headersOfCurrentCall: List[String] = Nil
var requestHeadersOfCurrentCall: List[String] = Nil
val responseBodyBox = {
resourceVerb match {
case "GET" =>
val x = ObpGetWithHeader(urlWithVersionAndLocale, requestHeader)
headersOfCurrentCall = x._2
requestHeadersOfCurrentCall = x._3
x._1
case "HEAD" =>
val x = ObpHeadWithHeader(urlWithVersionAndLocale, requestHeader)
headersOfCurrentCall = x._2
requestHeadersOfCurrentCall = x._3
x._1
case "DELETE" =>
val x = ObpDeleteWithHeader(urlWithVersionAndLocale, requestHeader)
headersOfCurrentCall = x._2
requestHeadersOfCurrentCall = x._3
x._1
case "POST" =>
val x = ObpPostWithHeader(urlWithVersionAndLocale, json, requestHeader)
headersOfCurrentCall = x._2
requestHeadersOfCurrentCall = x._3
x._1
case "PUT" =>
val x = ObpPutWithHeader(urlWithVersionAndLocale, json, requestHeader)
headersOfCurrentCall = x._2
requestHeadersOfCurrentCall = x._3
x._1
case _ => {
val failMsg = s"API Explorer says: Unsupported resourceVerb: $resourceVerb. Url requested was: $url"
logger.warn(failMsg)
Failure(failMsg)
}
}
}
logger.trace(s"responseBodyBox is ${responseBodyBox}")
// Handle the contents of the Box
val responseBody =
responseBodyBox match {
case Full(JNothing) => "" // If httpmethod is `HEAD`, the response maybe JNothing here.
case Full(json) => writePretty(json)
case Empty => "Empty: API did not return anything"
case Failure(message, _, _) => message
}
logger.trace(s"responseBody is $responseBody")
(responseBody, headersOfCurrentCall.mkString("\n"), requestHeadersOfCurrentCall.mkString("\n"))
}
// disabled button
// enabled button if no response after 28 seconds, http2 protocol ideal timeout is 30 seconds
def disabledBtn(name: String): JsCmd = {
val jsCode = s"""
|var timestamp = new Date().getTime();
|var btn = jQuery('input[name=$name]');
|setTimeout(function(){
| btn.prop('lastClickTime', timestamp).prop('disabled', true);
|}, 0);
|setTimeout(function() {
| if(btn.prop('lastClickTime') === timestamp){
| btn.removeAttr('disabled');
| }
|}, 28*1000)
|""".stripMargin.replaceAll("""[\r\n\s]+""", " ")
Run (jsCode)
}
def copyResultTextToClipboard(body: String): JsCmd = {
val encodedJsString = body.encJs
val stringWithoutQuotes = encodedJsString.substring(1, encodedJsString.length - 1)
Run(JsRaw(s"navigator.clipboard.writeText('${stringWithoutQuotes}')").toJsCmd)
}
val entitlementsForCurrentUser = getEntitlementsForCurrentUser
logger.info(s"there are ${entitlementsForCurrentUser.length} entitlementsForCurrentUser(s)")
val canReadResourceRole: Option[Entitlement] = entitlementsForCurrentUser.find(_.roleName=="CanReadResourceDoc")
val canReadGlossaryRole: Option[Entitlement] = entitlementsForCurrentUser.find(_.roleName=="CanReadGlossary")
val userEntitlementRequests = getUserEntitlementRequests
val canReadResourceRequest = userEntitlementRequests.find(_.roleName=="CanReadResourceDoc")
val canReadGlossaryRequest = userEntitlementRequests.find(_.roleName=="CanReadGlossary")
logger.info(s"there are ${userEntitlementRequests.length} userEntitlementRequests(s)")
val canReadResourceDocRoleInfo = List(RoleInfo(
role ="CanReadResourceDoc",
requiresBankId = false,
userHasEntitlement = canReadResourceRole.isDefined,
userHasEntitlementRequest = canReadResourceRequest.isDefined
))
val canReadGlossaryRoleInfo = List(RoleInfo(
role ="CanReadGlossary",
requiresBankId = false,
userHasEntitlement = canReadGlossaryRole.isDefined,
userHasEntitlementRequest = canReadGlossaryRequest.isDefined
))
var entitlementRequestStatus = ""
// This value is used to pre populate the form for Entitlement Request.
// It maybe be changed by the user in the form.
var rolesBankId = presetBankId
var RolesResourceId = ""
var entitlementRequestRoleName = ""
var resourceId = ""
var requestVerb = ""
var requestUrl = ""
var requestCustomHeader = ""
var requestBody = "{}"
var responseBody = "{}"
var errorResponseBodies = List("")
var isFavourites = "false"
//Note: OperationIdFromWebpage = OBPv4_0_0-getBanks
//But operationIdForOBP => OBPv4.0.0-getBanks (Javascript do not support '.' there.)
//We must do the converting properly for this two ids.
var favouritesOperationIdFromWebpage = ""
var favouritesApiCollectionId = ""
def processEntitlementRequest(name: String): JsCmd = {
logger.debug(s"processEntitlementRequest entitlementRequestStatus is $entitlementRequestStatus rolesBankId is $rolesBankId")
logger.debug(s"processEntitlementRequest says resourceId is $resourceId")
val entitlementRequestResponseStatusId = s"roles__entitlement_request_response_${RolesResourceId}_${entitlementRequestRoleName}"
logger.debug(s"id to set is: $entitlementRequestResponseStatusId")
val apiUrl = OAuthClient.currentApiBaseUrl
val entitlementRequestsUrl = "/obp/v3.0.0/entitlement-requests"
val createEntitlementRequest = CreateEntitlementRequestJSON(bank_id = rolesBankId, role_name = entitlementRequestRoleName)
// Convert case class to JValue
implicit val formats = DefaultFormats
val entitlementRequestJValue: JValue = Extraction.decompose(createEntitlementRequest)
// TODO: Put this in ObpAPI.scala
val response : String = getResponse(entitlementRequestsUrl, "POST", entitlementRequestJValue)._1
val result: String =
try {
// parse the string we get back from the API into a JValue
val json : JValue = parse(response)
// Convert to case class
val entitlementRequest: EntitlementRequestJson = json.extract[EntitlementRequestJson]
s"Entitlement Request with Id ${entitlementRequest.entitlement_request_id} was created. It will be reviewed shortly."
}
catch {
case _ => {
logger.info("")
s"The API Explorer could not create an Entitlement Request: $response"
}
}
// call url and put the response into the appropriate result div
// SetHtml accepts an id and value
SetHtml(entitlementRequestResponseStatusId, Text(result))
// enable button
val jsEnabledBtn = s"jQuery('input[name=$name]').removeAttr('disabled')"
Run (jsEnabledBtn)
}
def showResources: CssSel = {
logger.debug("before showResources:")
val getRootResponse = ObpAPI.getRoot
val mySpaces = getMySpaces
def resourceDocsRequiresRole = getRootResponse.flatMap(_.extractOpt[APIInfoJson400].map(_.resource_docs_requires_role)).openOr(false)
val spaceBankId = S.param("space_bank_id").getOrElse("")
// Get a list of resource docs from the API server
// This will throw an exception if resource_docs key is not populated
// Convert the json representation to ResourceDoc (pretty much a one to one mapping)
// The overview contains html. Just need to convert it to a NodeSeq so the template will render it as such
val allResourcesBox = if (resourceDocsRequiresRole && !spaceBankId.isEmpty) //If resourceDocsRequiresRole == true && spaceBankId is there, we only return one bank level dynamic resource docs
getOneBankLevelResourceDocsJson(apiVersion, spaceBankId)
else if( resourceDocsRequiresRole && spaceBankId.isEmpty)//If resourceDocsRequiresRole == true && spaceBankId empty, we will return all static + all the banks dynamic resource docs
getStaticAndAllBankLevelDynamicResourceDocs(apiVersion)
else // other case, we will return
getAllResourceDocsJson(apiVersion)
//Here need to change to Nil, if we throw exception here, we can not render the other parts of the home page.
val allResourcesList = allResourcesBox.getOrElse(Nil)
val allResources = for {
r <- allResourcesList
} yield ResourceDocPlus(
id = covertObpOperationIdToWebpageId(r.operation_id),
operationId = r.operation_id,
verb = r.request_verb,
url = modifiedRequestUrl(
r.specified_url, // We used to use the request_url - but we want to use the specified url i.e. the later version.
apiVersion
.replaceAll(UKVersionV20, "v2.0")
.replaceAll(UKVersionV31, "v3.1")
.replaceAll(BGVersionV133, VersionV133)
.replaceAll(BGVersionV1, "v1")
.replaceAll(BGVersionV13, "v1.3")
.replaceAll(BahrainOBFVersionV100, "v1.0.0")
.replaceAll(PAPIVersionV2111, "v2.1.1.1")
.replaceAll("OBPv", ""),
presetBankId,
presetAccountId
),
summary = r.summary,
description = stringToNodeSeq(r.description),
exampleRequestBody = r.example_request_body,
successResponseBody = r.success_response_body,
errorResponseBodies = r.error_response_bodies,
connectorMethods = r.connector_methods,
implementedBy = ImplementedBy(r.implemented_by.version, r.implemented_by.function),
tags = r.tags,
roleInfos = r.roles.map(i => RoleInfo(role = i.role,
requiresBankId = i.requires_bank_id,
userHasEntitlement = {
val result: Boolean = isLoggedIn match {
case true =>
{
val rolesFound = entitlementsForCurrentUser.map(_.roleName)
//logger.debug(s"rolesFound are $rolesFound")
// We only want to consider the user has the role if the role does not require bank id
// Otherwise users would find it difficult to request same role for different banks.
rolesFound.contains(i.role) && ! i.requires_bank_id
}
case _ => false
}
//logger.debug(s"userHasEntitlement will return: $result")
result
},
userHasEntitlementRequest = {
val result: Boolean = isLoggedIn match {
case true =>
{
val requestedRolesFound = userEntitlementRequests.map(_.roleName)
//logger.debug(s"requestedRolesFound are $requestedRolesFound")
// We only want to consider the user has requested the role if the role does not require bank id
// Otherwise users would find it difficult to request same role for different banks.
requestedRolesFound.contains(i.role) && ! i.requires_bank_id
}
case _ => false
}
//logger.debug(s"userHasEntitlementRequest will return: $result")
result
}
)),
isFeatured = r.is_featured,
specialInstructions = stringToNodeSeq(r.special_instructions)
)
val filteredResources5: List[ResourceDocPlus] = nativeParam match {
case Some(true) => {
for {
r <- allResources
// apiVersion currently has an extra v which should be removed.
if (r.implementedBy.version == apiVersion.stripPrefix("v")) // only show endpoints which have been implemented in this version.
} yield {
r
}
}
case Some(false) => {
for {
r <- allResources
// TODO apiVersion for OBP currently has an extra v which should be removed.
if (r.implementedBy.version != apiVersion.stripPrefix("v")) // the opposite case
} yield {
r
}
}
case _ => allResources // No preference (default) just return everything.
}
val resourcesToUse = filteredResources5.toSet.toList
logger.debug(s"allResources count is ${allResources.length}")
logger.debug(s"resourcesToUse count is ${resourcesToUse.length}")
if (allResources.length > 0 && resourcesToUse.length == 0) {
logger.info("tags filter reduced the list of resource docs to zero")
}
// Sort by the first and second tags (if any) then the summary.
// In order to help sorting, the first tag in a call should be most general, then more specific etc.
val resources = resourcesToUse.sortBy(r => {
val firstTag = r.tags.headOption.getOrElse("")
val secondTag = r.tags.take(1).toString()
(firstTag, secondTag, r.summary.toString)
})
//this can be empty list, if there is no operationIds there.
val webpageOperationIds = ObpAPI.getApiCollectionEndpointsById(apiCollectionId).map(_.api_collection_endpoints.map(_.operation_id)).openOr(List()).map(covertObpOperationIdToWebpageId)
val myWebpageOperationIds = ObpAPI.getApiCollectionEndpoints("Favourites").map(_.api_collection_endpoints.map(_.operation_id)).openOr(List()).map(covertObpOperationIdToWebpageId)
// Group resources by the first tag
val unsortedGroupedResources: Map[String, List[ResourceDocPlus]] = resources.groupBy(_.tags.headOr("ToTag"))
// Sort the groups by the Tag. Note in the rendering we sort the resources by summary.
val groupedResources = unsortedGroupedResources.toSeq.sortBy{ kv =>
val tagName = kv._1
// if tag name starts with blank character, replace blank with _, to let it order to the tail.
tagName.replaceFirst("^\\s", "_")
}
// Featured /////
val featuredResources = resources.filter(r => r.isFeatured == true)
// Group resources by the first tag
val unsortedFeaturedGroupedResources: Map[String, List[ResourceDocPlus]] = featuredResources.groupBy(_.tags.headOr("ToTag"))
// Sort the groups by the Tag. Note in the rendering we sort the resources by summary.
val groupedFeaturedResources = unsortedFeaturedGroupedResources.toSeq.sortBy(_._1)
/////////////////
// Title / Headline we display including count of APIs
val headline : String = s"""
${apiVersionRequested.stripPrefix("OBP").stripPrefix("BG").stripPrefix("STET").stripPrefix("UK")}
$tagsHeadline $contentHeadline $implementedHereHeadline (${resources.length} APIs)
""".trim()
logger.info (s"showingMessage is: $headline")
// Used to show / hide the Views selector
// TODO disable instead of hiding
val displayViews = "block"
//Only show the collections when the user logged In
val displayCollectionsDiv = if (isLoggedIn) {
"block"
} else {
"none"
}
val displayFeatured = if (featuredResources.length > 0 ) {
logger.info("show featured")
"block"
} else {
logger.info("not show featured")
"none"
}
val showIndexObpApiManagementLink = Helper.getPropsValue("webui_show_index_obp_api_management_link", "true").toBoolean
val showIndexApiManagerLink= Helper.getPropsValue("webui_show_index_api_manager_link", "true").toBoolean
val showIndexObpUserManagementLink = Helper.getPropsValue("webui_show_index_obp_user_management_link", "true").toBoolean
val showIndexAllObpLink = Helper.getPropsValue("webui_show_index_obp_all_link", "true").toBoolean
val showIndexDynamicLink = Helper.getPropsValue("webui_show_index_dynamic_link", "true").toBoolean
val showIndexMoreLink = Helper.getPropsValue("webui_show_index_more_link", "true").toBoolean
val showIndexSpaceLink = Helper.getPropsValue("webui_show_index_space_link", "true").toBoolean
val showIndexBerlinGroupLink = Helper.getPropsValue("webui_show_index_berlin_group_link", "false").toBoolean
val showIndexUkLink = Helper.getPropsValue("webui_show_index_uk_link", "false").toBoolean
val consentFlowLink = Helper.getPropsValue("consent_flow_link", "")
val displayIndexObpApiManagementLink = if (showIndexObpApiManagementLink ) {""} else {"none"}
val displayIndexApiManagerLink = if (showIndexApiManagerLink ) {""} else {"none"}
val displayIndexObpUserManagementLink = if (showIndexObpUserManagementLink ) {""} else {"none"}
val displayIndexAllObpLink = if (showIndexAllObpLink ) {""} else {"none"}
val displayIndexDynamicLink = if (showIndexDynamicLink ) {""} else {"none"}
val displayIndexMoreLink = if (showIndexMoreLink ) {""} else {"none"}
val displayIndexSpaceLink = if (showIndexSpaceLink ) {""} else {"none"}
val displayIndexBerlinGroupLink = if (showIndexBerlinGroupLink ) {""} else {"none"}
val displayIndexUkLink = if (showIndexUkLink ) {""} else {"none"}
val displayConsentFlowLink = if (consentFlowLink.nonEmpty ) {""} else {"none"}
// Do we want to show the Request Entitlement button.
// Should also consider if User has submitted an entitlement request or already has the role.
val displayRequestEntitlementButton = if (isLoggedIn) {
logger.info("show Request Entitlement button")
"block"
} else {
logger.info("not show Request Entitlement button")
"none"
}
// Controls when we display the request body.
def displayRequestBody(resourceVerb : String) = {
resourceVerb match {
case "POST" => "block"
case "PUT" => "block"
case "PATCH" => "block"
case _ => "none"
}
}
//TODO, need error handling:
val myApicollections: List[ApiCollectionJson400] = ObpAPI.getMyApiCollections.map(_.api_collections).getOrElse(List.empty[ApiCollectionJson400])
def process(name: String): JsCmd = {
// The DIVS in the DOM have underscores in their names.
resourceId = resourceId.replace(".","_")
logger.info(s"requestUrl is $requestUrl")
logger.info(s"requestCustomHeader is $requestCustomHeader")
logger.info(s"resourceId is $resourceId")
logger.debug(s"requestBody is $requestBody")
logger.debug(s"responseBody is $responseBody")
logger.debug(s"errorResponseBodies is $errorResponseBodies")
// Create json object from input string
val jsonObject = JsonParser.parse(requestBody)
val jsonResponseObject = JsonParser.parse(responseBody)
val jsonErrorResponse = errorResponseBodies
// the id of the element we want to populate and format.
val resultTarget = "result_" + resourceId
val boxTarget = "result_box_" + resourceId
// This will highlight the json. Replace the $ sign after we've constructed the string
val jsCommandHighlightResult : String = s"DOLLAR_SIGN('#$boxTarget').fadeIn();DOLLAR_SIGN('#$resultTarget').each(function(i, block) { hljs.highlightBlock(block);});".replace("DOLLAR_SIGN","$")
val jsEnabledSubmitBtn = s"jQuery('input[name=$name]').removeAttr('disabled')"
val rolesTarget = "roles_" + resourceId
val rolesboxTarget = "roles_box_" + resourceId
//val jsCommandHighlightRolesResult : String = s"DOLLAR_SIGN('#$rolesboxTarget').fadeIn();DOLLAR_SIGN('#$rolesTarget').each(function(i, block) { hljs.highlightBlock(block);});".replace("DOLLAR_SIGN","$")
//jsCommandHighlightRolesResult.contains("afsf")
// The id of the possible error responses box we want to hide after calling the API
val possibleErrorResponsesBoxTarget = "possible_error_responses_box_" + resourceId
// The id of the possible error responses box we want to hide after calling the API
val connectorMethodsBoxTarget = "connector_methods_box_" + resourceId
// The id of the roles responses box we want to hide after calling the API
val requestRolesResponsesBoxTarget = "required_roles_response_box_" + resourceId
// The javascript to hide it.
val jsCommandHidePossibleErrorResponsesBox : String = s"DOLLAR_SIGN('#$possibleErrorResponsesBoxTarget').fadeOut();".replace("DOLLAR_SIGN","$")
val jsCommandHideConnectorMethodsBoxTarget : String = s"DOLLAR_SIGN('#$connectorMethodsBoxTarget').show();".replace("DOLLAR_SIGN","$")
val jsCommandHideRequestRolesResponsesBox : String = s"DOLLAR_SIGN('#$requestRolesResponsesBoxTarget').fadeOut();".replace("DOLLAR_SIGN","$")
// The id of the possible error responses box we want to hide after calling the API
val typicalSuccessResponseBoxTarget = "typical_success_response_box_" + resourceId
// The javascript to hide it.
val jsCommandHideTypicalSuccessResponseBox : String = s"DOLLAR_SIGN('#$typicalSuccessResponseBoxTarget').fadeOut();".replace("DOLLAR_SIGN","$")
// The id of the full path
val fullPathTarget = "full_path_" + resourceId
val fullHeadersBox= "full_headers_box_"+resourceId
val fullHeadersTarget = "full_headers_" + resourceId
val fullRequestHeadersBox= "full_request_headers_box_"+ resourceId
val fullRequestHeadersTarget = "full_request_headers_" + resourceId
// The javascript to show it
val jsCommandShowFullPath : String = s"DOLLAR_SIGN('#$fullPathTarget').fadeIn();".replace("DOLLAR_SIGN","$")
val jsCommandShowFullHeaders : String =
s"DOLLAR_SIGN('#$fullHeadersBox').show();".replace("DOLLAR_SIGN","$") ++s"DOLLAR_SIGN('#$fullHeadersTarget').fadeIn();".replace("DOLLAR_SIGN","$")
val jsCommandShowFullRequestHeaders : String =
s"DOLLAR_SIGN('#$fullRequestHeadersBox').show();".replace("DOLLAR_SIGN","$") ++s"DOLLAR_SIGN('#$fullRequestHeadersTarget').fadeIn();".replace("DOLLAR_SIGN","$")
// alert('$fullPathTarget');
//logger.info(s"jsCommand is $jsCommand")
//logger.info(s"jsCommand2 is $jsCommandHidePossibleErrorResponsesBox")
/////////////
// TODO It would be nice to modify getResponse and underlying functions to return more information about the request including full path
// For now we duplicate the construction of the fullPath
val apiUrl = OAuthClient.currentApiBaseUrl
val urlWithVersion =
if (tagsParamString.equalsIgnoreCase("PSD2") == Some(true)) {
s"$requestUrl".split("\\?").toList match {
case url :: params :: Nil =>
url + params + "&format=ISO20022"
case url :: Nil =>
url + "?format=ISO20022"
case _ =>
s"$requestUrl"
}
} else {
s"$requestUrl"