ProjectController.cs 29.7 KB
Newer Older
1
using Coscine.Action;
2
using Coscine.Action.EventArgs;
3
4
using Coscine.Api.Project.ParameterObjects;
using Coscine.Api.Project.ReturnObjects;
5
6
using Coscine.ApiCommons;
using Coscine.ApiCommons.Factories;
7
using Coscine.Configuration;
8
9
10
using Coscine.Database.DataModel;
using Coscine.Database.Models;
using Coscine.Database.ReturnObjects;
Marcel Nellesen's avatar
Marcel Nellesen committed
11
using Coscine.Database.Util;
12
using Coscine.Logging;
13
14
15
16
using Coscine.Metadata;
using Coscine.ResourceLoader;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
17
using Microsoft.Extensions.Logging;
18
using System;
19
using System.Collections.Generic;
20
using System.Linq;
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
21
22
23

namespace Coscine.Api.Project.Controllers
{
24
25
26
27

    /// <summary>
    ///  /// This controller represents the actions which can be taken with a project object.
    /// </summary>
28
    [Authorize]
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
29
30
31
    public class ProjectController : Controller
    {
        private readonly Authenticator _authenticator;
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
32
        private readonly ProjectModel _projectModel;
33
        private readonly IConfiguration _configuration;
34
        private readonly Emitter _emitter;
Marcel Nellesen's avatar
Marcel Nellesen committed
35
        private readonly ActivatedFeaturesModel _activatedFeaturesModel;
36
        private readonly ProjectRoleModel _projectRoleModel;
37
38
39
        private readonly ProjectQuotaModel _projectQuotaModel;
        private readonly ResourceTypeModel _resourceTypeModel;
        private readonly ResourceModel _resourceModel;
40
        private readonly CoscineLogger _coscineLogger;
41
        private readonly VisibilityModel _visibilityModel;
42
        private readonly int _maxAvailable = 100;
43

44
45
46
47
        /// <summary>
        /// ProjectController constructor
        /// </summary>
        /// <param name="logger">Logger</param>
48
        public ProjectController(ILogger<ProjectController> logger)
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
49
        {
50
            _authenticator = new Authenticator(this, Program.Configuration);
51
            _configuration = Program.Configuration;
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
52
            _projectModel = new ProjectModel();
53
            _emitter = new Emitter(_configuration);
Marcel Nellesen's avatar
Marcel Nellesen committed
54
            _activatedFeaturesModel = new ActivatedFeaturesModel();
55
            _projectRoleModel = new ProjectRoleModel();
56
57
58
            _resourceTypeModel = new ResourceTypeModel();
            _resourceModel = new ResourceModel();
            _projectQuotaModel = new ProjectQuotaModel();
59
            _coscineLogger = new CoscineLogger(logger);
60
            _visibilityModel = new VisibilityModel();
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
61
        }
62
63
64
65
66

