-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathProjectController.cs
More file actions
2460 lines (2077 loc) · 92.6 KB
/
ProjectController.cs
File metadata and controls
2460 lines (2077 loc) · 92.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Internal;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Threading.Tasks;
using Infrastructure.Data;
using Core.Interfaces;
using Web.ViewModels.Project;
using Core.Entities;
using System.Net.Http;
using System.Collections;
using Microsoft.AspNetCore.Http;
using System.ComponentModel;
using static System.Reflection.Metadata.BlobBuilder;
using System.Net;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Analysim.Web.ViewModels.Project;
using SixLabors.ImageSharp.Metadata.Profiles.Exif;
using System.Web;
using Newtonsoft.Json;
using Analysim.Core.Entities;
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;
namespace Web.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ProjectController : ControllerBase
{
private readonly ApplicationDbContext _dbContext;
private readonly IConfiguration _configuration;
public ProjectController(ApplicationDbContext dbContext, IConfiguration configuration)
{
_dbContext = dbContext;
_configuration = configuration;
}
#region GET REQUEST
/*
* Type : GET
* URL : /api/project/getprojectbyid/
* Param : {projectID}
* Description: Get Project
*/
[HttpGet("[action]/{projectID}")]
public IActionResult GetProjectByID([FromRoute] int projectID)
{
// Find Project
// Include To Many List
var project = _dbContext.Projects
.Include(p => p.BlobFiles)
.Include(p => p.ProjectUsers)
.Include(p => p.Notebooks)
.Include(p => p.ProjectTags).ThenInclude(pt => pt.Tag)
.SingleOrDefault(p => p.ProjectID == projectID);
if (project == null) return NotFound(new { message = "Project Not Found" });
// Return Ok Request
return Ok(new
{
result = project,
message = "Received Project"
});
}
/*
* Type : GET
* URL : /api/project/getprojectbyroute/
* Param : {owner}/{projectname}
* Description: Get Project
*/
[HttpGet("[action]/{owner}/{projectname}")]
public IActionResult GetProjectByRoute([FromRoute] string owner, [FromRoute] string projectname)
{
// Find Project
var project = _dbContext.Projects
.Include(p => p.BlobFiles)
.Include(p => p.Notebooks)
.Include(p => p.ProjectUsers).ThenInclude(pu => pu.User)
.Include(p => p.ProjectTags).ThenInclude(pt => pt.Tag)
.SingleOrDefault(p => p.Route.ToLower() == owner.ToLower() + "/" + projectname.ToLower());
if (project == null) return NotFound(new { message = "Project Not Found" });
// Return Ok Request
return Ok(new
{
result = project,
message = "Received Project"
});
}
/*
* Type : GET
* URL : /api/project/getprojectrange?
* Description: Get Project Range
*/
[HttpGet("[action]")]
public IActionResult GetProjectRange([FromQuery(Name = "id")] List<int> idList)
{
// Find Project
var projects = _dbContext.Projects
.Include(p => p.BlobFiles)
.Include(p => p.ProjectUsers)
.Include(p => p.ProjectTags).ThenInclude(pt => pt.Tag)
.Where(p => idList.Contains(p.ProjectID))
.ToList();
// Return Ok Request
return Ok(new
{
result = projects,
message = "Received Project"
});
}
/*
* Type : GET
* URL : /api/project/getprojectList
* Description: Get Project List
*/
[HttpGet("[action]")]
public IActionResult GetProjectList()
{
// Get All Project And Include To Many List
var projects = _dbContext.Projects
.Include(p => p.BlobFiles)
.Include(p => p.ProjectUsers)
.Include(p => p.ProjectTags).ThenInclude(pt => pt.Tag)
.ToList();
// Return Ok Request
return Ok(new
{
result = projects,
message = "Received Project"
});
}
/*
* Type : GET
* URL : /api/project/search?
* Description: Filter Project Using Search Term
*/
[HttpGet("[action]")]
public IActionResult Search([FromQuery(Name = "term")] List<string> searchTerms)
{
var matchedTag = _dbContext.Tag
.ToList()
.Where(t => searchTerms.Any(st => t.Name.ToLower().Contains(st.ToLower())));
var matchedProject = _dbContext.Projects
.Include(p => p.BlobFiles)
.Include(p => p.ProjectUsers)
.Include(p => p.ProjectTags).ThenInclude(pt => pt.Tag)
.ToList()
.Where(p => matchedTag.Any(mt => p.ProjectTags.Any(pt => pt.Tag.Name.ToLower() == mt.Name.ToLower())));
if (matchedProject.Count() == 0) return NoContent();
return Ok(new
{
result = matchedProject,
message = "Received Search Result."
});
}
/*
* Type : GET
* URL : /api/project/downloadfile/
* Param : {fileID}
* Description: Download file from Azure Storage
*/
[HttpGet("[action]/{fileID}")]
public async Task<IActionResult> DownloadFile([FromRoute] int fileID)
{
try
{
// Find blobfile
var blobFile = await _dbContext.BlobFiles.FindAsync(fileID);
if (blobFile == null) return NotFound();
//find blobfile content
var blobFileContent = await _dbContext.BlobFileContent.FindAsync(fileID);
if (blobFileContent == null) return NotFound();
//BlobDownloadInfo data = await _blobService.GetBlobAsync(blobFile);
return File(blobFileContent.Content, "application/octet-stream", blobFile.Name + blobFile.Extension);
}
catch (Exception e)
{
// Return Bad Request If There Is Any Error
return BadRequest(e);
}
}
/*
* Type : GET
* URL : /api/project/download/
* Param : {username}/{projectname}/{directory}/{filename}
* Description: Download file with user and project name
*/
[HttpGet("[action]/{username}/{projectname}/{*filepath}")]
public async Task<IActionResult> Download([FromRoute] string username, [FromRoute] string projectname, [FromRoute] string filepath)
{
try
{
// Find blobfile
var blobFile = await _dbContext.BlobFiles
.FirstOrDefaultAsync(b => b.User.UserName == username && b.Container == projectname && b.Directory + b.Name + b.Extension == filepath);
if (blobFile == null) return NotFound();
//find blobfile content
var blobFileContent = await _dbContext.BlobFileContent.FindAsync(blobFile.BlobFileID);
if (blobFileContent == null) return NotFound();
//BlobDownloadInfo data = await _blobService.GetBlobAsync(blobFile);
return File(blobFileContent.Content, "application/octet-stream", blobFile.Name + blobFile.Extension);
}
catch (Exception e)
{
// Return Bad Request If There Is Any Error
return BadRequest(e);
}
}
[HttpGet("[action]/{notebookID}/{version}")]
public async Task<IActionResult> DownloadNotebook([FromRoute] int notebookID, [FromRoute] int version)
{
try
{
// Find Project
var notebookContent = await _dbContext.NotebookContent
.FindAsync(notebookID, version);
if (notebookContent == null) return NotFound();
var notebook = await _dbContext.Notebook.FindAsync(notebookID);
if (notebook == null) return NotFound();
//BlobDownloadInfo data = await _blobService.GetNotebookAsync(notebook);
return File(notebookContent.Content, "application/octet-stream", notebook.Name + "_v" + version + notebook.Extension);
}
catch (Exception e)
{
// Return Bad Request If There Is Any Error
return BadRequest(e);
}
}
[HttpGet("[action]/{notebookID}")]
public async Task<IActionResult> GetNotebook([FromRoute] int notebookID)
{
try
{
var notebook = await _dbContext.Notebook.Include(notebook => notebook.
observableNotebookDatasets).FirstOrDefaultAsync(notebook => notebook.NotebookID == notebookID);
return Ok(new
{
message = "Notebook Retrieved",
notebook
});
}
catch (Exception e)
{
// Return Bad Request If There Is Any Error
return BadRequest(e);
}
}
[HttpGet("[action]")]
public IActionResult GetAllNotebooks()
{
var notebooks = _dbContext.Notebook
.Include(n => n.observableNotebookDatasets)
.ToList();
return Ok(new
{
result = notebooks,
message = "All notebooks retrieved"
});
}
[HttpGet("[action]/{notebookID}")]
public async Task<IActionResult> GetNotebookVersions([FromRoute] int notebookID)
{
try
{
var versions = await _dbContext.NotebookContent
.Where(n => n.NotebookID == notebookID)
.OrderByDescending(n => n.Version)
.Select(n => n.Version)
.ToListAsync();
return Ok(new
{
message = "versions for the notebook retrieved",
versions = versions
});
}
catch (Exception e)
{
// Return Bad Request If There Is Any Error
return BadRequest(e);
}
}
#endregion
#region POST REQUEST
/*
* Type : POST
* URL : /api/project/forkproject
* Param : ProjectViewModel
* Description: Fork Project
*/
[Authorize]
[HttpPost("[action]")]
public async Task<IActionResult> ForkProject([FromForm] ProjectForkVM formdata)
{
// Find User
var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (string.IsNullOrEmpty(userIdClaim) || !int.TryParse(userIdClaim, out var userId))
{
return Unauthorized(new { message = "Invalid user identifier." });
}
var user = await _dbContext.Users.SingleOrDefaultAsync(u => u.Id == userId);
if (user == null) return NotFound(new { message = "User Not Found" });
// Find Project
var project = await _dbContext.Projects.FindAsync(formdata.ProjectID);
if (project == null) return NotFound(new { message = "Project Not Found" });
// Check if the project already exists
bool projectExists = await _dbContext.Projects
.AnyAsync(p => p.ProjectUsers.Any(aup =>
aup.User.Id == userId &&
aup.Project.Name == project.Name &&
aup.UserRole == "owner"));
if (projectExists) return Conflict(new { message = "Project Already Exists" });
await using var tx = await _dbContext.Database.BeginTransactionAsync();
try
{
// 1) Create Project
var newProject = new Project
{
Name = project.Name,
Visibility = project.Visibility,
Description = project.Description,
DateCreated = DateTimeOffset.UtcNow,
LastUpdated = DateTimeOffset.UtcNow,
Route = user.UserName + "/" + project.Name,
ForkedFromProjectID = project.ProjectID,
};
await _dbContext.Projects.AddAsync(newProject);
await _dbContext.SaveChangesAsync();
// 2) Add ProjectUser (owner)
await _dbContext.AddAsync(new ProjectUser
{
UserID = user.Id,
ProjectID = newProject.ProjectID,
UserRole = "owner",
IsFollowing = true
});
await _dbContext.SaveChangesAsync();
// Maps old blob ids with new blob ids
var blobFileIdMap = new Dictionary<int, int>();
// 3) Add BlobFiles
if (formdata.BlobFilesID != null && formdata.BlobFilesID.Length > 0)
{
for (int i = 0; i < formdata.BlobFilesID.Length; i++)
{
var file = await _dbContext.BlobFiles.FindAsync(formdata.BlobFilesID[i]);
if (file == null) continue;
var newBlobFile = new BlobFile
{
Container = file.Container,
Directory = file.Directory,
Name = file.Name,
Extension = file.Extension,
Size = file.Size,
Uri = file.Uri,
DateCreated = DateTimeOffset.UtcNow,
LastModified = DateTimeOffset.UtcNow,
User = user,
UserID = user.Id,
Project = newProject,
ProjectID = newProject.ProjectID,
};
await _dbContext.BlobFiles.AddAsync(newBlobFile);
await _dbContext.SaveChangesAsync();
// Link blob ids
blobFileIdMap[file.BlobFileID] = newBlobFile.BlobFileID;
var oldBlobFileContent = await _dbContext.BlobFileContent.FindAsync(file.BlobFileID);
if(oldBlobFileContent != null)
{
await _dbContext.BlobFileContent.AddAsync(new BlobFileContent
{
BlobFileID = newBlobFile.BlobFileID,
Content = oldBlobFileContent.Content
});
await _dbContext.SaveChangesAsync();
}
}
}
// 4) Clone Notebooks + Contents + ObservableNotebookDataset
var sourceNotebooks = await _dbContext.Notebook
.Where(n => n.ProjectID == project.ProjectID)
.Include(n => n.NotebookContents)
.Include(n => n.observableNotebookDatasets)
.ToListAsync();
foreach (var oldNotebook in sourceNotebooks)
{
var newNotebook = new Notebook
{
ProjectID = newProject.ProjectID,
Project = newProject,
Name = oldNotebook.Name,
Directory = oldNotebook.Directory,
Extension = oldNotebook.Extension,
Container = "notebook-" + newProject.Name.ToLower(),
Route = user.UserName + "/" + newProject.Name,
Uri = oldNotebook.Uri,
Size = oldNotebook.Size,
DateCreated = DateTimeOffset.UtcNow,
LastModified = DateTimeOffset.UtcNow,
type = oldNotebook.type
};
await _dbContext.Notebook.AddAsync(newNotebook);
await _dbContext.SaveChangesAsync();
// Copy versions
if (oldNotebook.NotebookContents != null && oldNotebook.NotebookContents.Count > 0)
{
foreach (var oldContent in oldNotebook.NotebookContents)
{
await _dbContext.NotebookContent.AddAsync(new NotebookContent
{
NotebookID = newNotebook.NotebookID,
Version = oldContent.Version,
Content = oldContent.Content,
Author = oldContent.Author,
Size = oldContent.Size,
DateCreated = oldContent.DateCreated
});
}
}
// Copy observable dataset links
if (oldNotebook.observableNotebookDatasets != null && oldNotebook.observableNotebookDatasets.Count > 0)
{
foreach (var oldObs in oldNotebook.observableNotebookDatasets)
{
// Checks if map includes blob copy
// if not, do not create row
if(!blobFileIdMap.TryGetValue(oldObs.BlobFileID, out var newBlobFileId))
{
continue;
}
await _dbContext.ObservableNotebookDataset.AddAsync(new ObservableNotebookDataset
{
NotebookID = newNotebook.NotebookID,
datasetName = oldObs.datasetName,
datasetURL = oldObs.datasetURL,
BlobFileID = newBlobFileId
});
}
}
await _dbContext.SaveChangesAsync();
}
await tx.CommitAsync();
return Ok(new
{
result = newProject,
message = "Project Successfully Forked"
});
}
catch (Exception ex)
{
await tx.RollbackAsync();
Console.WriteLine(ex);
return BadRequest(new
{
message = "Fork failed",
detail = ex.Message
});
}
}
/*
* Type : POST
* URL : /api/project/forkprojectwithoutblob
* Param : ProjectViewModel
* Description: Fork Project Without Blob
*/
[Authorize]
[HttpPost("[action]")]
public async Task<IActionResult> ForkProjectWithoutBlob([FromForm] ProjectForkVM formdata)
{
// Find User
var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (string.IsNullOrEmpty(userIdClaim) || !int.TryParse(userIdClaim, out var userId))
{
return Unauthorized(new { message = "Invalid user identifier." });
}
var user = await _dbContext.Users.SingleOrDefaultAsync(u => u.Id == userId);
if (user == null) return NotFound(new { message = "User Not Found" });
// Find Project
var project = await _dbContext.Projects.FindAsync(formdata.ProjectID);
if (project == null) return NotFound(new { message = "Project Not Found" });
// Check if the project already exists
bool projectExists = await _dbContext.Projects
.AnyAsync(p => p.ProjectUsers.Any(aup =>
aup.User.Id == userId &&
aup.Project.Name == project.Name &&
aup.UserRole == "owner"));
// If the project exists, return a conflict response
if (projectExists) return Conflict(new { message = "Project Already Exists" });
await using var tx = await _dbContext.Database.BeginTransactionAsync();
try
{
// 1) Create forked Project
var newProject = new Project
{
Name = project.Name,
Visibility = project.Visibility,
Description = project.Description,
DateCreated = DateTimeOffset.UtcNow,
LastUpdated = DateTimeOffset.UtcNow,
Route = user.UserName + "/" + project.Name,
ForkedFromProjectID = project.ProjectID,
};
// Add Project And Save Change
await _dbContext.Projects.AddAsync(newProject);
await _dbContext.SaveChangesAsync();
// 2) Add owner
await _dbContext.AddAsync(new ProjectUser
{
UserID = user.Id,
ProjectID = newProject.ProjectID,
UserRole = "owner",
IsFollowing = true
});
await _dbContext.SaveChangesAsync();
// 3) Clone Notebooks + Contents + ObservableNotebookDataset
var sourceNotebooks = await _dbContext.Notebook
.Where(n => n.ProjectID == project.ProjectID)
.Include(n => n.NotebookContents)
.Include(n => n.observableNotebookDatasets)
.ToListAsync();
foreach (var oldNotebook in sourceNotebooks)
{
var newNotebook = new Notebook
{
ProjectID = newProject.ProjectID,
Project = newProject,
Name = oldNotebook.Name,
Directory = oldNotebook.Directory,
Extension = oldNotebook.Extension,
Container = "notebook-" + newProject.Name.ToLower(),
Route = user.UserName + "/" + newProject.Name,
Uri = oldNotebook.Uri,
Size = oldNotebook.Size,
DateCreated = DateTimeOffset.UtcNow,
LastModified = DateTimeOffset.UtcNow,
type = oldNotebook.type
};
await _dbContext.Notebook.AddAsync(newNotebook);
await _dbContext.SaveChangesAsync();
// Copy versions
if (oldNotebook.NotebookContents != null && oldNotebook.NotebookContents.Count > 0)
{
foreach (var oldContent in oldNotebook.NotebookContents)
{
await _dbContext.NotebookContent.AddAsync(new NotebookContent
{
NotebookID = newNotebook.NotebookID,
Version = oldContent.Version,
Content = oldContent.Content,
Author = oldContent.Author,
Size = oldContent.Size,
DateCreated = oldContent.DateCreated
});
}
}
// Do not copy observable dataset links
// this fork mode does not copy blob files.
await _dbContext.SaveChangesAsync();
}
await tx.CommitAsync();
return Ok(new
{
result = newProject,
message = "Project Successfully Forked"
});
}
catch (Exception ex)
{
await tx.RollbackAsync();
Console.WriteLine(ex);
return BadRequest(new
{
message = "Fork failed",
detail = ex.Message
});
}
}
/*
* Type : POST
* URL : /api/project/createproject
* Param : ProjectViewModel
* Description: Create Project
*/
[Authorize]
[HttpPost("[action]")]
public async Task<IActionResult> CreateProject([FromForm] ProjectVM formdata)
{
// Find User
var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (string.IsNullOrEmpty(userIdClaim) || !int.TryParse(userIdClaim, out var userId))
{
return Unauthorized(new { message = "Invalid user identifier." });
}
var user = await _dbContext.Users.SingleOrDefaultAsync(u => u.Id == userId);
//var user = await _dbContext.Users.FindAsync(userId);
if (user == null) return NotFound(new { message = "User Not Found" });
// Check if the project already exists
bool projectExists = await _dbContext.Projects
.AnyAsync(p => p.ProjectUsers.Any(aup =>
aup.UserID == userId &&
aup.Project.Name == formdata.Name &&
aup.UserRole == "owner"));
// If the project exists, return a conflict response
if (projectExists) return Conflict(new { message = "Project Already Exists" });
// Create Project
var newProject = new Project
{
Name = formdata.Name,
Visibility = formdata.Visibility,
Description = formdata.Description,
DateCreated = DateTimeOffset.UtcNow,
LastUpdated = DateTimeOffset.UtcNow,
Route = user.UserName + "/" + formdata.Name
};
// Add Project And Save Change
await _dbContext.Projects.AddAsync(newProject);
await _dbContext.SaveChangesAsync();
// Add ProjectUser And Save Change
await _dbContext.AddAsync(
new ProjectUser
{
UserID = user.Id,
ProjectID = newProject.ProjectID,
UserRole = "owner",
IsFollowing = true
}
);
await _dbContext.SaveChangesAsync();
// Check If Default Tag Exist
Tag tagUserName = _dbContext.Tag.SingleOrDefault(t => t.Name == user.UserName);
Tag tagProjectName = _dbContext.Tag.SingleOrDefault(t => t.Name == formdata.Name);
// Create Username Tag If Not Found
if (tagUserName == null)
{
tagUserName = new Tag { Name = user.UserName };
// Add Tag And Save Change
await _dbContext.Tag.AddAsync(tagUserName);
await _dbContext.SaveChangesAsync();
}
// Create Project Name Tag If Not Found
if (tagProjectName == null)
{
tagProjectName = new Tag { Name = formdata.Name };
// Add Tag And Save Change
await _dbContext.Tag.AddAsync(tagProjectName);
await _dbContext.SaveChangesAsync();
}
// Add Both Tag To Project
await _dbContext.ProjectTags.AddRangeAsync(
new ProjectTag
{
ProjectID = newProject.ProjectID,
TagID = tagUserName.TagID
},
new ProjectTag
{
ProjectID = newProject.ProjectID,
TagID = tagProjectName.TagID
}
);
// Save Changes
await _dbContext.SaveChangesAsync();
//uploading a readme file
var readmeContent = new
{
cells = new[]
{
new
{
cell_type = "markdown",
metadata = new { },
source = new[] { $"# Hello, this is Readme file of {formdata.Name}" }
}
},
metadata = new { },
nbformat = 4,
nbformat_minor = 2
};
var readmeJson = System.Text.Json.JsonSerializer.Serialize(readmeContent);
var readmeFileContent = System.Text.Encoding.UTF8.GetBytes(readmeJson);
Notebook readmeNotebook = new Notebook
{
Container = "notebook-" + newProject.Name.ToLower(),
Name = "readme",
Directory = "notebook/",
Extension = ".ipynb",
Uri = "",
Size = readmeFileContent.Length,
DateCreated = DateTime.UtcNow,
LastModified = DateTime.UtcNow,
ProjectID = newProject.ProjectID,
type = "new",
Route = user.UserName + "/" + newProject.Name
};
await _dbContext.Notebook.AddAsync(readmeNotebook);
await _dbContext.SaveChangesAsync();
NotebookContent readmeNotebookContent = new NotebookContent
{
NotebookID = readmeNotebook.NotebookID,
Version = 1,
Content = readmeFileContent,
Author = "hello",
Size = readmeFileContent.Length,
DateCreated = DateTime.UtcNow
};
await _dbContext.NotebookContent.AddAsync(readmeNotebookContent);
await _dbContext.SaveChangesAsync();
// Return Ok Request
return Ok(new
{
result = newProject,
message = "Project Successfully Created"
});
}
/*
* Type : POST
* URL : /api/project/adduser
* Param : ProjectUserViewModel
* Description: Add User To Project
*/
[Authorize]
[HttpPost("[action]")]
public async Task<IActionResult> AddUser([FromForm] ProjectUserVM formdata)
{
// Find User
var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (string.IsNullOrEmpty(userIdClaim) || !int.TryParse(userIdClaim, out var userId))
{
return Unauthorized(new { message = "Invalid user identifier." });
}
var user = await _dbContext.Users.SingleOrDefaultAsync(u => u.Id == userId);
if (user == null) return NotFound(new { message = "User Not Found" });
bool isOwner = await _dbContext.Projects
.AnyAsync(p => p.ProjectUsers.Any(aup =>
aup.User.Id == user.Id &&
aup.Project.ProjectID == formdata.ProjectID &&
aup.UserRole == "owner"));
if (!isOwner) return Unauthorized(new { message = "You are not the owner of the project" });
// Find Tag In Database
var projectUser = _dbContext.ProjectUsers.Find(formdata.UserID, formdata.ProjectID);
// Update Project User If Exist
if (projectUser != null)
{
// If Project User Is Not Follower Return Error
if (projectUser.UserRole != "follower") return Conflict(new { result = formdata, message = "Project User Already Exist" });
// Add Tag To Project
projectUser.UserRole = formdata.UserRole;
await _dbContext.SaveChangesAsync();
_dbContext.Entry(projectUser).Reference(pu => pu.User).Load();
// Return Ok Status
return Ok(new
{
result = projectUser,
message = "Project User Successfully Updated"
});
}
// Create Many To Many Connection
projectUser = new ProjectUser
{
ProjectID = formdata.ProjectID,
UserID = formdata.UserID,
UserRole = formdata.UserRole,
IsFollowing = formdata.IsFollowing
};
// Add To Database And Save Change
await _dbContext.ProjectUsers.AddAsync(projectUser);
await _dbContext.SaveChangesAsync();
_dbContext.Entry(projectUser).Reference(pu => pu.User).Load();
// Return Ok Status
return Ok(new
{
result = projectUser,
message = "Project User Successfully Created"
});
}
/*
* Type : POST
* URL : /api/project/addtag
* Param : ProjectTagViewModel
* Description: Add Tag To Project
*/
[HttpPost("[action]")]
[Authorize]
public async Task<IActionResult> AddTag([FromForm] ProjectTagVM formdata)
{
// Find User
var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (string.IsNullOrEmpty(userIdClaim) || !int.TryParse(userIdClaim, out var userId))
{
return Unauthorized(new { message = "Invalid user identifier." });
}
var user = await _dbContext.Users.SingleOrDefaultAsync(u => u.Id == userId);
if (user == null) return NotFound(new { message = "User Not Found" });
bool isOwner = await _dbContext.Projects
.AnyAsync(p => p.ProjectUsers.Any(aup =>
aup.User.Id == user.Id &&
aup.Project.ProjectID == formdata.ProjectID &&
aup.UserRole == "owner"));
if (!isOwner)
{
return Unauthorized(new { message = "You are not the owner of the project" });
}
// Find Tag In Database
Tag tag = _dbContext.Tag.SingleOrDefault(t => t.Name == formdata.TagName);
if (tag == null)
{
// Create Tag
tag = new Tag
{
Name = formdata.TagName,
};
// Add Tag To Database
await _dbContext.Tag.AddAsync(tag);
await _dbContext.SaveChangesAsync();
}
// Find ProjectTag In Database
ProjectTag projectTag = _dbContext.ProjectTags.SingleOrDefault(pt => pt.ProjectID == formdata.ProjectID && pt.TagID == tag.TagID);
if (projectTag != null) return Conflict(new { message = "Project Tag Already Exist" });
// Add Project Tag To Project
projectTag = new ProjectTag
{
ProjectID = formdata.ProjectID,
TagID = tag.TagID
};
// Add Tag to Project And Save
await _dbContext.ProjectTags.AddAsync(projectTag);
await _dbContext.SaveChangesAsync();
// Return Ok Status
return Ok(new
{
result = projectTag,
message = "Project Tag Added"
});
}
/*
* Type : POST
* URL : /api/project/uploadfile
* Param : FileUploadProjectViewModel
* Description: Upload file to Azure Storage
*/
[Authorize]
[HttpPost("[action]")]
public async Task<IActionResult> UploadFile([FromForm] ProjectFileUploadVM formdata)
{
try
{
// Find User
var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (string.IsNullOrEmpty(userIdClaim) || !int.TryParse(userIdClaim, out var userId))
{
return Unauthorized(new { message = "Invalid user identifier." });
}
var user = await _dbContext.Users.SingleOrDefaultAsync(u => u.Id == userId);