Esempio n. 1
0
        public async Task <DownloadableFile> DownloadPreview(string caffFileId)
        {
            CaffFile caffFile = FindExistingCaffFile(caffFileId);

            if (!File.Exists(caffFile.FilePath))
            {
                throw new Exception("This caff file dosen't exists on the server!");
            }

            var tempPath    = CreateTempDecriptedFile(caffFile);
            var previewData = RunNativeComponent(tempPath);

            File.Delete(tempPath);

            previewData = previewData.Replace('\\', '/');
            var preview = JsonConvert.DeserializeObject <PreviewModel>(previewData);

            var memory = new MemoryStream();

            using (var stream = new FileStream(preview.PreviewPath, FileMode.Open))
            {
                await stream.CopyToAsync(memory);
            }
            memory.Position = 0;

            return(new DownloadableFile()
            {
                Memory = memory,
                FilePath = preview.PreviewPath
            });
        }
Esempio n. 2
0
        /// <summary>
        /// Prepares the chosen caff file for editing
        /// </summary>
        /// <param name="id">The ID of the chonsen file</param>
        /// <returns></returns>
        public IActionResult Edit(int?id)
        {
            _logger.LogInformation("User : "******"  Action: The /Edit page has been accessed.");

            if (id == null)
            {
                return(NotFound());
            }

            CaffFile caffFileToEdit = GetCaffFile(id);

            if (caffFileToEdit == null)
            {
                return(NotFound());
            }

            var isAuthorized = _authorizationService.AuthorizeAsync(User, caffFileToEdit, CaffFileOperations.Update);

            if (!isAuthorized.Result.Succeeded)
            {
                _logger.LogInformation("User : "******"  Action: The /Edit page hasn't been accessed because the user does not have the right to do so.");

                return(Unauthorized());
            }
            return(View(caffFileToEdit));
        }
Esempio n. 3
0
        public async Task <string> UpdateCaffFile(CaffFile updatedCaffFile, string askingUserId)
        {
            var askingUser = await userManager.FindByIdAsync(askingUserId);

            if (!hasAccessToCaffFile(updatedCaffFile.Id, askingUser))
            {
                throw new Exception("You have no access to this caff file!");
            }
            CaffFile oldCaffFile = FindExistingCaffFile(updatedCaffFile.Id);

            updatedCaffFile.FilePath     = oldCaffFile.FilePath;
            updatedCaffFile.Owner        = oldCaffFile.Owner;
            updatedCaffFile.AesKey       = oldCaffFile.AesKey;
            updatedCaffFile.CreationDate = oldCaffFile.CreationDate;
            updatedCaffFile.Comments.Where(c => !oldCaffFile.Comments.Any(oc => oc.Text == c.Text))
            .ToList()
            .ForEach(c => { c.CreationDate = DateTime.Now; });
            updatedCaffFile.Comments.Where(c => !oldCaffFile.Comments.Any(oc => oc.Text == c.Text))
            .ToList()
            .ForEach(c => { c.Owner = askingUserId; });
            updatedCaffFile.Comments.Where(c => oldCaffFile.Comments.Any(oc => oc.Text == c.Text))
            .ToList()
            .ForEach(c => { c.Owner = oldCaffFile.Comments.Find(oc => oc.Id == c.Id).Owner; });
            if (caffFileRepository.Update(updatedCaffFile))
            {
                return(updatedCaffFile.Id);
            }

            throw new Exception("Couldn't update this caff file!");
        }
Esempio n. 4
0
        public async Task <string> UpdateComment(Comment updatedComment, string parentCaffId, string askingUserId)
        {
            var askingUser = await userManager.FindByIdAsync(askingUserId);

            if (!hasAccessToComment(parentCaffId, updatedComment.Id, askingUser))
            {
                throw new Exception("You have no access to this comment!");
            }
            CaffFile parentCaffFile = FindExistingCaffFile(parentCaffId);

            Comment oldComment = parentCaffFile.Comments.Find(c => c.Id == updatedComment.Id);

            if (oldComment == null)
            {
                throw new Exception("Couldn't find the comment to update!");
            }
            updatedComment.Owner        = oldComment.Owner;
            updatedComment.CreationDate = DateTime.Now;
            parentCaffFile.Comments.Remove(oldComment);
            parentCaffFile.Comments.Add(updatedComment);

            if (caffFileRepository.Update(parentCaffFile))
            {
                return(updatedComment.Id);
            }

            throw new Exception("Couldn't update the caff file!");
        }