        /// <summary>
        /// Returns all available projects (including sub projects)
        /// </summary>
        /// <returns>Ok</returns>
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
67
        [Route("[controller]")]
68
        public ActionResult<IEnumerable<ProjectObject>> Index()
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
69
        {
70
            var user = _authenticator.GetUser();
71
            var result = _projectModel.GetWithAccess(user, UserRoles.Member, UserRoles.Owner).ToList()
72
                .Select((project) => _projectModel.CreateReturnObjectFromDatabaseObject(project))
73
74
                .OrderBy(element => element.DisplayName);

75
76
77
            return Ok(result);
        }

78
79
80
81
        /// <summary>
        /// Retrieves all top level projects
        /// </summary>
        /// <returns>Ok</returns>
82
        [Route("[controller]/-/topLevel")]
83
        public ActionResult<IEnumerable<ProjectObject>> GetTopLevelProjects()
84
85
        {
            var user = _authenticator.GetUser();
86
            var projects = _projectModel.GetTopLevelWithAccess(user, UserRoles.Member, UserRoles.Owner).ToList()
87
88
89
90
                .Select((project) => _projectModel.CreateReturnObjectFromDatabaseObject(project))
                .OrderBy(element => element.DisplayName);

            if (Request.Query != null && Request.Query["noanalyticslog"] != "true")
91
            {
92
                LogAnalyticsViewHome(projects.Select(x => x.Id.ToString()).ToList());
93
            }
94

95
            return Ok(projects);
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
96
97
        }

98
99
100
101
102
        /// <summary>
        /// This returns the the project if the user has access to it
        /// </summary>
        /// <param name="id">Id of the resource</param>
        /// <returns>Ok or Statuscode 401</returns>
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
103
        [HttpGet("[controller]/{id}")]
104
        public ActionResult<ProjectObject> Get(string id)
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
105
        {
106
107
108
109
            var user = _authenticator.GetUser();
            var project = _projectModel.GetById(Guid.Parse(id));
            if (_projectModel.HasAccess(user, project, UserRoles.Member, UserRoles.Owner))
            {
110
                SubProjectModel subProjectModel = new SubProjectModel();
111
                var subProjectRel = subProjectModel.GetAllWhere((subProject) => subProject.SubProjectId == project.Id && project.Deleted == false);
112

113
114
115
116
117
                var parentProjectRelation = subProjectRel.FirstOrDefault();
                if (parentProjectRelation != null && _projectModel.HasAccess(user, parentProjectRelation.ProjectId, UserRoles.Member, UserRoles.Owner))
                {
                    return Ok(_projectModel.CreateReturnObjectFromDatabaseObject(project, parentProjectRelation.ProjectId));
                }
118
119
120
121
122
123
                return Ok(_projectModel.CreateReturnObjectFromDatabaseObject(project));
            }
            else
            {
                return Unauthorized($"User is not allowed to see given the project {id}");
            }
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
124
125
        }

126
127
128
129
130
        /// <summary>
        /// Gets the resources
        /// </summary>
        /// <param name="id">Id of the resource</param>
        /// <returns>Json object or Statuscode 401</returns>
131
        [HttpGet("[controller]/{id}/resources")]
132
        public ActionResult<IEnumerable<ResourceObject>> GetResources(string id)
133
        {
134
135
136
137
138
139
140
            var project = _projectModel.GetById(Guid.Parse(id));
            var user = _authenticator.GetUser();

            var resourceModel = new ResourceModel();
            var resourceTypeModel = new ResourceTypeModel();
            if (_projectModel.HasAccess(user, project, UserRoles.Member, UserRoles.Owner))
            {
141
                var resources = resourceModel.GetAllWhere((resource) =>
142
                        (from projectResource in resource.ProjectResources
143
144
145
146
147
                         where projectResource.ProjectId == project.Id
                         select projectResource).Any())
                        .Select((resource) =>
                        {
                            return resourceModel.CreateReturnObjectFromDatabaseObject(resource);
148
                        }).OrderBy(element => element.DisplayName);
149
150
                if (Request.Query != null && Request.Query["noanalyticslog"] != "true")
                {
151
152
                    var projectObject = _projectModel.CreateReturnObjectFromDatabaseObject(_projectModel.GetById(project.Id));
                    LogAnalyticsViewProject(project, resources.ToList(), projectObject.Disciplines, projectObject.Organizations, user);
153
                }
154
                return Json(resources);
155
156
157
158
159
            }
            else
            {
                return Unauthorized($"User is not allowed to see given the project {id}");
            }
160
161
        }

162
        /// <summary>
163
        /// Retrieves the quota for the selected project.
164
        /// </summary>
165
166
167
168
        /// <param name="projectId">Id of the project.</param>
        /// <returns>List of project quotas</returns>
        [HttpGet("[controller]/{projectId}/quota/-/all")]
        public ActionResult<IEnumerable<ProjectQuota>> Quotas(string projectId)
169
170
        {
            var user = _authenticator.GetUser();
171
172
173
174
175
176
177
178
179

            if (!Guid.TryParse(projectId, out Guid projectGuid))
            {
                return BadRequest($"{projectId} is not a guid.");
            }

            var project = _projectModel.GetById(projectGuid);

            if (project == null)
180
            {
181
182
183
184
185
186
187
                return NotFound($"Could not find project with id: {projectId}");
            }

            if (!_projectModel.HasAccess(user, project, UserRoles.Owner))
            {
                return Unauthorized("The user is not authorized to perform a get on the selected project!");
            }
188

189
            var resourceTypes = _resourceTypeModel.GetAllWhere(x => x.Enabled.HasValue && x.Enabled.Value);
190

191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
            return Json(resourceTypes.Select(x => CreateProjectQuotaReturnObject(x, projectGuid)));
        }

