-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathSpaces.scala
More file actions
795 lines (714 loc) · 32.5 KB
/
Spaces.scala
File metadata and controls
795 lines (714 loc) · 32.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
package api
import api.Permission.Permission
import controllers.Utils
import models._
import play.api.Logger
import play.api.Play._
import play.api.i18n.Messages
import play.api.libs.json.{JsError, JsResult, JsSuccess, Json}
import play.api.libs.json.Json.{toJson, _}
import services._
import util.Mail
import java.util.Date
import javax.inject.Inject
import scala.collection.mutable.ListBuffer
/**
* Spaces allow users to partition the data into realms only accessible to users with the right permissions.
*/
class Spaces @Inject()(spaces: SpaceService,
userService: UserService,
datasetService: DatasetService,
collectionService: CollectionService,
events: EventService,
datasets: DatasetService,
appConfig: AppConfigurationService) extends ApiController {
/**
* String name of the Space such as 'Project space' etc., parsed from conf/messages
*/
val spaceTitle: String = Messages("space.title")
//TODO- Minimal Space created with Name and description. URLs are not yet put in
def createSpace() = PermissionAction(Permission.CreateSpace)(parse.json) { implicit request =>
Logger.debug("Creating new space")
if(request.user.get.status == UserStatus.ReadOnly) {
BadRequest(toJson("User is Read-Only"))
} else {
val nameOpt = (request.body \ "name").asOpt[String]
val descOpt = (request.body \ "description").asOpt[String]
(nameOpt, descOpt) match {
case (Some(name), Some(description)) => {
// TODO: add creator
val userId = request.user.get.id
val c = ProjectSpace(name = name, description = description, created = new Date(), creator = userId,
homePage = List.empty, logoURL = None, bannerURL = None, collectionCount = 0,
datasetCount = 0, fileCount = 0, userCount = 0, spaceBytes = 0, metadata = List.empty)
spaces.insert(c) match {
case Some(id) => {
appConfig.incrementCount('spaces, 1)
events.addObjectEvent(request.user, c.id, c.name, "create_space")
userService.findRoleByName("Admin") match {
case Some(realRole) => {
spaces.addUser(userId, realRole, UUID(id))
}
case None => Logger.info("No admin role found")
}
Ok(toJson(Map("id" -> id)))
}
case None => Ok(toJson(Map("status" -> "error")))
}
}
case (_, _) => BadRequest(toJson("Missing required parameters"))
}
}
}
def removeSpace(spaceId: UUID) = PermissionAction(Permission.DeleteSpace, Some(ResourceRef(ResourceRef.space, spaceId))) { implicit request =>
spaces.get(spaceId) match {
case Some(space) => {
removeContentsFromSpace(spaceId,request.user)
spaces.delete(spaceId, Utils.baseUrl(request), request.apiKey, request.user)
appConfig.incrementCount('spaces, -1)
events.addObjectEvent(request.user , space.id, space.name, "delete_space")
current.plugin[AdminsNotifierPlugin].foreach {
_.sendAdminsNotification(Utils.baseUrl(request), "Space", "removed", space.id.stringify, space.name)
}
}
}
//Success anyway, as if space is not found it is most probably deleted already
Ok(toJson(Map("status" -> "success")))
}
def get(id: UUID) = PermissionAction(Permission.ViewSpace, Some(ResourceRef(ResourceRef.space, id))) { implicit request =>
spaces.get(id) match {
case Some(space) => Ok(spaceToJson(Utils.decodeSpaceElements(space)))
case None => NotFound("Space not found")
}
}
def getUsers(id: UUID) = PermissionAction(Permission.ViewSpace, Some(ResourceRef(ResourceRef.space, id))) { implicit request =>
spaces.get(id) match {
case Some(space) =>
val usersInSpace = spaces.getUsersInSpace(space.id, None)
Ok(toJson(usersInSpace.map(userToJson)))
case None => {
NotFound("Space not found")
}
}
}
def list(when: Option[String], title: Option[String], date: Option[String], limit: Int) = UserAction(needActive=false) { implicit request =>
Ok(toJson(listSpaces(when, title, date, limit, Set[Permission](Permission.ViewSpace), false, request.user, request.user.fold(false)(_.superAdminMode), true).map(spaceToJson)))
}
def listCanEdit(when: Option[String], title: Option[String], date: Option[String], limit: Int) = UserAction(needActive=true) { implicit request =>
Ok(toJson(listSpaces(when, title, date, limit, Set[Permission](Permission.AddResourceToSpace, Permission.EditSpace), false, request.user, request.user.fold(false)(_.superAdminMode), true).map(spaceToJson)))
}
def listCanEditNotAlreadyIn(when: Option[String], collectionId : UUID, title: Option[String], date: Option[String], limit: Int) = UserAction(needActive=true ){ implicit request =>
Ok(toJson(listSpaces(when, title, date, limit, Set[Permission](Permission.AddResourceToSpace, Permission.EditSpace), false, request.user, request.user.fold(false)(_.superAdminMode), true).map(spaceToJson)))
}
/**
* Returns list of collections based on parameters and permissions.
* TODO this needs to be cleaned up when do permissions for adding to a resource
*/
private def listSpaces(when: Option[String], title: Option[String], date: Option[String], limit: Int, permission: Set[Permission], mine: Boolean, user: Option[User], superAdmin: Boolean, showPublic: Boolean, onlyTrial: Boolean = false) : List[ProjectSpace] = {
if (mine && user.isEmpty) return List.empty[ProjectSpace]
(when, title, date) match {
case (Some(w), Some(t), Some(d)) => {
if (mine)
spaces.listUser(d, nextPage=(w=="a"), limit, t, user, superAdmin, user.get)
else
spaces.listAccess(d, nextPage=(w=="a"), limit, t, permission, user, superAdmin, showPublic, showOnlyShared = false)
}
case (Some(w), Some(t), None) => {
if (mine)
spaces.listUser(limit, t, user, superAdmin, user.get)
else
spaces.listAccess(limit, t, permission, user, superAdmin, showPublic, showOnlyShared = false)
}
case (Some(w), None, Some(d)) => {
if (mine)
spaces.listUser(d, nextPage=(w=="a"), limit, user, superAdmin, user.get)
else
spaces.listAccess(d, nextPage=(w=="a"), limit, permission, user, superAdmin, showPublic, onlyTrial, showOnlyShared = false)
}
case (Some(w), None, None) => {
if (mine)
spaces.listUser(limit, user, superAdmin, user.get)
else
spaces.listAccess(limit, permission, user, superAdmin, showPublic, onlyTrial, showOnlyShared = false)
}
// default when to be "after" if not present in parameters. i.e. nextPage=true
case (None, Some(t), Some(d)) => {
if (mine)
spaces.listUser(d, true, limit, t, user, superAdmin, user.get)
else
spaces.listAccess(d, true, limit, t, permission, user, superAdmin, showPublic, showOnlyShared = false)
}
case (None, Some(t), None) => {
if (mine)
spaces.listUser(limit, t, user, superAdmin, user.get)
else
spaces.listAccess(limit, t, permission, user, superAdmin, showPublic, showOnlyShared = false)
}
case (None, None, Some(d)) => {
if (mine)
spaces.listUser(d, true, limit, user, superAdmin, user.get)
else
spaces.listAccess(d, true, limit, permission, user, superAdmin, showPublic, onlyTrial, showOnlyShared = false)
}
case (None, None, None) => {
if (mine)
spaces.listUser(limit, user, superAdmin, user.get)
else
spaces.listAccess(limit, permission, user, superAdmin, showPublic, onlyTrial, showOnlyShared = false)
}
}
}
def spaceToJson(space: ProjectSpace) = {
toJson(Map("id" -> space.id.stringify,
"name" -> space.name,
"description" -> space.description,
"creator" -> space.creator.stringify,
"created" -> space.created.toString))
}
def userToJson(user: User) = {
toJson(Map("id" -> user.id.stringify,
"email" -> user.email.get
))
}
def addCollectionToSpace(spaceId: UUID, collectionId: UUID) = PermissionAction(Permission.AddResourceToSpace, Some(ResourceRef(ResourceRef.space, spaceId))) {
implicit request =>
(spaces.get(spaceId), collectionService.get(collectionId)) match {
case (Some(s), Some(c)) => {
// TODO this needs to be cleaned up when do permissions for adding to a resource
if (!Permission.checkOwner(request.user, ResourceRef(ResourceRef.collection, collectionId))) {
Forbidden(toJson(s"You are not the ${Messages("owner").toLowerCase()} of the collection"))
} else {
spaces.addCollection(collectionId, spaceId, request.user)
collectionService.addToRootSpaces(collectionId, spaceId)
events.addSourceEvent(request.user, c.id, c.name, s.id, s.name, EventType.ADD_COLLECTION_SPACE.toString)
collectionService.index(collectionId)
spaces.get(spaceId) match {
case Some(space) => {
if (play.Play.application().configuration().getBoolean("addDatasetToCollectionSpace")){
collectionService.addDatasetsInCollectionAndChildCollectionsToCollectionSpaces(collectionId, request.user)
}
Ok(Json.obj("collectionInSpace" -> space.collectionCount.toString))
}
case None => NotFound
}
}
}
case (_, _) => NotFound
}
}
def addDatasetToSpace(spaceId: UUID, datasetId: UUID) = PermissionAction(Permission.AddResourceToSpace, Some(ResourceRef(ResourceRef.space, spaceId))) {
implicit request =>
(spaces.get(spaceId), datasetService.get(datasetId)) match {
case (Some(s), Some(d)) => {
// TODO this needs to be cleaned up when do permissions for adding to a resource
if (!Permission.checkOwner(request.user, ResourceRef(ResourceRef.dataset, datasetId))) {
Forbidden(toJson(s"You are not the ${Messages("owner").toLowerCase()} of the dataset"))
} else {
spaces.addDataset(datasetId, spaceId)
events.addSourceEvent(request.user, d.id, d.name, s.id, s.name, EventType.ADD_DATASET_SPACE.toString)
datasets.index(datasetId)
Ok(Json.obj("datasetsInSpace" -> (s.datasetCount + 1).toString))
}
}
case (_, _) => NotFound
}
}
def removeCollection(spaceId: UUID, collectionId: UUID, removeDatasets : Boolean) = PermissionAction(Permission.RemoveResourceFromSpace, Some(ResourceRef(ResourceRef.space, spaceId)), Some(ResourceRef(ResourceRef.collection, collectionId))) { implicit request =>
val user = request.user
user match {
case Some(loggedInUser) => {
(spaces.get(spaceId), collectionService.get(collectionId)) match {
case (Some(s), Some(c)) => {
if(c.root_spaces contains s.id) {
spaces.removeCollection(collectionId, spaceId)
collectionService.removeFromRootSpaces(collectionId, spaceId)
if (removeDatasets ){
updateSubCollectionsAndDatasets(spaceId, collectionId, user)
} else {
updateSubCollections(spaceId, collectionId)
}
events.addSourceEvent(request.user, c.id, c.name, s.id, s.name, EventType.REMOVE_COLLECTION_SPACE.toString)
Ok(toJson("success"))
} else {
BadRequest("Space is not part of root spaces")
}
}
case (_, _) => NotFound
}
}
case None => NotFound("User not supplied")
}
}
private def updateSubCollections(spaceId: UUID, collectionId: UUID) {
collectionService.get(collectionId) match {
case Some(collection) => {
val collectionDescendants = collectionService.getAllDescendants(collectionId)
for (descendant <- collectionDescendants){
val rootCollectionSpaces = collectionService.getRootSpaceIds(descendant.id)
for (space <- descendant.spaces) {
if (space == spaceId){
spaces.removeCollection(descendant.id, space)
}
}
}
}
case None => Logger.error("no collection found with id " + collectionId)
}
}
private def removeContentsFromSpace(spaceId : UUID, user : Option[User]){
spaces.get(spaceId) match {
case Some(space) => {
val collectionsInSpace = spaces.getCollectionsInSpace(Some(space.id.stringify),Some(0))
val datasetsInSpace = spaces.getDatasetsInSpace(Some(space.id.stringify),Some(0))
for (ds <- datasetsInSpace){
datasets.removeFromSpace(ds.id,space.id)
}
for (col <- collectionsInSpace){
spaces.removeCollection(col.id,space.id)
collectionService.removeFromRootSpaces(col.id, spaceId)
updateSubCollectionsAndDatasets(spaceId, col.id, user)
}
}
case None => Logger.error("Cannot remove contents. No space exists with id : " + spaceId )
}
}
private def updateSubCollectionsAndDatasets(spaceId: UUID, collectionId: UUID, user : Option[User] ) {
collectionService.get(collectionId) match {
case Some(collection) => {
val collectionDescendants = collectionService.getAllDescendants(collectionId)
val datasetsInCollection = datasetService.listCollection(collectionId.stringify, user)
for (dataset <- datasetsInCollection){
if (dataset.spaces.contains(spaceId)){
if (!datasetBelongsToOtherCollectionInSpace(dataset.id, collectionId, spaceId, collectionDescendants.toList)){
spaces.removeDataset(dataset.id,spaceId)
}
}
}
for (descendant <- collectionDescendants){
for (space <- descendant.spaces) {
if (space == spaceId){
spaces.removeCollection(descendant.id, space)
}
}
}
}
case None => Logger.error("no collection found with id " + collectionId)
}
}
private def datasetBelongsToOtherCollectionInSpace(datasetId : UUID, collectionId : UUID, spaceId : UUID, descendants : List[Collection]): Boolean = {
var foundOtherCollectionInSpace = false
datasetService.get(datasetId) match {
case Some(dataset) => {
if (!dataset.spaces.contains(spaceId)){
foundOtherCollectionInSpace = false
}
else {
val collectionIdsContainingDataset = dataset.collections
collectionService.get(collectionIdsContainingDataset).found.foreach(collection => {
val spacesOfCollection = collection.spaces
if (spacesOfCollection.contains(spaceId) && !descendants.contains(collection)){
foundOtherCollectionInSpace = true
}
})
}
}
case None => Logger.error("No dataset matches id " + datasetId)
}
return foundOtherCollectionInSpace
}
def listDatasets(spaceId: UUID, limit: Integer) = PermissionAction(Permission.ViewSpace, Some(ResourceRef(ResourceRef.space, spaceId))) { implicit request =>
spaces.get(spaceId) match {
case Some(space) =>{
val datasetList = datasets.listSpace(limit, spaceId.stringify)
Ok(toJson(datasetList))
}
case None => NotFound(s"Space $spaceId not found.")
}
}
def listCollections(spaceId: UUID, limit: Integer) = PermissionAction(Permission.ViewSpace, Some(ResourceRef(ResourceRef.space, spaceId))) { implicit request =>
spaces.get(spaceId) match {
case Some(space) => {
val collectionList = collectionService.listSpace(limit, spaceId.stringify)
Ok(toJson(collectionList))
}
case None => NotFound(s"Space $spaceId not found.")
}
}
def removeDataset(spaceId: UUID, datasetId: UUID) = PermissionAction(Permission.RemoveResourceFromSpace, Some(ResourceRef(ResourceRef.space, spaceId)), Some(ResourceRef(ResourceRef.dataset, datasetId))) { implicit request =>
(spaces.get(spaceId), datasetService.get(datasetId)) match {
case (Some(s), Some(d)) => {
spaces.removeDataset(datasetId, spaceId)
events.addSourceEvent(request.user , d.id, d.name, s.id, s.name, EventType.REMOVE_DATASET_SPACE.toString)
Ok(Json.obj("isTrial"-> datasets.get(datasetId).exists(_.isTRIAL).toString))
}
case (_, _) => NotFound
}
}
/**
* REST endpoint: POST call to update the configuration information associated with a specific Space
*
* Takes one arg, id:
*
* id, the UUID associated with the space that will be updated
*
* The data contained in the request body will defined by the following String key-value pairs:
*
* description -> The text for the updated description for the space
* name -> The text for the updated name for this space
* timetolive -> Text that represents an integer for the number of hours to retain resources
* enabled -> Text that represents a boolean flag for whether or not the space should purge resources that have expired
*
*/
def updateSpace(spaceid: UUID) = PermissionAction(Permission.EditSpace, Some(ResourceRef(ResourceRef.space, spaceid)))(parse.json) { implicit request =>
if (UUID.isValid(spaceid.stringify)) {
//Set up the vars we are looking for
var description: String = null
var name: String = null
var timeAsString: String = null
var enabled: Boolean = false
var access: String = SpaceStatus.PRIVATE.toString
var aResult: JsResult[String] = (request.body \ "description").validate[String]
// Pattern matching
aResult match {
case s: JsSuccess[String] => {
description = s.get
}
case e: JsError => {
Logger.error("Errors: " + JsError.toFlatJson(e).toString())
BadRequest(toJson("description data is missing from the updateSpace call."))
}
}
aResult = (request.body \ "name").validate[String]
// Pattern matching
aResult match {
case s: JsSuccess[String] => {
name = s.get
}
case e: JsError => {
Logger.error("Errors: " + JsError.toFlatJson(e).toString())
BadRequest(toJson("name data is missing from the updateSpace call."))
}
}
aResult = (request.body \ "timetolive").validate[String]
// Pattern matching
aResult match {
case s: JsSuccess[String] => {
timeAsString = s.get
}
case e: JsError => {
Logger.error("Errors: " + JsError.toFlatJson(e).toString())
BadRequest(toJson("timetolive data is missing from the updateSpace call."))
}
}
// Pattern matching
(request.body \ "enabled").validate[Boolean] match {
case b: JsSuccess[Boolean] => {
enabled = b.get
}
case e: JsError => {
Logger.error("Errors: " + JsError.toFlatJson(e).toString())
BadRequest(toJson("enabled data is missing from the updateSpace call."))
}
}
(request.body \ "access").validate[String] match {
case b: JsSuccess[String] => {
access = b.get
}
case e: JsError => {
Logger.error("Errors: " + JsError.toFlatJson(e).toString())
BadRequest(toJson("access data is missing from the updateSpace call."))
}
}
if (spaces.get(spaceid).map(_.isTrial).getOrElse(true) == true ){
access = SpaceStatus.TRIAL.toString
}
Logger.debug(s"updateInformation for space with id $spaceid. Args are $description, $name, $enabled, $timeAsString and $access")
//Generate the expiration time and the boolean flag
val timeToLive = timeAsString.toInt * 60 * 60 * 1000L
//val expireEnabled = enabledAsString.toBoolean
Logger.debug("converted values are " + timeToLive + " and " + enabled)
spaces.updateSpaceConfiguration(spaceid, name, description, timeToLive, enabled, access)
events.addObjectEvent(request.user, spaceid, name, "update_space_information")
Ok(Json.obj("status" -> "success"))
}
else {
Logger.error(s"The given id $spaceid is not a valid ObjectId.")
BadRequest(toJson(s"The given id $spaceid is not a valid ObjectId."))
}
}
/**
* REST endpoint: POST call to update the user information associated with a specific Space
*
* Takes one arg, spaceId:
*
* spaceId, the UUID associated with the space that will be updated
*
* The data contained in the request body will defined by the following String key-value pairs:
*
* rolesandusers -> A map that contains a role level as a key and a comma separated String of user IDs as the value
*
*/
def updateUsers(spaceId: UUID) = PermissionAction(Permission.EditSpace, Some(ResourceRef(ResourceRef.space, spaceId)))(parse.json) { implicit request =>
val user = request.user
if (UUID.isValid(spaceId.stringify)) {
val aResult: JsResult[Map[String, String]] = (request.body \ "rolesandusers").validate[Map[String, String]]
// Pattern matching
aResult match {
case aMap: JsSuccess[Map[String, String]] => {
//Set up a map of existing users to check against
val existingUsers = spaces.getUsersInSpace(spaceId, None)
var existUserRole: Map[String, String] = Map.empty
for (aUser <- existingUsers) {
spaces.getRoleForUserInSpace(spaceId, aUser.id) match {
case Some(aRole) => {
existUserRole += (aUser.id.stringify -> aRole.name)
}
case None => Logger.debug("This shouldn't happen. A user in a space should always have a role.")
}
}
val roleMap: Map[String, String] = aMap.get
for ((k, v) <- roleMap) {
//Deal with users that were removed
userService.findRoleByName(k) match {
case Some(aRole) => {
val idArray: Array[String] = v.split(",").map(_.trim())
for (existUserId <- existUserRole.keySet) {
if (!idArray.contains(existUserId)) {
//Check if the role is for this level
existUserRole.get(existUserId) match {
case Some(existRole) => {
if (existRole == k) {
//In this case, the level is correct, so it is a removal
spaces.removeUser(UUID(existUserId), spaceId)
}
}
case None => Logger.debug("This should never happen. A user in a space should always have a role.")
}
}
}
}
case None => Logger.debug("A role was sent up that doesn't exist. It is " + k)
}
}
spaces.get(spaceId) match {
case Some(space) => {
for ((k, v) <- roleMap) {
//The role needs to exist
userService.findRoleByName(k) match {
case Some(aRole) => {
val idArray: Array[String] = v.split(",").map(_.trim())
//Deal with all the ids that were sent up (changes and adds)
for (aUserId <- idArray) {
//For some reason, an empty string is getting through as aUserId on length
if (aUserId != "") {
if (existUserRole.contains(aUserId)) {
//The user exists in the space already
existUserRole.get(aUserId) match {
case Some(existRole) => {
if (existRole != k) {
spaces.changeUserRole(UUID(aUserId), aRole, spaceId)
}
}
case None => Logger.debug("This shouldn't happen. A user that is assigned to a space should always have a role.")
}
}
else {
//New user completely to the space
spaces.addUser(UUID(aUserId), aRole, spaceId)
events.addRequestEvent(user, userService.get(UUID(aUserId)).get, spaceId, spaces.get(spaceId).get.name, "add_user_to_space")
val newmember = userService.get(UUID(aUserId))
val theHtml = views.html.spaces.inviteNotificationEmail(spaceId.stringify, space.name, user.get.getMiniUser, newmember.get.getMiniUser.fullName, aRole.name)
Mail.sendEmail(s"[${AppConfiguration.getDisplayName}] - Added to $spaceTitle", request.user, newmember ,theHtml)
}
}
else {
Logger.debug("There was an empty string that counted as an array...")
}
}
}
case None => Logger.debug("A role was sent up that doesn't exist. It is " + k)
}
}
if(space.userCount != spaces.getUsersInSpace(space.id, None).length){
spaces.updateUserCount(space.id, spaces.getUsersInSpace(space.id, None).length)
}
Ok(Json.obj("status" -> "success"))
}
case None => NotFound(toJson("Errors: Could not find space"))
}
}
case e: JsError => {
Logger.error("Errors: " + JsError.toFlatJson(e).toString())
BadRequest(toJson("rolesandusers data is missing from the updateUsers call."))
}
}
}
else {
Logger.error(s"The given id $spaceId is not a valid ObjectId.")
BadRequest(toJson(s"The given id $spaceId is not a valid ObjectId."))
}
}
def removeUser(spaceId: UUID, removeUser:String) = PermissionAction(Permission.EditSpace, Some(ResourceRef(ResourceRef.space, spaceId))) { implicit request =>
val user = request.user
if(spaces.getRoleForUserInSpace(spaceId, UUID(removeUser)) != None){
spaces.removeUser(UUID(removeUser), spaceId)
events.addRequestEvent(user, userService.get(UUID(removeUser)).get, spaceId, spaces.get(spaceId).get.name, "remove_user_from_space")
Ok(Json.obj("status" -> "success"))
} else {
Logger.error(s"Remove User $removeUser from space $spaceId does not exist.")
BadRequest(toJson(s"The given id $spaceId is not a valid ObjectId."))
}
}
def follow(id: UUID) = AuthenticatedAction { implicit request =>
implicit val user = request.user
user match {
case Some(loggedInUser) => {
spaces.get(id) match {
case Some(space) => {
events.addObjectEvent(user, id, space.name, "follow_space")
spaces.addFollower(id, loggedInUser.id)
userService.followResource(loggedInUser.id, new ResourceRef(ResourceRef.space, id))
val recommendations = getTopRecommendations(id, loggedInUser)
recommendations match {
case x :: xs => Ok(Json.obj("status" -> "success", "recommendations" -> recommendations))
case Nil => Ok(Json.obj("status" -> "success"))
}
}
case None => {
NotFound
}
}
}
case None => {
Unauthorized
}
}
}
def unfollow(id: UUID) = AuthenticatedAction { implicit request =>
implicit val user = request.user
user match {
case Some(loggedInUser) => {
spaces.get(id) match {
case Some(space) => {
events.addObjectEvent(user, id, space.name, "unfollow_space")
spaces.removeFollower(id, loggedInUser.id)
userService.unfollowResource(loggedInUser.id, new ResourceRef(ResourceRef.space, id))
Ok
}
case None => {
NotFound
}
}
}
case None => {
Unauthorized
}
}
}
def getTopRecommendations(followeeUUID: UUID, follower: User): List[MiniEntity] = {
val followeeModel = spaces.get(followeeUUID)
followeeModel match {
case Some(followeeModel) => {
val sourceFollowerIDs = followeeModel.followers
val excludeIDs = follower.followedEntities.map(typedId => typedId.id) ::: List(followeeUUID, follower.id)
val num = play.api.Play.configuration.getInt("number_of_recommendations").getOrElse(10)
userService.getTopRecommendations(sourceFollowerIDs, excludeIDs, num)
}
case None => {
List.empty
}
}
}
def acceptRequest(id:UUID, requestuser:String, role:String) = PermissionAction(Permission.EditSpace, Some(ResourceRef(ResourceRef.space, id))) { implicit request =>
implicit val user = request.user
spaces.get(id) match {
case Some(s) => {
Logger.debug("request submitted in api.Space.acceptrequest ")
userService.get(UUID(requestuser)) match {
case Some(requestUser) => {
events.addRequestEvent(user, requestUser, id, s.name, "acceptrequest_space")
spaces.removeRequest(id, requestUser.id)
userService.findRoleByName(role) match {
case Some(r) => spaces.addUser(requestUser.id, r, id)
case _ => Logger.debug("Role not found" + role)
}
if(requestUser.email.isDefined) {
val subject: String = "Authorization Request from " + AppConfiguration.getDisplayName + " Accepted"
val body = views.html.spaces.requestresponseemail(user.get, id.toString, s.name, "accepted your request and assigned you as " + role + " to")
Mail.sendEmail(subject, request.user, getRecipientsList(s, requestUser), body)
}
Ok(Json.obj("status" -> "success"))
}
case None => NotFound("Request user not found")
}
}
case None => NotFound("Space not found")
}
}
def getRecipientsList(s: ProjectSpace, requestUser: User): List[String] = {
val recipients = new ListBuffer[String]()
recipients += requestUser.email.get.toString
for (requestReceiver <- spaces.getUsersInSpace(s.id, None)) {
spaces.getRoleForUserInSpace(s.id, requestReceiver.id) match {
case Some(aRole) => {
if (aRole.permissions.contains(Permission.EditSpace.toString) && requestReceiver.id != requestUser.id) {
recipients += requestReceiver.toString
}
}
}
}
return recipients.toList
}
def rejectRequest(id:UUID, requestuser:String) = PermissionAction(Permission.EditSpace, Some(ResourceRef(ResourceRef.space, id))) { implicit request =>
implicit val user = request.user
spaces.get(id) match {
case Some(s) => {
Logger.debug("request submitted in api.Space.rejectRequest")
userService.get(UUID(requestuser)) match {
case Some(requestUser) => {
events.addRequestEvent(user, requestUser, id, spaces.get(id).get.name, "rejectrequest_space")
spaces.removeRequest(id, requestUser.id)
if(requestUser.email.isDefined) {
val subject: String = "Authorization Request from " + AppConfiguration.getDisplayName + " Rejected"
val body = views.html.spaces.requestresponseemail(user.get, id.toString, s.name, "rejected your request to")
Mail.sendEmail(subject, request.user, getRecipientsList(s, requestUser), body)
}
Ok(Json.obj("status" -> "success"))
}
case None => NotFound("Request user not found")
}
}
case None => NotFound("Space not found")
}
}
def verifySpace(id:UUID) = ServerAdminAction { implicit request =>
implicit val user = request.user
user match {
case Some(loggedInUser) => {
spaces.get(id) match {
case Some(s) if s.isTrial => {
spaces.update(s.copy(status = SpaceStatus.PRIVATE.toString))
//set datasets in this space as verified status
datasetService.listSpace(0, s.id.toString()).map{ d =>
if(d.isTRIAL) {
datasetService.update(d.copy(status = DatasetStatus.DEFAULT.toString))
}
}
userService.listUsersInSpace(s.id, None).map { member =>
val theHtml = views.html.spaces.verifySpaceEmail(s.id.stringify, s.name, member.getMiniUser.fullName)
Mail.sendEmail("Space Status update", request.user, member, theHtml)
}
Ok(toJson(Map("status" -> "success")))
}
// If the space wasn't found by ID
case _ => {
BadRequest("Verify space failed")
}
}
}
case None => {
Unauthorized
}
}
}
}