Esempio n. 5
0
        public async Task <string> DeleteComment(string commentId, string parentCaffId, string askingUserId)
        {
            var askingUser = await userManager.FindByIdAsync(askingUserId);

            if (!hasAccessToCaffFile(parentCaffId, askingUser) && !hasAccessToComment(parentCaffId, commentId, askingUser))
            {
                throw new Exception("You have no access to this comment!");
            }
            CaffFile parentCaffFile = FindExistingCaffFile(parentCaffId);

            Comment oldComment = parentCaffFile.Comments.Find(c => c.Id == commentId);

            if (oldComment == null)
            {
                throw new Exception("Couldn't find the comment to delete!");
            }
            parentCaffFile.Comments.Remove(oldComment);

            if (caffFileRepository.Update(parentCaffFile))
            {
                return(commentId);
            }

            throw new Exception("Couldn't update the caff file!");
        }
Esempio n. 6
0
        public async Task <IActionResult> Edit(CaffFile editedCaffFile)
        {
            var originalCaffFile = GetCaffFile(editedCaffFile.Id);

            if (ModelState.IsValid)
            {
                if (originalCaffFile == null)
                {
                    return(NotFound());
                }

                var isAuthorized = _authorizationService.AuthorizeAsync(User, originalCaffFile, CaffFileOperations.Update);
                if (!isAuthorized.Result.Succeeded)
                {
                    return(Unauthorized());
                }

                originalCaffFile.Comment = editedCaffFile.Comment;
                await _context.SaveChangesAsync();

                _logger.LogInformation("User : "******"  Action: The file " + originalCaffFile.Path + " has been modified successfully.");
                return(RedirectToAction("Index"));
            }
            // var originalCaffFile = GetCaffFile(editedCaffFile.Id);
            _logger.LogInformation("User : "******"  Action: The file " + originalCaffFile.Path + " hasn't been modified successfully.");
            return(View(editedCaffFile));
        }
Esempio n. 7
0
        public async Task DeleteFileAsync(Guid fileId)
        {
            var fileEntity = await _context
                             .Files
                             .FindAsync(fileId);

            if (fileEntity == null)
            {
                return;
            }

            var blobContainerClient = fileEntity switch
            {
                CaffFile _ => _caffBlobContainerClient,
                PreviewFile _ => _previewBlobContainerClient,
                _ => throw new InvalidOperationException()
            };

            var blobName   = GetBlobName(fileEntity);
            var blobClient = blobContainerClient.GetBlobClient(blobName);

            await blobClient.DeleteIfExistsAsync();

            _context.Files.Remove(fileEntity);

            await _context.SaveChangesAsync();
        }
Esempio n. 8
0
        public async Task <FileDto> GetFileAsync(Guid fileId)
        {
            var fileEntity = await _context
                             .Files
                             .FindAsync(fileId);

            if (fileEntity == null)
            {
                throw new CaffStoreNotFoundException("File not found");
            }

            var blobName = GetBlobName(fileEntity);

            var blobContainerClient = fileEntity switch
            {
                CaffFile _ => _caffBlobContainerClient,
                PreviewFile _ => _previewBlobContainerClient,
                _ => throw new InvalidOperationException()
            };

            var blobClient = blobContainerClient.GetBlobClient(blobName);

            var uri = fileEntity switch
            {
                CaffFile _ => GenerateSasUri(blobClient.Uri),
                PreviewFile _ => blobClient.Uri,
                _ => throw new InvalidOperationException()
            };

            return(new FileDto
            {
                Id = fileEntity.Id,
                FileUri = uri
            });
        }