        private ProjectQuotaReturnObject CreateProjectQuotaReturnObject(ResourceType x, Guid projectGuid)
        {
            var projectQuota = _projectQuotaModel.GetWhere((y) =>
                    y.ProjectId == projectGuid &&
                    y.ResourceTypeId == x.Id);
            return new ProjectQuotaReturnObject
            {
                Id = x.Id,
                Name = x.DisplayName,
                Used = CalculateUsed(x, projectGuid),
                Allocated = projectQuota == null ? 0 : projectQuota.Quota
            };
206
207
208
209
210
211
212
        }

        private int CalculateUsed(ResourceType resourceType, Guid projectId)
        {
            var resourceTypeDefinition = ResourceTypeFactory.CreateResourceTypeObject(resourceType.DisplayName, _configuration);

            var resources = _resourceModel.GetAllWhere((resource) =>
213
                        (from projectResource in resource.ProjectResources
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
                         where projectResource.ProjectId == projectId
                         select projectResource).Any() &&
                         resource.TypeId == resourceType.Id);

            var used = resources.Sum(y => resourceTypeDefinition.GetResourceQuotaAvailable(y.Id.ToString(), _resourceModel.GetResourceTypeOptions(y.Id)).Result);
            return (int)used;
        }

        /// <summary>
        /// Retrieves the quota for the selected project and resource Type.
        /// </summary>
        /// <param name="projectId">Id of the project</param>
        /// <param name="resourceTypeId">Id of the resource type</param>
        /// <returns>The project quota for the resource type.</returns>
        [HttpGet("[controller]/{projectId}/quota/{resourceTypeId}")]
        public ActionResult<ProjectQuotaReturnObject> Quota(string projectId, string resourceTypeId)
        {
            var user = _authenticator.GetUser();

            if (!Guid.TryParse(projectId, out Guid projectGuid))
            {
                return BadRequest($"{projectId} is not a guid.");
236
            }
237
238
239
240
241
242
243
244
245

            var project = _projectModel.GetById(projectGuid);

            if (project == null)
            {
                return NotFound($"Could not find project with id: {projectId}");
            }

            if (!_projectModel.HasAccess(user, project, UserRoles.Owner))
246
247
248
            {
                return Unauthorized("The user is not authorized to perform a get on the selected project!");
            }
249
250
251
252
253
254
255
256

            if (!Guid.TryParse(resourceTypeId, out Guid resourceTypeGuid))
            {
                return BadRequest($"{resourceTypeId} is not a guid.");
            }

            var resourceType = _resourceTypeModel.GetById(resourceTypeGuid);

257
            if (resourceType == null || !resourceType.Enabled.HasValue || !resourceType.Enabled.Value)
258
259
260
261
262
263
264
265
266
            {
                return NotFound($"Could not find resourceType with id: {resourceTypeId}");
            }

            var projectQuota =
                _projectQuotaModel.GetWhere((x) =>
                    x.ProjectId == projectGuid &&
                    x.ResourceTypeId == resourceTypeGuid);

267
268
269
270
271
272
273
            var projectQuotaReturnObject = new ProjectQuotaReturnObject
            {
                Id = resourceTypeGuid,
                Name = resourceType.DisplayName,
                Used = CalculateUsed(resourceType, projectGuid),
                Allocated = projectQuota.Quota
            };
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

            return Json(projectQuotaReturnObject);
        }

