-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathApplication.scala
More file actions
1147 lines (1094 loc) · 40.1 KB
/
Application.scala
File metadata and controls
1147 lines (1094 loc) · 40.1 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 controllers
import javax.inject.*
import java.security.MessageDigest
import org.apache.pekko.actor.typed.scaladsl.adapter.*
import org.apache.pekko.actor.typed.{ActorRef, ActorSystem}
import controllers.ApplicationData.AuthAction
import csw.services.icd.db.*
import csw.services.icd.github.IcdGitManager
import icd.web.shared.SharedUtils.Credentials
import icd.web.shared.*
import org.eclipse.jgit.api.errors.TransportException
import org.webjars.play.*
import play.api.libs.json.Json
import play.api.mvc.Cookie.SameSite.Strict
import play.filters.csrf.{CSRF, CSRFAddToken}
import play.api.mvc.*
import play.api.{Configuration, Environment, Mode}
import org.apache.pekko.actor.typed.scaladsl.AskPattern.*
import org.apache.pekko.util.Timeout
import icd.web.shared.IcdModels.{IcdModel, ServicePath}
import csw.services.icd.deleteDirectoryRecursively
import java.net.URLDecoder
import scala.collection.mutable
import scala.concurrent.duration.*
import scala.concurrent.{Await, Future}
import scala.util.{Failure, Success, Try}
import java.io.File
import java.nio.file.Files
/**
* Provides the interface between the web client and the server
*/
//noinspection TypeAnnotation,DuplicatedCode,ScalaUnusedSymbol
@Singleton
class Application @Inject() (
actorSystem: org.apache.pekko.actor.ActorSystem,
// myExecutionContext: MyExecutionContext,
env: Environment,
addToken: CSRFAddToken,
assets: AssetsFinder,
webJarsUtil: WebJarsUtil,
components: ControllerComponents,
configuration: Configuration,
authAction: AuthAction
) extends AbstractController(components) {
import ApplicationData.*
import JsonSupport.*
import ApplicationActor.*
implicit val timeout: Timeout = Timeout(1000.seconds)
implicit val typedActorSystem: ActorSystem[Nothing] = actorSystem.toTyped
import actorSystem.*
if (!tryDb.isSuccess) {
println("Error: Failed to connect to the icd database. Make sure mongod is running.")
System.exit(1)
}
private val db: IcdDb = tryDb.get
private val icdGitManager = IcdGitManager(db.versionManager)
// The expected SHA of username:password from application.conf
private val expectedSha = configuration.get[String](cookieName)
// Use an actor to manage concurrent access to cached data
private val appActor: ActorRef[ApplicationActor.Messages] = {
val behavior = ApplicationActor.create(db)
actorSystem.spawn(behavior, "app-actor")
}
// Somehow disabling the CSRF filter in application.conf and adding it here was needed to make this work
// (The CSRF token is needed for the file upload dialog in the client)
def index =
addToken(Action { implicit request =>
implicit val environment: Environment = env
val token = Csrf(CSRF.getToken.get.value)
val debug = env.mode == Mode.Dev
Ok(views.html.index(debug, assets, token, webJarsUtil))
})
// Server side of the upload ICD feature.
// Supported file types: A directory containing icd model files (and supported resources)
def uploadFiles(): Action[MultipartFormData[play.api.libs.Files.TemporaryFile]] =
Action(parse.multipartFormData) { implicit request =>
val files = request.body.files.toList
// Save uploaded files to a temp dir
val tempDir = Files.createTempDirectory("icd").toFile
files.foreach { filePart =>
val newFile = new File(tempDir, filePart.filename)
if (!newFile.getParentFile.exists()) newFile.getParentFile.mkdirs()
filePart.ref.copyTo(newFile)
}
val problems = db.ingestAndCleanup(tempDir)
deleteDirectoryRecursively(tempDir)
if (problems.exists(_.severity == "error")) {
NotAcceptable(Json.toJson(problems))
} else {
// Upload publishes a new "upload" version of the API, so need to update the cached list of versions
Await.ready(appActor ? UpdateAfterPublish.apply, 60.seconds)
Ok(Json.toJson(problems))
}
}
/**
* Gets a list of top level subsystem names
*/
def subsystemNames =
Action.async {
val resp: Future[List[String]] = appActor ? GetSubsystemNames.apply
resp.map(names => Ok(Json.toJson(names)))
}
/**
* Gets information about a named subsystem
*/
def subsystemInfo(subsystem: String, maybeVersion: Option[String], maybeComponent: Option[String]) =
authAction.async {
val resp: Future[Option[SubsystemInfo]] = appActor ? (GetSubsystemInfo(subsystem, maybeVersion, maybeComponent, _))
resp.map {
case Some(info) => Ok(Json.toJson(info))
case None => NotFound
}
}
/**
* Gets a list of components belonging to the given version of the given subsystem
*/
def components(subsystem: String, maybeVersion: Option[String]) =
authAction.async {
val resp: Future[List[String]] = appActor ? (GetComponents(subsystem, maybeVersion, _))
resp.map(names => Ok(Json.toJson(names)))
}
/**
* Query the database for information about the subsystem's components
*
* @param subsystem the subsystem
* @param maybeVersion the subsystem's version (default: current)
* @param maybeComponent component name (default all in subsystem)
* @param searchAll if true, search all components for API dependencies
* @param clientApi if true, include subscribed events, sent commands
*/
def componentInfo(
subsystem: String,
maybeVersion: Option[String],
maybeComponent: Option[String],
searchAll: Option[Boolean],
clientApi: Option[Boolean]
) =
authAction.async {
val resp: Future[List[ComponentInfo]] =
appActor ? (GetComponentInfo(subsystem, maybeVersion, maybeComponent, searchAll, clientApi, _))
resp.map(info => Ok(Json.toJson(info)))
}
// /**
// * Query the database for all of the published system events, ordered by subsystem/component
// */
// def eventList() =
// authAction.async {
// val resp: Future[List[AllEventList.EventsForSubsystem]] =
// appActor ? GetEventList
// resp.map(info => Ok(Json.toJson(info)))
// }
/**
* Query the database for information about the given components in an ICD
*
* @param subsystem the source subsystem
* @param maybeVersion the source subsystem's version (default: current)
* @param maybeComponent optional component name (default: all in subsystem)
* @param target the target subsystem
* @param maybeTargetVersion the target subsystem's version
* @param maybeTargetComponent optional target component name (default: all in target subsystem)
*/
def icdComponentInfo(
subsystem: String,
maybeVersion: Option[String],
maybeComponent: Option[String],
target: String,
maybeTargetVersion: Option[String],
maybeTargetComponent: Option[String]
): Action[AnyContent] =
authAction.async {
val resp: Future[List[ComponentInfo]] = appActor ? (GetIcdComponentInfo(
subsystem,
maybeVersion,
maybeComponent,
target,
maybeTargetVersion,
maybeTargetComponent,
_
))
resp.map(info => Ok(Json.toJson(info)))
}
/**
* Returns the PDF for the given ICD
*
* @param subsystem the source subsystem
* @param maybeVersion the source subsystem's version (default: current)
* @param maybeComponent optional component name (default: all in subsystem)
* @param target the target subsystem
* @param maybeTargetVersion optional target subsystem's version (default: current)
* @param maybeTargetComponent optional target component name (default: all in target subsystem)
* @param maybeIcdVersion optional ICD version (default: current)
* @param maybeOrientation "portrait" or "landscape" (default)
* @param maybeFontSize base font size
* @param maybeLineHeight line-height for HTML
* @param maybePaperSize Letter, Legal, A4, A3, default: Letter
* @param maybeDetails If true, the PDF lists all detailed info, otherwise only the expanded rows in web app
* @param documentNumber optional document number to include in PDF under subtitle
*/
def icdAsPdf(
subsystem: String,
maybeVersion: Option[String],
maybeComponent: Option[String],
target: String,
maybeTargetVersion: Option[String],
maybeTargetComponent: Option[String],
maybeIcdVersion: Option[String],
maybeOrientation: Option[String],
maybeFontSize: Option[Int],
maybeLineHeight: Option[String],
maybePaperSize: Option[String],
maybeDetails: Option[Boolean],
documentNumber: Option[String]
): Action[AnyContent] =
Action.async { implicit request =>
val expandedIds =
if (request.method == "POST")
request.body.asFormUrlEncoded.get("expandedIds").headOption.getOrElse("").split(',').toList
else Nil
val resp: Future[Option[Array[Byte]]] = appActor ? (
GetIcdAsPdf(
subsystem,
maybeVersion,
maybeComponent,
target,
maybeTargetVersion,
maybeTargetComponent,
maybeIcdVersion,
PdfOptions(
maybeOrientation,
maybeFontSize,
maybeLineHeight,
maybePaperSize,
maybeDetails,
expandedIds,
documentNumber = documentNumber.getOrElse("")
),
_
)
)
resp.map {
case Some(bytes) =>
val filename = maybeIcdVersion match {
case None => s"ICD-SDB-$subsystem-$target.pdf"
case Some(icdVersion) => s"ICD-SDB-$subsystem-$target-$icdVersion.pdf"
}
Ok(bytes).as("application/pdf").withHeaders(("Content-Disposition", s"filename=\"$filename\""))
case None =>
NotFound
}
}
/**
* Returns the PDF for the given subsystem API
*
* @param subsystem the source subsystem
* @param maybeVersion the source subsystem's version (default: current)
* @param maybeComponent optional component (default: all in subsystem)
* @param searchAll if true, search all components for API dependencies
* @param clientApi if true, include subscribed events and sent commands in API
* @param maybeOrientation "portrait" or "landscape" (default)
* @param maybeFontSize base font size
* @param maybeLineHeight line-height for HTML
* @param maybePaperSize Letter, Legal, A4, A3, default: Letter
* @param maybeDetails If true, the PDF lists all detailed info, otherwise only the expanded rows in web app
* @param documentNumber optional document number to include in PDF under subtitle
*/
def apiAsPdf(
subsystem: String,
maybeVersion: Option[String],
maybeComponent: Option[String],
searchAll: Option[Boolean],
clientApi: Option[Boolean],
maybeOrientation: Option[String],
maybeFontSize: Option[Int],
maybeLineHeight: Option[String],
maybePaperSize: Option[String],
maybeDetails: Option[Boolean],
documentNumber: Option[String]
) =
Action.async { implicit request =>
val expandedIds =
if (request.method == "POST")
request.body.asFormUrlEncoded.get("expandedIds").headOption.getOrElse("").split(',').toList
else Nil
val resp: Future[Option[Array[Byte]]] = appActor ? (
GetApiAsPdf(
subsystem,
maybeVersion,
maybeComponent,
searchAll,
clientApi,
PdfOptions(
maybeOrientation,
maybeFontSize,
maybeLineHeight,
maybePaperSize,
maybeDetails,
expandedIds,
documentNumber = documentNumber.getOrElse("")
),
_
)
)
resp.map {
case Some(bytes) =>
val filename = maybeVersion match {
case None => s"API-SDB-$subsystem.pdf"
case Some(version) => s"API-SDB-$subsystem-$version.pdf"
}
Ok(bytes).as("application/pdf").withHeaders(("Content-Disposition", s"filename=\"$filename\""))
case None =>
NotFound
}
}
/**
* Returns a PDF for the FITS keyword information
*
* @param tag "All" for all keywords, otherwise restrict output to given tag, as defined in DMS-Model-Files/FITS-Dictionary
* @param maybeOrientation "portrait" or "landscape" (default)
* @param maybeFontSize base font size
* @param maybeLineHeight line-height for HTML
* @param maybePaperSize Letter, Legal, A4, A3, default: Letter
* @param maybeDetails Not used (for compatibility with other PDF generating APIs)
*/
def fitsDictionaryAsPdf(
tag: String,
maybeOrientation: Option[String],
maybeFontSize: Option[Int],
maybeLineHeight: Option[String],
maybePaperSize: Option[String],
maybeDetails: Option[Boolean]
) =
Action.async { implicit request =>
val resp: Future[Option[Array[Byte]]] = appActor ? (
GetFitsDictionaryAsPdf(
tag,
PdfOptions(maybeOrientation, maybeFontSize, maybeLineHeight, maybePaperSize),
_
)
)
resp.map {
case Some(bytes) =>
val fileName = tag match {
case "All" => "FITS-Dictionary.pdf"
case _ => s"FITS-Dictionary-$tag.pdf"
}
Ok(bytes).as("application/pdf").withHeaders(("Content-Disposition", s"filename=\"$fileName\""))
case None =>
NotFound
}
}
/**
* Returns the archived items report (PDF) for the given subsystem API
*
* @param subsystem the source subsystem
* @param maybeVersion the source subsystem's version (default: current)
* @param maybeComponent optional component (default: all in subsystem)
* @param maybeOrientation If set, should be "portrait" or "landscape" (default: landscape)
* @param maybeFontSize base font size for body text (default: 10)
*/
def archivedItemsReport(
subsystem: String,
maybeVersion: Option[String],
maybeComponent: Option[String],
maybeOrientation: Option[String],
maybeFontSize: Option[Int],
maybeLineHeight: Option[String],
maybePaperSize: Option[String]
) =
authAction.async {
val resp: Future[Option[Array[Byte]]] = appActor ? (
GetArchivedItemsReport(
subsystem,
maybeVersion,
maybeComponent,
PdfOptions(maybeOrientation, maybeFontSize, maybeLineHeight, maybePaperSize),
_
)
)
resp.map {
case Some(bytes) =>
val filename = maybeVersion match {
case None => s"$subsystem-Archived-Items.pdf"
case Some(version) => s"$subsystem-$version-Archived-Items.pdf"
}
Ok(bytes).as("application/pdf").withHeaders(("Content-Disposition", s"filename=\"$filename\""))
case None =>
NotFound
}
}
/**
* Returns the archived items report (HTML) for the given subsystem API
*
* @param subsystem the source subsystem
* @param maybeVersion the source subsystem's version (default: current)
* @param maybeComponent optional component (default: all in subsystem)
*/
def archivedItemsReportHtml(
subsystem: String,
maybeVersion: Option[String],
maybeComponent: Option[String]
) =
authAction.async {
val resp: Future[Option[String]] = appActor ? (
GetArchivedItemsReportHtml(
subsystem,
maybeVersion,
maybeComponent,
_
)
)
resp.map {
case Some(html) =>
Ok(html).as("text/html")
case None =>
NotFound
}
}
/**
* Returns the archived items report (PDF) for all current subsystems
* @param maybeOrientation If set, should be "portrait" or "landscape" (default: landscape)
* @param maybeFontSize base font size for body text (default: 10)
*/
def archivedItemsReportFull(
maybeOrientation: Option[String],
maybeFontSize: Option[Int],
maybeLineHeight: Option[String],
maybePaperSize: Option[String]
) =
authAction.async {
val resp: Future[Option[Array[Byte]]] = appActor ? (
GetArchivedItemsReportFull(
PdfOptions(maybeOrientation, maybeFontSize, maybeLineHeight, maybePaperSize),
_
)
)
resp.map {
case Some(bytes) =>
Ok(bytes).as("application/pdf").withHeaders(("Content-Disposition", s"filename=\"Archived-Items.pdf\""))
case None =>
NotFound
}
}
/**
* Returns the alarms report (PDF) for the given subsystem API
*
* @param subsystem the source subsystem
* @param maybeVersion the source subsystem's version (default: current)
* @param maybeComponent optional component (default: all in subsystem)
* @param maybeOrientation If set, should be "portrait" or "landscape" (default: landscape)
* @param maybeFontSize base font size for body text (default: 10)
*/
def alarmsReport(
subsystem: String,
maybeVersion: Option[String],
maybeComponent: Option[String],
maybeOrientation: Option[String],
maybeFontSize: Option[Int],
maybeLineHeight: Option[String],
maybePaperSize: Option[String]
) =
authAction.async {
val resp: Future[Option[Array[Byte]]] = appActor ? (
GetAlarmsReport(
subsystem,
maybeVersion,
maybeComponent,
PdfOptions(maybeOrientation, maybeFontSize, maybeLineHeight, maybePaperSize),
_
)
)
resp.map {
case Some(bytes) =>
val filename = maybeVersion match {
case None => s"$subsystem-Alarms.pdf"
case Some(version) => s"$subsystem-$version-Alarms.pdf"
}
Ok(bytes).as("application/pdf").withHeaders(("Content-Disposition", s"filename=\"$filename\""))
case None =>
NotFound
}
}
/**
* Returns the alarms report (PDF) for all current subsystems
*
* @param maybeOrientation If set, should be "portrait" or "landscape" (default: landscape)
* @param maybeFontSize base font size for body text (default: 10)
*/
def alarmsReportFull(
maybeOrientation: Option[String],
maybeFontSize: Option[Int],
maybeLineHeight: Option[String],
maybePaperSize: Option[String]
) =
authAction.async {
val resp: Future[Option[Array[Byte]]] = appActor ? (
GetAlarmsReportFull(
PdfOptions(maybeOrientation, maybeFontSize, maybeLineHeight, maybePaperSize),
_
)
)
resp.map {
case Some(bytes) =>
Ok(bytes).as("application/pdf").withHeaders(("Content-Disposition", s"filename=\"Alarms.pdf\""))
case None =>
NotFound
}
}
/**
* Returns a missing items report (PDF) for the given subsystem/component API
*
* @param subsystem the source subsystem
* @param maybeVersion the source subsystem's version (default: current)
* @param maybeComponent optional component (default: all in subsystem)
* @param maybeTarget optional target subsystem
* @param maybeTargetVersion optional target subsystem's version (default: current)
* @param maybeTargetComponent optional target component name (default: all in target subsystem)
* @param maybeOrientation If set, should be "portrait" or "landscape" (default: landscape)
* @param maybeFontSize base font size for body text (default: 10)
*/
def missingItemsReport(
subsystem: String,
maybeVersion: Option[String],
maybeComponent: Option[String],
maybeTarget: Option[String],
maybeTargetVersion: Option[String],
maybeTargetComponent: Option[String],
maybeOrientation: Option[String],
maybeFontSize: Option[Int],
maybeLineHeight: Option[String],
maybePaperSize: Option[String]
) =
authAction.async {
val resp: Future[Option[Array[Byte]]] = appActor ? (
GetMissingItemsReport(
subsystem,
maybeVersion,
maybeComponent,
maybeTarget,
maybeTargetVersion,
maybeTargetComponent,
PdfOptions(maybeOrientation, maybeFontSize, maybeLineHeight, maybePaperSize),
_
)
)
resp.map {
case Some(bytes) =>
val filename = maybeVersion match {
case None => s"$subsystem-Missing-Items.pdf"
case Some(version) => s"$subsystem-$version-Missing-Items.pdf"
}
Ok(bytes).as("application/pdf").withHeaders(("Content-Disposition", s"filename=\"$filename\""))
case None =>
NotFound
}
}
/**
* Returns a missing items report (HTML) for the given subsystem/component API
*
* @param subsystem the source subsystem
* @param maybeVersion the source subsystem's version (default: current)
* @param maybeComponent optional component (default: all in subsystem)
* @param maybeTarget optional target subsystem
* @param maybeTargetVersion optional target subsystem's version (default: current)
* @param maybeTargetComponent optional target component name (default: all in target subsystem)
* @param maybeOrientation If set, should be "portrait" or "landscape" (default: landscape)
* @param maybeFontSize base font size for body text (default: 10)
*/
def missingItemsReportHtml(
subsystem: String,
maybeVersion: Option[String],
maybeComponent: Option[String],
maybeTarget: Option[String],
maybeTargetVersion: Option[String],
maybeTargetComponent: Option[String],
maybeOrientation: Option[String],
maybeFontSize: Option[Int],
maybeLineHeight: Option[String],
maybePaperSize: Option[String]
) =
authAction.async {
val resp: Future[Option[String]] = appActor ? (
GetMissingItemsReportHtml(
subsystem,
maybeVersion,
maybeComponent,
maybeTarget,
maybeTargetVersion,
maybeTargetComponent,
PdfOptions(maybeOrientation, maybeFontSize, maybeLineHeight, maybePaperSize),
_
)
)
resp.map {
case Some(html) =>
Ok(html).as("text/html")
case None =>
NotFound
}
}
/**
* Returns a missing items report (PDF) for all current subsystems
* @param maybeOrientation If set, should be "portrait" or "landscape" (default: landscape)
* @param maybeFontSize base font size for body text (default: 10)
*/
def missingItemsReportFull(
maybeOrientation: Option[String],
maybeFontSize: Option[Int],
maybeLineHeight: Option[String],
maybePaperSize: Option[String]
) =
authAction.async {
val resp: Future[Option[Array[Byte]]] = appActor ? (
GetMissingItemsReportFull(
PdfOptions(maybeOrientation, maybeFontSize, maybeLineHeight, maybePaperSize),
_
)
)
resp.map {
case Some(bytes) =>
Ok(bytes).as("application/pdf").withHeaders(("Content-Disposition", s"filename=\"Missing-Items.pdf\""))
case None =>
NotFound
}
}
/**
* Returns the PDF for the given ICD
*
* @param subsystem the source subsystem
* @param maybeVersion the source subsystem's version (default: current)
* @param maybeComponent optional component name (default: all in subsystem)
* @param maybeTarget optional target subsystem
* @param maybeTargetVersion optional target subsystem's version (default: current)
* @param maybeTargetComponent optional target component name (default: all in target subsystem)
* @param maybeIcdVersion optional ICD version (default: current)
* @param maybeRatio Image aspect ratio (y/x)
* @param maybeMissingEvents Plot missing events
* @param maybeMissingCommands Plot missing commands
* @param maybeCommandLabels Plot command labels
* @param maybeEventLabels Plot event labels
* @param maybeGroupSubsystems Group components from same subsystem together
* @param maybeLayout Dot layout engine: One of {dot,fdp,sfdp,twopi,neato,circo,patchwork}
* @param maybeOverlap Node overlap handling: {true,false,scale}
* @param maybeSplines Use splines for edges?
* @param maybeOmitTypes list of component types (HCD,Assembly,Sequencer,Application) to omit as primaries (default={'HCD'})
*/
def makeGraph(
subsystem: String,
maybeVersion: Option[String],
maybeComponent: Option[String],
maybeTarget: Option[String],
maybeTargetVersion: Option[String],
maybeTargetComponent: Option[String],
maybeIcdVersion: Option[String],
maybeRatio: Option[Double],
maybeMissingEvents: Option[Boolean],
maybeMissingCommands: Option[Boolean],
maybeCommandLabels: Option[Boolean],
maybeEventLabels: Option[Boolean],
maybeGroupSubsystems: Option[Boolean],
maybeOnlySubsystems: Option[Boolean],
maybeLayout: Option[String],
maybeOverlap: Option[String],
maybeSplines: Option[Boolean],
maybeOmitTypes: Option[String],
maybeImageFormat: Option[String]
): Action[AnyContent] = {
import IcdVizOptions.*
Action.async { implicit request =>
val resp: Future[Option[Array[Byte]]] = appActor ? (
MakeGraph(
subsystem,
maybeVersion,
maybeComponent,
maybeTarget,
maybeTargetVersion,
maybeTargetComponent,
maybeIcdVersion,
IcdVizOptions(
ratio = maybeRatio.getOrElse(defaultRatio),
missingEvents = maybeMissingEvents.getOrElse(defaultMissingEvents),
missingCommands = maybeMissingCommands.getOrElse(defaultMissingCommands),
commandLabels = maybeCommandLabels.getOrElse(defaultCommandLabels),
eventLabels = maybeEventLabels.getOrElse(defaultEventLabels),
groupSubsystems = maybeGroupSubsystems.getOrElse(defaultGroupSubsystems),
onlySubsystems = maybeOnlySubsystems.getOrElse(defaultOnlySubsystems),
layout = maybeLayout.getOrElse(defaultLayout),
overlap = maybeOverlap.getOrElse(defaultOverlap),
splines = maybeSplines.getOrElse(defaultUseSplines),
omitTypes = maybeOmitTypes.getOrElse(defaultOmit).split(",").toList,
imageFormat = maybeImageFormat.getOrElse(defaultImageFormat)
),
_
)
)
resp.map {
case Some(bytes) =>
val format = maybeImageFormat.getOrElse(defaultImageFormat).toLowerCase()
val (suffix, contentType) = format match {
case "png" => (format, "image/png")
case "svg" => (format, "image/svg+xml")
case "pdf" => (format, "application/pdf")
case "eps" => (format, "application/postscript")
case _ => ("pdf", "application/pdf")
}
val filename = maybeTarget match {
case None =>
maybeVersion match {
case None => s"$subsystem-Graph.$suffix"
case Some(version) => s"$subsystem-$version-Graph.$suffix"
}
case Some(target) =>
maybeIcdVersion match {
case None => s"$subsystem-$target-Graph.$suffix"
case Some(icdVersion) => s"$subsystem-$target-$icdVersion-Graph.$suffix"
}
}
Ok(bytes).as(contentType).withHeaders(("Content-Disposition", s"filename=\"$filename\""))
case None =>
NotFound
}
}
}
/**
* Returns a detailed list of the versions of the given subsystem
*/
def getVersions(subsystem: String) =
authAction.async {
val resp: Future[List[VersionInfo]] = appActor ? (GetVersions(subsystem, _))
resp.map(versions => Ok(Json.toJson(versions)))
}
/**
* Returns a list of version names for the given subsystem
*/
def getVersionNames(subsystem: String) =
authAction.async {
val resp: Future[List[String]] = appActor ? (GetVersionNames(subsystem, _))
resp.map(names => Ok(Json.toJson(names)))
}
/**
* Gets a list of ICD names as pairs of (subsystem, targetSubsystem)
*/
def getIcdNames =
Action.async {
val resp: Future[List[IcdName]] = appActor ? GetIcdNames.apply
resp.map(names => Ok(Json.toJson(names)))
}
/**
* Gets a list of versions for the ICD from subsystem to target subsystem
*/
def getIcdVersions(subsystem: String, target: String) =
authAction.async {
val resp: Future[List[IcdVersionInfo]] = appActor ? (GetIcdVersions(subsystem, target, _))
resp.map(list => Ok(Json.toJson(list)))
}
/**
* Gets the difference between two subsystem versions
*/
def diff(subsystem: String, versionsStr: String) =
authAction.async {
val resp: Future[List[DiffInfo]] = appActor ? (GetDiff(subsystem, versionsStr, _))
resp.map(list => Ok(Json.toJson(list)))
}
/**
* Returns OK(true) if this is a public icd web server (upload not allowed,publish allowed, password protected)
*/
def isPublicServer =
Action {
val publicServer = configuration.get[Boolean]("icd.isPublicServer")
Ok(Json.toJson(publicServer))
}
/**
* Responds with the JSON for the PublishInfo for every subsystem
*/
def getPublishInfo(maybeSubsystem: Option[String]) =
authAction {
val publishInfo = icdGitManager.getPublishInfo(maybeSubsystem)
Ok(Json.toJson(publishInfo))
}
/**
* Checks if the given GitHub user and password are valid for publish
*/
def checkGitHubCredentials() =
authAction(block = { implicit request =>
val maybeGitHubCredentials = request.body.asJson.map(json => Json.fromJson[GitHubCredentials](json).get)
if (maybeGitHubCredentials.isEmpty) {
BadRequest("Missing POST data of type GitHubCredentials")
}
else {
val gitHubCredentials = maybeGitHubCredentials.get
try {
icdGitManager.checkGitHubCredentials(gitHubCredentials)
Ok.as(JSON)
}
catch {
case ex: TransportException =>
Unauthorized(ex.getMessage)
case ex: Exception =>
ex.printStackTrace()
BadRequest(ex.getMessage)
}
}
})
private def convertBytesToHex(bytes: Array[Byte]): String = {
val sb = new mutable.StringBuilder
for (b <- bytes) {
sb.append(String.format("%02x", Byte.box(b)))
}
sb.toString
}
/**
* Checks if the given user and password are valid for using the web app
*/
def checkCredentials() =
Action(block = { implicit request =>
val maybeCredentials = request.body.asJson.map(json => Json.fromJson[Credentials](json).get)
if (maybeCredentials.isEmpty) {
BadRequest("Missing POST data of type Credentials")
}
else {
val credentials = maybeCredentials.get
try {
val sha = convertBytesToHex(MessageDigest.getInstance("SHA-256").digest(credentials.toString.getBytes))
if (sha == expectedSha)
Ok.as(JSON).withCookies(Cookie(cookieName, sha, sameSite = Some(Strict)))
else
Unauthorized("Wrong user name or password")
}
catch {
case ex: Exception =>
ex.printStackTrace()
BadRequest(ex.getMessage)
}
}
})
/**
* Checks if the user is already logged in (returns true if logged in)
*/
def checkForCookie() =
Action(block = { implicit request =>
request.cookies.get(cookieName) match {
case Some(cookie) => Ok(Json.toJson(cookie.value == expectedSha))
case None => Ok(Json.toJson(false))
}
})
/**
* Log out of the web app
*/
def logout() =
authAction {
Ok.as(JSON).discardingCookies(DiscardingCookie(cookieName))
}
/**
* Publish the selected API (add an entry for the current commit of the master branch on GitHub)
*/
def publishApi() =
authAction.async { implicit request =>
val maybePublishApiInfo = request.body.asJson.map(json => Json.fromJson[PublishApiInfo](json).get)
if (maybePublishApiInfo.isEmpty) {
Future(BadRequest("Missing POST data of type PublishApiInfo"))
}
else {
val publishApiInfo = maybePublishApiInfo.get
val problems = icdGitManager.validate(publishApiInfo.subsystem)
if (problems.nonEmpty) {
val msg =
s"The version of ${publishApiInfo.subsystem} on GitHub did not pass validation: ${problems.map(_.toString).mkString(", ")}."
Future(NotAcceptable(msg))
}
else {
val resp: Future[Try[ApiVersionInfo]] = appActor ? (PublishApi(publishApiInfo, _))
resp.map {
case Success(info) =>
Ok(Json.toJson(info))
case Failure(ex) =>
ex match {
case ex: TransportException =>
Unauthorized(ex.getMessage)
case ex: Exception =>
ex.printStackTrace()
BadRequest(ex.getMessage)
}
}
}
}
}
/**
* Publish an ICD (add an entry to the icds file on the master branch of https://github.com/tmt-icd/ICD-Model-Files)
*/
def publishIcd() =
authAction.async { implicit request =>
val maybePublishIcdInfo = request.body.asJson.map(json => Json.fromJson[PublishIcdInfo](json).get)
if (maybePublishIcdInfo.isEmpty) {
Future(BadRequest("Missing POST data of type PublishIcdInfo"))
}
else {
val publishIcdInfo = maybePublishIcdInfo.get
val resp: Future[Try[IcdVersionInfo]] = appActor ? (PublishIcd(publishIcdInfo, _))
resp.map {
case Success(info) =>
Ok(Json.toJson(info))
case Failure(ex) =>
ex match {
case ex: TransportException =>
Unauthorized(ex.getMessage)
case ex: Exception =>
ex.printStackTrace()
BadRequest(ex.getMessage)
}
}
}
}
/**
* Unublish the selected API (removes an entry from the file in the master branch on GitHub)
*/
def unpublishApi() =
authAction.async { implicit request =>
val maybeUnpublishApiInfo = request.body.asJson.map(json => Json.fromJson[UnpublishApiInfo](json).get)
if (maybeUnpublishApiInfo.isEmpty) {
Future(BadRequest("Missing POST data of type UnpublishApiInfo"))
}
else {
val unpublishApiInfo = maybeUnpublishApiInfo.get
val resp: Future[Try[Option[ApiVersionInfo]]] = appActor ? (UnpublishApi(unpublishApiInfo, _))
resp.map {
case Success(info) =>
info match {
case Some(apiVersionInfo) =>
Ok(Json.toJson(apiVersionInfo))
case None =>
NotFound(s"${unpublishApiInfo.subsystem}-${unpublishApiInfo.subsystemVersion} was not found")
}
Ok(Json.toJson(info))
case Failure(ex) =>
ex match {
case ex: TransportException =>
Unauthorized(ex.getMessage)
case ex: Exception =>
ex.printStackTrace()
BadRequest(ex.getMessage)
}
}
}
}
/**
* Unpublish an ICD (remove an entry in the icds file on the master branch of https://github.com/tmt-icd/ICD-Model-Files)
*/
def unpublishIcd() =
authAction.async { implicit request =>
val maybeUnpublishIcdInfo = request.body.asJson.map(json => Json.fromJson[UnpublishIcdInfo](json).get)
if (maybeUnpublishIcdInfo.isEmpty) {
Future(BadRequest("Missing POST data of type UnpublishIcdInfo"))
}
else {