Esempio n. 9
0
        private string CreateTempDecriptedFile(CaffFile caffFile)
        {
            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = caffFile.AesKey.Key;
                aesAlg.IV  = caffFile.AesKey.IV;

                aesAlg.Mode = CipherMode.CBC;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                var pathToSave             = Path.Combine(Directory.GetCurrentDirectory(), "Resources", "Temp");
                var tempPath = Path.Combine(pathToSave, caffFile.Id + ".temp");

                using (var stream = new FileStream(caffFile.FilePath, FileMode.Open))
                {
                    using (var csDecrypt = new CryptoStream(stream, decryptor, CryptoStreamMode.Read))
                    {
                        using (var outStream = new FileStream(tempPath, FileMode.Create))
                        {
                            csDecrypt.CopyTo(outStream);
                        }
                    }
                }

                return(tempPath);
            }
            throw new Exception("Couldn't decrypt file!");
        }
Esempio n. 10
0
        private CaffFile FindExistingCaffFile(string caffFileId)
        {
            CaffFile caffFile = caffFileRepository.Find(caffFileId);

            if (caffFile == null)
            {
                throw new Exception("Couldn't find the requested caff file!");
            }
            return(caffFile);
        }
Esempio n. 11
0
 public FileModel(CaffFile file)
 {
     this.Id           = file.Id;
     this.Title        = file.Title;
     this.Description  = file.Description;
     this.OwnerName    = file.Owner.UserName;
     this.FileComments = file.FileComments
                         .Select(fc => new FileCommentModel(fc))
                         .ToList();
 }
Esempio n. 12
0
        public Comment GetComment(string commentId, string parentCaffId)
        {
            CaffFile parentCaffFile = FindExistingCaffFile(parentCaffId);

            Comment requestedComment = parentCaffFile.Comments.Find(c => c.Id == commentId);

            if (requestedComment == null)
            {
                throw new Exception("Couldn't find the requested comment!");
            }
            return(requestedComment);
        }
Esempio n. 13
0
        public string CreateNewComment(Comment newComment, string parentCaffId, string askingUserId)
        {
            CaffFile parentCaffFile = FindExistingCaffFile(parentCaffId);

            newComment.Id           = ObjectId.GenerateNewId().ToString();
            newComment.Owner        = askingUserId;
            newComment.CreationDate = DateTime.Now;
            parentCaffFile.Comments.Add(newComment);
            if (caffFileRepository.Update(parentCaffFile))
            {
                return(newComment.Id);
            }
            throw new Exception("Couldn't add the comment to the caff file!");
        }
Esempio n. 14
0
        public async Task <IActionResult> Create(CaffFileViewModel caff)
        {
            if (ModelState.IsValid)
            {
                CaffFile newCaffFile = new CaffFile
                {
                    UserId  = int.Parse(_userManager.GetUserId(User)),
                    Comment = caff.Comment
                };

                var isAuthorized = await _authorizationService.AuthorizeAsync(
                    User, newCaffFile,
                    CaffFileOperations.Create);

                if (!isAuthorized.Succeeded)
                {
                    return(Unauthorized());
                }

                if (caff.Content != null)
                {
                    // TODO: Add the file uploader function here that returns the path of the uploaded CAFF file
                    var verified = await VerifyAndUploadCaffFileAsync(caff.Content);


                    if (verified == null)
                    {
                        return(View("Error"));
                    }
                    var caffPath  = verified[0];
                    var imagePath = verified[2];

                    newCaffFile.Path      = caffPath;
                    newCaffFile.ImagePath = imagePath;
                    _context.CaffFiles.Add(newCaffFile);

                    await _context.SaveChangesAsync();

                    _logger.LogInformation("User : "******"  Action: Uploaded a new CAFF. CaffPath: " + caffPath);
                    _logger.LogInformation("User : "******"  Action: Uploaded a new CAFF. ImagePath: " + imagePath);
                }

                return(RedirectToAction(nameof(Index)));
            }
            _logger.LogInformation("User : "******"  Action: The model is invalid.");

            return(View(caff));
        }
Esempio n. 15
0
        public async Task <NewFileModel> UploadFile(NewFileModel newFile)
        {
            var caffUri      = SaveCaffFile(newFile);
            var thumbnailUri = GenerateThumbnail(newFile, caffUri);
            var newEntity    = new CaffFile
            {
                CAFFUri      = caffUri,
                ThumbnailUri = thumbnailUri,
                Title        = newFile.Title,
                Description  = newFile.Description,
                OwnerId      = UserManager.GetUserId()
            };

            Context.Files.Add(newEntity);
            await Context.SaveChangesAsync();

            return(newFile);
        }