        /// <summary>
        /// Get the max quota for a resource type.
        /// </summary>
        /// <param name="projectId">Id of the project.</param>
        /// <param name="resourceTypeId">Id of the resource</param>
        /// <returns>The maximum value for the quota.</returns>
        [HttpGet("[controller]/{projectId}/quota/{resourceTypeId}/max")]
        public ActionResult<MaxProjectQuota> GetQuotaMax(string projectId, string resourceTypeId)
        {
            var user = _authenticator.GetUser();

            if (!Guid.TryParse(projectId, out Guid projectGuid))
            {
                return BadRequest($"{projectId} is not a guid.");
            }

            var project = _projectModel.GetById(projectGuid);

            if (project == null)
            {
                return NotFound($"Could not find project with id: {projectId}");
            }

            if (!_projectModel.HasAccess(user, project, UserRoles.Owner))
            {
                return Unauthorized("The user is not authorized to perform a get on the selected project!");
            }

            if (!Guid.TryParse(resourceTypeId, out Guid resourceTypeGuid))
            {
                return BadRequest($"{resourceTypeId} is not a guid.");
            }

            var resourceType = _resourceTypeModel.GetById(resourceTypeGuid);

313
            if (resourceType == null || !resourceType.Enabled.HasValue || !resourceType.Enabled.Value)
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
            {
                return NotFound($"Could not find resourceType with id: {resourceTypeId}");
            }

            return Json(new MaxProjectQuota { Id = resourceTypeGuid, Available = _maxAvailable });
        }

