ProjectController.cs 29.6 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
362
363
364
365
366
367
368
369
            {
                return NotFound($"Could not find resourceType with id: {resourceTypeId}");
            }

            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);

370
            if (used > updateProjectQuotaObject.Allocated)
371
372
373
374
            {
                return BadRequest($"Cannot set quota ({updateProjectQuotaObject.Allocated}) below the used value ({used}).");
            }

375
            if (updateProjectQuotaObject.Allocated > _maxAvailable)
376
            {
377
                return BadRequest($"Cannot set quota to {updateProjectQuotaObject.Allocated}. It would exceed the limit of {_maxAvailable}");
378
379
380
381
382
383
            }

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

            return NoContent();
384
        }
385

386
387
388
389
390
        /// <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
391
392
393
        [HttpPost("[controller]/{id}")]
        public IActionResult Update(string id)
        {
394
395
396
            var user = _authenticator.GetUser();
            var projectObject = ObjectFactory<ProjectObject>.DeserializeFromStream(Request.Body);
            var project = _projectModel.GetById(Guid.Parse(id));
397
            if (_projectModel.HasAccess(user, project, UserRoles.Owner))
398
            {
399
                LogAnalyticsEditProject(project, _projectModel.GetMetadataCompleteness(projectObject), projectObject.Disciplines, projectObject.Organizations, user);
400
401
402
403
404
405
                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
406
407
        }

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

431
432
433
434
435
436
        /// <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
437
        public void DeleteProject(Database.DataModel.Project project, bool isHard = false, bool propegateAction = true)
438
        {
439
            var subProjectModel = new SubProjectModel();
440
441
            foreach (var subProject in subProjectModel.GetAllWhere(
                (subProject) => subProject.ProjectId == project.Id
442
                                && (subProject.SubProjectNavigation.Deleted == false || isHard)
443
            ))
444
            {
Marcel Nellesen's avatar
Marcel Nellesen committed
445
                Database.DataModel.Project subProjectObject;
446
447
448
                if (isHard)
                {
                    subProjectObject = _projectModel.GetByIdIncludingDeleted(subProject.SubProjectId);
449
                    subProjectModel.Delete(subProject);
450
451
452
453
454
455
                }
                else
                {
                    subProjectObject = _projectModel.GetById(subProject.SubProjectId);
                }
                DeleteProject(subProjectObject, isHard, propegateAction);
456
457
458
459
            }

            foreach (var subProject in subProjectModel.GetAllWhere((subProject) => subProject.SubProjectId == project.Id))
            {
460
461
462
463
                if (isHard)
                {
                    subProjectModel.Delete(subProject);
                }
464
465
            }

Marcel Nellesen's avatar
Marcel Nellesen committed
466
            if (isHard)
467
            {
Marcel Nellesen's avatar
Marcel Nellesen committed
468
                var projectResourceModel = new ProjectResourceModel();
469
470
                var resourceModel = new ResourceModel();
                var resourceTypeModel = new ResourceTypeModel();
Marcel Nellesen's avatar
Marcel Nellesen committed
471
                foreach (var projectResource in projectResourceModel.GetAllWhere((projectResource) => projectResource.ProjectId == project.Id))
472
                {
473
474
475
476
                    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);
477
                    projectResourceModel.Delete(projectResource);
478
                    resourceModel.Delete(resource);
479
                }
480

Marcel Nellesen's avatar
Marcel Nellesen committed
481
482
                var projectRoleModel = new ProjectRoleModel();
                foreach (var projectRole in projectRoleModel.GetAllWhere((projectRole) => projectRole.ProjectId == project.Id))
483
484
485
                {
                    projectRoleModel.Delete(projectRole);
                }
486

Marcel Nellesen's avatar
Marcel Nellesen committed
487
488
                var projectDisciplineModel = new ProjectDisciplineModel();
                foreach (var projectDiscipline in projectDisciplineModel.GetAllWhere((projectDiscipline) => projectDiscipline.ProjectId == project.Id))
489
490
491
                {
                    projectDisciplineModel.Delete(projectDiscipline);
                }
492

Marcel Nellesen's avatar
Marcel Nellesen committed
493
494
                var projectInstituteModel = new ProjectInstituteModel();
                foreach (var projectInstitute in projectInstituteModel.GetAllWhere((projectInstitute) => projectInstitute.ProjectId == project.Id))
495
                {
496
                    projectInstituteModel.Delete(projectInstitute);
Marcel Nellesen's avatar
Marcel Nellesen committed
497
498
                }

499
                foreach (var projectQuota in _projectQuotaModel.GetAllWhere((Quota) => Quota.ProjectId == project.Id))
Marcel Nellesen's avatar
Marcel Nellesen committed
500
                {
501
                    _projectQuotaModel.Delete(projectQuota);
502
                }
503

Marcel Nellesen's avatar
Marcel Nellesen committed
504
505
                _activatedFeaturesModel.DeactivateAllFeatures(project);

506
507
508
509
510
511
512
                if (propegateAction)
                {
                    _emitter.EmitProjectDelete(new ProjectEventArgs(_configuration)
                    {
                        Project = project
                    });
                }
513

514
                _projectModel.HardDelete(project);
Marcel Nellesen's avatar
Marcel Nellesen committed
515
            }
516
517
518
519
            else
            {
                _projectModel.Delete(project);
            }
520
521
        }

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

533
            if (projectObject?.ParentId != new Guid()
534
535
536
537
538
                && !_projectModel.HasAccess(user, _projectModel.GetById(projectObject.ParentId), UserRoles.Owner))
            {
                return Unauthorized("User is not allowed to create SubProjects.");
            }

539
            var project = _projectModel.StoreFromObject(projectObject, user, isRWTHMember);
540

541
            if (projectObject.ParentId != new Guid()
542
543
544
545
546
547
548
549
550
551
552
553
554
                // 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
            });

555
            LogAnalyticsAddProject(project, _projectModel.GetMetadataCompleteness(projectObject), projectObject.Disciplines, projectObject.Organizations, user);
556

557
            return Json(_projectModel.CreateReturnObjectFromDatabaseObject(project));
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
558
        }
559

560
561
562
563
564
        /// <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>
565
566
567
        private bool IsRWTHMember(User user)
        {
            var externalIds = new ExternalIdModel().GetAllWhere((externalId) => externalId.UserId == user.Id);
568
            if (!externalIds.Any())
569
570
571
572
            {
                return false;
            }
            var externalIdList = new List<string>();
573

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

581
        private void LogAnalyticsViewHome(List<string> projectIds)
582
        {
583
584
585
586
587
588
589
590
591
592
593
594
595
596
            _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));
597

598
599
            _coscineLogger.AnalyticsLog(
                new AnalyticsLogObject
600
                {
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
                    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
621
                {
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
                    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
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
                    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,
                });
673
        }
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
674
675
    }
}