Esempio n. 16
0
        public async Task <string> DeleteCaffFile(string caffFileId, string askingUserId)
        {
            var askingUser = await userManager.FindByIdAsync(askingUserId);

            if (!hasAccessToCaffFile(caffFileId, askingUser))
            {
                throw new Exception("You have no access to this caff file!");
            }
            CaffFile caffFile = caffFileRepository.Find(caffFileId);

            if (caffFile.FilePath != null)
            {
                File.Delete(caffFile.FilePath);
            }
            if (caffFileRepository.Delete(caffFileId))
            {
                return(caffFileId);
            }

            throw new Exception("Couldn't delete this caff file!");
        }
Esempio n. 17
0
        public async Task <DownloadableFile> DownloadCaffFile(string caffFileId)
        {
            CaffFile caffFile = FindExistingCaffFile(caffFileId);

            if (!File.Exists(caffFile.FilePath))
            {
                throw new Exception("This caff file dosen't exists on the server!");
            }

            var memory = new MemoryStream();

            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = caffFile.AesKey.Key;
                aesAlg.IV  = caffFile.AesKey.IV;

                aesAlg.Mode = CipherMode.CBC;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                using (var stream = new FileStream(caffFile.FilePath, FileMode.Open))
                {
                    using (var csDecrypt = new CryptoStream(stream, decryptor, CryptoStreamMode.Read))
                    {
                        await csDecrypt.CopyToAsync(memory);
                    }
                }
                memory.Position = 0;
            }

            return(new DownloadableFile()
            {
                Memory = memory,
                FilePath = caffFile.FilePath
            });
        }
Esempio n. 18
0
        public string CreateNewCaffFile(CaffFile newCaffFile, string askingUserId)
        {
            var id = ObjectId.GenerateNewId().ToString();

            newCaffFile.Id           = id;
            newCaffFile.Owner        = askingUserId;
            newCaffFile.CreationDate = DateTime.Now;

            newCaffFile.Comments.ForEach(c =>
            {
                c.Id           = ObjectId.GenerateNewId().ToString();
                c.CreationDate = newCaffFile.CreationDate;
                c.Owner        = askingUserId;
            });

            if (caffFileRepository.Create(newCaffFile))
            {
                return(id);
            }
            else
            {
                throw new Exception("Couldn't create a new caff file!");
            }
        }
Esempio n. 19
0
        public string UploadCaffFile(string caffId, IFormFile file)
        {
            CaffFile caffFile   = FindExistingCaffFile(caffId);
            var      folderName = Path.Combine("Resources", "CAFFFiles");

            folderName = Path.Combine(folderName, caffFile.Owner);
            if (!Directory.Exists(folderName))
            {
                Directory.CreateDirectory(folderName);
            }

            using (var random = new RNGCryptoServiceProvider())
            {
                var key = new byte[16];
                random.GetBytes(key);

                byte[] IV;

                using (Aes aesAlg = Aes.Create())
                {
                    aesAlg.Key = key;

                    aesAlg.GenerateIV();
                    IV = aesAlg.IV;

                    aesAlg.Mode = CipherMode.CBC;

                    var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);


                    var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);
                    if (file.Length > 0)
                    {
                        var fileName = caffFile.Id + "_" + ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                        var fullPath = Path.Combine(pathToSave, fileName);
                        using (var stream = new FileStream(fullPath, FileMode.Create))
                        {
                            using (var csEncrypt = new CryptoStream(stream, encryptor, CryptoStreamMode.Write))
                            {
                                file.CopyTo(csEncrypt);
                            }
                        }
                        caffFile.FilePath = fullPath;
                        caffFile.AesKey   = new AesEncryptingModel()
                        {
                            Key = key,
                            IV  = IV
                        };
                    }
                    else
                    {
                        throw new Exception("File was empty!");
                    }

                    if (caffFileRepository.Update(caffFile))
                    {
                        return(caffId);
                    }
                    throw new Exception("Couldn't save the filepath of the uploaded file!");
                }
            }
        }
Esempio n. 20
0
        public IEnumerable <Comment> GetCommentsOfCaffFile(string parentCaffId)
        {
            CaffFile parentCaffFile = FindExistingCaffFile(parentCaffId);

            return(parentCaffFile.Comments);
        }