        /// <summary>
        /// Update the project quota.
        /// </summary>
        /// <param name="projectId">Id of the project.</param>
        /// <param name="resourceTypeId">Id of the resource.</param>
        /// <param name="updateProjectQuotaObject">Object containing the update values.</param>
        /// <returns>NoContent (204).</returns>
        [HttpPost("[controller]/{projectId}/quota/{resourceTypeId}")]
329
        public IActionResult UpdateQuota(string projectId, string resourceTypeId, [FromBody] UpdateProjectQuotaObject updateProjectQuotaObject)
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
        {
            var user = _authenticator.GetUser();

            if (!Guid.TryParse(projectId, out Guid projectGuid))
            {
                return BadRequest($"{projectId} is not a guid.");
            }

            var project = _projectModel.GetById(projectGuid);

            if (project == null)
            {
                return NotFound($"Could not find project with id: {projectId}");
            }

            if (!_projectModel.HasAccess(user, project, UserRoles.Owner))
            {
                return Unauthorized("The user is not authorized to perform a get on the selected project!");
            }

            if (!Guid.TryParse(resourceTypeId, out Guid resourceTypeGuid))
            {
                return BadRequest($"{resourceTypeId} is not a guid.");
            }

            var resourceType = _resourceTypeModel.GetById(resourceTypeGuid);

357
            if (resourceType == null || !resourceType.Enabled.HasValue || !resourceType.Enabled.Value)
358
359
360
361
            {
                return NotFound($"Could not find resourceType with id: {resourceTypeId}");
            }

362
363
364
365
366
            if (resourceType.DisplayName.Equals("rdss3"))
            {
                return BadRequest($"Cannot adjust quota for rdss3.");
            }

367
368
369
370
371
372
373
374
            if (updateProjectQuotaObject.Allocated < 0)
            {
                return BadRequest($"Allocated {updateProjectQuotaObject.Allocated}. Cannot be less than 0.");
            }

            var projectQuotaForCurrent = _projectQuotaModel.GetWhere(x => x.ProjectId == projectGuid && x.ResourceTypeId == resourceTypeGuid);
            var used = CalculateUsed(resourceType, projectGuid);

375
            if (used > updateProjectQuotaObject.Allocated)
376
377
378
379
            {
                return BadRequest($"Cannot set quota ({updateProjectQuotaObject.Allocated}) below the used value ({used}).");
            }

380
            if (updateProjectQuotaObject.Allocated > _maxAvailable)
381
            {
382
                return BadRequest($"Cannot set quota to {updateProjectQuotaObject.Allocated}. It would exceed the limit of {_maxAvailable}");
383
384
385
386
387
388
            }

            projectQuotaForCurrent.Quota = updateProjectQuotaObject.Allocated;
            _projectQuotaModel.Update(projectQuotaForCurrent);

            return NoContent();
389
        }
390

391
392
393
394
395
        /// <summary>
        /// Updates the selected project 
        /// </summary>
        /// <param name="id">Id of the resource</param>
        /// <returns>Ok or Statuscode 401</returns>
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
396
397
398
        [HttpPost("[controller]/{id}")]
        public IActionResult Update(string id)
        {
399
400
401
            var user = _authenticator.GetUser();
            var projectObject = ObjectFactory<ProjectObject>.DeserializeFromStream(Request.Body);
            var project = _projectModel.GetById(Guid.Parse(id));
402
            if (_projectModel.HasAccess(user, project, UserRoles.Owner))
403
            {
404
                LogAnalyticsEditProject(project, _projectModel.GetMetadataCompleteness(projectObject), projectObject.Disciplines, projectObject.Organizations, user);
405
406
407
408
409
410
                return Ok(_projectModel.UpdateByObject(project, projectObject));
            }
            else
            {
                return Unauthorized("The user is not authorized to perform an update on the selected project!");
            }
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
411
412
        }

413
414
415
416
417
        /// <summary>
        /// Deletes the selected project
        /// </summary>
        /// <param name="id">Id of the resource</param>
        /// <returns>Json object or Statuscode 401</returns>
418
419
420
        [HttpDelete("[controller]/{id}")]
        public IActionResult Delete(string id)
        {
421
422
423
424
            var user = _authenticator.GetUser();
            var project = _projectModel.GetById(Guid.Parse(id));
            if (_projectModel.HasAccess(user, project, UserRoles.Owner))
            {
425
426
                var projectObject = _projectModel.CreateReturnObjectFromDatabaseObject(_projectModel.GetById(project.Id));
                LogAnalyticsDeleteProject(project, projectObject.Disciplines, projectObject.Organizations, user);
427
428
429
430
431
432
433
                DeleteProject(project);
                return Json(_projectModel.CreateReturnObjectFromDatabaseObject(project));
            }
            else
            {
                return Unauthorized("The user is not authorized to perform an update on the selected project!");
            }
434
435
        }

436
437
438
439
440
441
        /// <summary>
        /// Deletes the project
        /// </summary>
        /// <param name="project">Project</param>
        /// <param name="isHard">isHard</param>
        /// <param name="propegateAction">propegate Action</param>
Marcel Nellesen's avatar
Marcel Nellesen committed
442
        public void DeleteProject(Database.DataModel.Project project, bool isHard = false, bool propegateAction = true)
443
        {
444
            var subProjectModel = new SubProjectModel();
445
446
            foreach (var subProject in subProjectModel.GetAllWhere(
                (subProject) => subProject.ProjectId == project.Id
447
                                && (subProject.SubProjectNavigation.Deleted == false || isHard)
448
            ))
449
            {
Marcel Nellesen's avatar
Marcel Nellesen committed
450
                Database.DataModel.Project subProjectObject;
451
452
453
                if (isHard)
                {
                    subProjectObject = _projectModel.GetByIdIncludingDeleted(subProject.SubProjectId);
454
                    subProjectModel.Delete(subProject);
455
456
457
458
459
460
                }
                else
                {
                    subProjectObject = _projectModel.GetById(subProject.SubProjectId);
                }
                DeleteProject(subProjectObject, isHard, propegateAction);
461
462
463
464
            }

            foreach (var subProject in subProjectModel.GetAllWhere((subProject) => subProject.SubProjectId == project.Id))
            {
465
466
467
468
                if (isHard)
                {
                    subProjectModel.Delete(subProject);
                }
469
470
            }

Marcel Nellesen's avatar
Marcel Nellesen committed
471
            if (isHard)
472
            {
Marcel Nellesen's avatar
Marcel Nellesen committed
473
                var projectResourceModel = new ProjectResourceModel();
474
475
                var resourceModel = new ResourceModel();
                var resourceTypeModel = new ResourceTypeModel();
Marcel Nellesen's avatar
Marcel Nellesen committed
476
                foreach (var projectResource in projectResourceModel.GetAllWhere((projectResource) => projectResource.ProjectId == project.Id))
477
                {
478
479
480
481
                    var resource = resourceModel.GetById(projectResource.ResourceId);
                    var resourceTypeOptions = resourceModel.GetResourceTypeOptions(projectResource.ResourceId);
                    var resourceTypeDefinition = ResourceTypeFactory.CreateResourceTypeObject(resourceTypeModel.GetById(resource.TypeId).DisplayName, _configuration);
                    resourceTypeDefinition.DeleteResource(projectResource.ResourceId.ToString(), resourceTypeOptions);
482
                    projectResourceModel.Delete(projectResource);
483
                    resourceModel.Delete(resource);
484
                }
485

Marcel Nellesen's avatar
Marcel Nellesen committed
486
487
                var projectRoleModel = new ProjectRoleModel();
                foreach (var projectRole in projectRoleModel.GetAllWhere((projectRole) => projectRole.ProjectId == project.Id))
488
489
490
                {
                    projectRoleModel.Delete(projectRole);
                }
491

Marcel Nellesen's avatar
Marcel Nellesen committed
492
493
                var projectDisciplineModel = new ProjectDisciplineModel();
                foreach (var projectDiscipline in projectDisciplineModel.GetAllWhere((projectDiscipline) => projectDiscipline.ProjectId == project.Id))
494
495
496
                {
                    projectDisciplineModel.Delete(projectDiscipline);
                }
497

Marcel Nellesen's avatar
Marcel Nellesen committed
498
499
                var projectInstituteModel = new ProjectInstituteModel();
                foreach (var projectInstitute in projectInstituteModel.GetAllWhere((projectInstitute) => projectInstitute.ProjectId == project.Id))
500
                {
501
                    projectInstituteModel.Delete(projectInstitute);
Marcel Nellesen's avatar
Marcel Nellesen committed
502
503
                }

504
                foreach (var projectQuota in _projectQuotaModel.GetAllWhere((Quota) => Quota.ProjectId == project.Id))
Marcel Nellesen's avatar
Marcel Nellesen committed
505
                {
506
                    _projectQuotaModel.Delete(projectQuota);
507
                }
508

Marcel Nellesen's avatar
Marcel Nellesen committed
509
510
                _activatedFeaturesModel.DeactivateAllFeatures(project);

511
512
513
514
515
516
517
                if (propegateAction)
                {
                    _emitter.EmitProjectDelete(new ProjectEventArgs(_configuration)
                    {
                        Project = project
                    });
                }
518

519
                _projectModel.HardDelete(project);
Marcel Nellesen's avatar
Marcel Nellesen committed
520
            }
521
522
523
524
            else
            {
                _projectModel.Delete(project);
            }
525
526
        }

527
528
529
530
        /// <summary>
        /// Creates a project
        /// </summary>
        /// <returns>Json object or Statuscode 401</returns>
531
        [HttpPost("[controller]")]
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
532
533
        public IActionResult Store()
        {
534
            var user = _authenticator.GetUser();
535
            var isRWTHMember = IsRWTHMember(user);
536
537
            var projectObject = ObjectFactory<ProjectObject>.DeserializeFromStream(Request.Body);

538
            if (projectObject?.ParentId != new Guid()
539
540
541
542
543
                && !_projectModel.HasAccess(user, _projectModel.GetById(projectObject.ParentId), UserRoles.Owner))
            {
                return Unauthorized("User is not allowed to create SubProjects.");
            }

544
            var project = _projectModel.StoreFromObject(projectObject, user, isRWTHMember);
545

546
            if (projectObject.ParentId != new Guid()
547
548
549
550
551
552
553
554
555
556
557
558
559
                // for now, only an owner can add subprojects to projects
                && _projectModel.HasAccess(user, _projectModel.GetById(projectObject.ParentId), UserRoles.Owner))
            {
                var subProjectModel = new SubProjectModel();
                subProjectModel.LinkSubProject(projectObject.ParentId, project.Id);
            }

            _emitter.EmitProjectCreate(new ProjectEventArgs(_configuration)
            {
                Project = project,
                ProjectOwner = user
            });

560
            LogAnalyticsAddProject(project, _projectModel.GetMetadataCompleteness(projectObject), projectObject.Disciplines, projectObject.Organizations, user);
561

562
            return Json(_projectModel.CreateReturnObjectFromDatabaseObject(project));
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
563
        }
564

565
566
567
568
569
        /// <summary>
        /// Checks if the given user is a member of the RWTH 
        /// </summary>
        /// <param name="user">User object</param>
        /// <returns>True, if member of RWTH or false, if not a member of RWTH</returns>
570
571
572
        private bool IsRWTHMember(User user)
        {
            var externalIds = new ExternalIdModel().GetAllWhere((externalId) => externalId.UserId == user.Id);
573
            if (!externalIds.Any())
574
575
576
577
            {
                return false;
            }
            var externalIdList = new List<string>();
578

579
580
            foreach (var externalId in externalIds)
            {
581
                externalIdList.Add(externalId.ExternalId1);
582
            }
583
            return new RdfStoreConnector(Program.Configuration.GetStringAndWait("coscine/local/virtuoso/additional/url")).GetTriples(new Uri("https://ror.org/04xfq0f34"), null, null, 1, externalIdList).Any();
584
585
        }

586
        private void LogAnalyticsViewHome(List<string> projectIds)
587
        {
588
589
590
591
592
593
594
595
596
597
598
599
600
601
            _coscineLogger.AnalyticsLog(
                new AnalyticsLogObject
                {
                    Type = "Action",
                    Operation = "View Home",
                    ProjectList = projectIds
                });
        }

        private void LogAnalyticsViewProject(Database.DataModel.Project project, List<ResourceObject> resources, IEnumerable<DisciplineObject> disciplines, IEnumerable<OrganizationObject> organizations, User user)
        {
            var resourceTypes = _resourceTypeModel.GetAllWhere(x => x.Enabled.HasValue && x.Enabled.Value);

            var objects = resourceTypes.Select(x => CreateProjectQuotaReturnObject(x, project.Id));
602

603
604
            _coscineLogger.AnalyticsLog(
                new AnalyticsLogObject
605
                {
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
                    Type = "Action",
                    Operation = "View Project",
                    RoleId = _projectRoleModel.GetGetUserRoleForProject(project.Id, user.Id).ToString(),
                    ProjectId = project.Id.ToString(),
                    QuotaSize = objects.Select(x => $"{x.Name}: {x.Used}/{x.Allocated}").ToList(),
                    Disciplines = disciplines.Select(x => x.DisplayNameEn).ToList(),
                    Organizations = organizations.Select(x => x.DisplayName).ToList(),
                    Visibility = project.VisibilityId.HasValue ? _visibilityModel.GetById(project.VisibilityId.Value)?.DisplayName : null,
                    ResourceList = resources.Select(x => x.Id.ToString()).ToList(),
                });
        }

        private void LogAnalyticsEditProject(Database.DataModel.Project project, string metadataCompletness, IEnumerable<DisciplineObject> disciplines, IEnumerable<OrganizationObject> organizations, User user)
        {
            var resourceTypes = _resourceTypeModel.GetAllWhere(x => x.Enabled.HasValue && x.Enabled.Value);

            var objects = resourceTypes.Select(x => CreateProjectQuotaReturnObject(x, project.Id));

            _coscineLogger.AnalyticsLog(
                new AnalyticsLogObject
626
                {
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
                    Type = "Action",
                    Operation = "Edit Project",
                    RoleId = _projectRoleModel.GetGetUserRoleForProject(project.Id, user.Id).ToString(),
                    ProjectId = project.Id.ToString(),
                    QuotaSize = objects.Select(x => $"{x.Name}: {x.Used}/{x.Allocated}").ToList(),
                    MetadataCompleteness = metadataCompletness,
                    Disciplines = disciplines.Select(x => x.DisplayNameEn).ToList(),
                    Organizations = organizations.Select(x => x.DisplayName).ToList(),
                    Visibility = project.VisibilityId.HasValue ? _visibilityModel.GetById(project.VisibilityId.Value)?.DisplayName : null,
                });
        }

        private void LogAnalyticsAddProject(Database.DataModel.Project project, string metadataCompletness, IEnumerable<DisciplineObject> disciplines, IEnumerable<OrganizationObject> organizations, User user)
        {
            var resourceTypes = _resourceTypeModel.GetAllWhere(x => x.Enabled.HasValue && x.Enabled.Value);

            var objects = resourceTypes.Select(x => CreateProjectQuotaReturnObject(x, project.Id));

            _coscineLogger.AnalyticsLog(
                new AnalyticsLogObject
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
                    Type = "Action",
                    Operation = "Add Project",
                    RoleId = _projectRoleModel.GetGetUserRoleForProject(project.Id, user.Id).ToString(),
                    ProjectId = project.Id.ToString(),
                    QuotaSize = objects.Select(x => $"{x.Name}: {x.Used}/{x.Allocated}").ToList(),
                    MetadataCompleteness = metadataCompletness,
                    Disciplines = disciplines.Select(x => x.DisplayNameEn).ToList(),
                    Organizations = organizations.Select(x => x.DisplayName).ToList(),
                    Visibility = project.VisibilityId.HasValue ? _visibilityModel.GetById(project.VisibilityId.Value)?.DisplayName : null,
                });
        }

        private void LogAnalyticsDeleteProject(Database.DataModel.Project project, IEnumerable<DisciplineObject> disciplines, IEnumerable<OrganizationObject> organizations, User user)
        {
            var resourceTypes = _resourceTypeModel.GetAllWhere(x => x.Enabled.HasValue && x.Enabled.Value);

            var objects = resourceTypes.Select(x => CreateProjectQuotaReturnObject(x, project.Id));

            _coscineLogger.AnalyticsLog(
                new AnalyticsLogObject
                {
                    Type = "Action",
                    Operation = "Delete Project",
                    RoleId = _projectRoleModel.GetGetUserRoleForProject(project.Id, user.Id).ToString(),
                    ProjectId = project.Id.ToString(),
                    QuotaSize = objects.Select(x => $"{x.Name}: {x.Used}/{x.Allocated}").ToList(),
                    Disciplines = disciplines.Select(x => x.DisplayNameEn).ToList(),
                    Organizations = organizations.Select(x => x.DisplayName).ToList(),
                    Visibility = project.VisibilityId.HasValue ? _visibilityModel.GetById(project.VisibilityId.Value)?.DisplayName : null,
                });
678
        }
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
679
680
    }
}