Example #1
0
        public Models.File GetFileInfo(string filePath)
        {
            FileInfo f = new FileInfo(filePath);

            Models.File file = new Models.File();

            file.FileName     = f.Name;
            file.FileLocation = f.FullName;
            file.FileSize     = f.Length.ToString();
            file.FileType     = Path.GetExtension(filePath);

            return(file);
        }
Example #2
0
        public void SendFile(Models.File file, Component comp)
        {
            communication com = new communication();
            CosmosObject  cos = new CosmosObject();

            cos.CommandType         = 9;
            cos.DestinationIPAdress = comp.Address;
            cos.DestinationQueue    = "cosmos";
            cos.SourceQueue         = com.generateID(8);
            cos.SourceIPAddress     = com.knowLocalIp().ToString();
            cos.Payload             = (object)file;
            com.send(cos);
        }
Example #3
0
        public async Task <IActionResult> DeleteSingleFile(int fileId)
        {
            File file = await fileService.FindAsync(fileId);

            User user = await HttpContext.GetContextUser(userService)
                        .ConfigureAwait(false);

            if (file == null)
            {
                ProblemDetails problem = new ProblemDetails
                {
                    Title    = "File was not found.",
                    Detail   = "File was not found.",
                    Instance = "9D3830A2-E7D1-4610-A147-1D43BFB8DDBC"
                };
                return(NotFound(problem));
            }

            bool isAllowed = userService.UserHasScope(user.IdentityId, nameof(Defaults.Scopes.FileWrite));

            if (!(file.Uploader.Id.Equals(user.Id) || isAllowed))
            {
                ProblemDetails problem = new ProblemDetails
                {
                    Title    = "Not authorized.",
                    Detail   = "You do not have the required permissions to delete this file.",
                    Instance = "88967A6F-B168-44E2-A8E7-E9EBD555940E"
                };
                return(Unauthorized(problem));
            }

            try
            {
                await fileService.RemoveAsync(fileId)
                .ConfigureAwait(false);

                fileService.Save();
                fileUploader.DeleteFileFromDirectory(file);
                return(Ok());
            } catch (FileNotFoundException)
            {
                ProblemDetails problem = new ProblemDetails
                {
                    Title    = "File could not be deleted because the path does not exist.",
                    Detail   = "File could not be found.",
                    Instance = "436349B4-50D9-49FD-8618-82367BEB7941"
                };

                return(NotFound(problem));
            }
        }
Example #4
0
        public async Task <ActionResult <Models.File> > AddFile([FromBody] Models.File file)
        {
            try
            {
                await _context.Files.AddAsync(file);

                await _context.SaveChangesAsync();

                file.NoteBook = null;
                return(file);
            }
            catch
            {
                return(Problem("Error In Save Video Task"));
            }
        }
Example #5
0
        public async Task <IActionResult> GetSingleFile(int fileId)
        {
            File file = await fileService.FindAsync(fileId);

            if (file == null)
            {
                ProblemDetails problem = new ProblemDetails
                {
                    Title    = "File could not be found.",
                    Detail   = "File could not be found.",
                    Instance = "875B6402-D771-45EC-AB56-3DE0CDD446D6"
                };
                return(NotFound(problem));
            }

            return(Ok(mapper.Map <File, FileResourceResult>(file)));
        }
Example #6
0
        public async Task <IActionResult> UploadSingleFile([FromForm] FileResource fileResource)
        {
            if (fileResource.File == null)
            {
                ProblemDetails problem = new ProblemDetails
                {
                    Title    = "Failed posting file.",
                    Detail   = "File is null.",
                    Instance = "ACD46F17-A239-4353-92A5-0B81AA0A96E9"
                };
                return(BadRequest(problem));
            }
            try
            {
                DateTime uploadDateTime = DateTime.Now;
                int      fileExtPos     = fileResource.File.FileName.LastIndexOf(".");
                string   extension      = fileResource.File.FileName.Substring(fileExtPos);
                string   newFileName    = Guid.NewGuid() + extension;
                User     user           = await HttpContext.GetContextUser(userService)
                                          .ConfigureAwait(false);

                File file = new File(newFileName, newFileName, user, uploadDateTime);

                await fileUploader.CopyFileToDirectory(fileResource.File, newFileName);

                await fileService.AddAsync(file);

                fileService.Save();

                return(Ok(mapper.Map <File, FileResourceResult>(file)));
            } catch (FileExistException fileExistException)
            {
                ProblemDetails problem = new ProblemDetails
                {
                    Title    = fileExistException.Message,
                    Detail   = "Please rename filename.",
                    Instance = "D902F8C6-23FF-4506-B272-C757BD709464"
                };
                return(BadRequest(problem));
            }
        }
        public File CreateDirectory()
        {
            File NewDirectory = null;

            File body = new File();
            body.Title = "E-Academy-Materials";
            body.Description = "Directory for hosting zip files of topics";
            body.MimeType = "application/vnd.google-apps.folder";
            body.Parents = new List<ParentReference>() { new ParentReference() { Id = ROOT_DIRECTORY_ID } };

            try
            {
                FilesResource.InsertRequest request = this.service.Files.Insert(body);
                NewDirectory = request.Execute();
            }

            catch (Exception e)
            {
                Console.WriteLine("An error occurred: " + e.Message);
            }

            return NewDirectory;
        }
Example #8
0
        public void SaveFile(string ownerType, int ownerID, string fileType, HttpPostedFileBase file)
        {
            var client = new RestClient(ConfigurationManager.AppSettings.Get("APIURL"));

            if (file == null || file.ContentLength == 0)
            {
                return;
            }

            var fileName      = Path.GetFileName(file.FileName);
            var fileExtension = Path.GetExtension(file.FileName);
            var fileSize      = file.ContentLength;

            if (fileType == "profilePicture" || fileType == "image")
            {
                if (!acceptedImageExtensions.Contains(fileExtension))
                {
                    return;
                }
            }
            else
            {
                if (!acceptedMusicExtensions.Contains(fileExtension))
                {
                    return;
                }
            }

            if (fileSize > maxFileSize)
            {
                return;
            }

            if (ownerType == "user")
            {
                var folder = HttpContext.Current.Server.MapPath($"~/Content/Uploads/Users/{ownerID}/");
                if (!Directory.Exists(folder))
                {
                    Directory.CreateDirectory(folder);
                }

                var path = Path.Combine(folder, fileName);

                file.SaveAs(path);

                if (fileType == "profilePicture")
                {
                    var user = new User();
                    user.ID             = ownerID;
                    user.ProfilePicture = fileName;

                    var request = new RestRequest("user/update/profilepicture", Method.PUT);
                    request.AddJsonBody(user);

                    client.Execute(request);
                }
                else
                {
                    var fileLogic = new FileLogic();
                    fileLogic.Name = fileName;

                    var user = new User();
                    user.ID    = ownerID;
                    user.Files = new List <FileLogic>();
                    user.Files.Add(fileLogic);

                    var request = new RestRequest("user/add/file", Method.POST);
                    request.AddJsonBody(user);

                    client.Execute(request);
                }
            }
        }
        public ZipFileGoogleDriveResponseModel Upload(ZipFileGoogleDriveRequestModel uploadFile)
        {
            var body = new File();
            body.Title = uploadFile.OriginalName;
            body.MimeType = "application/zip";
            body.Description = "test";

            body.Parents = new List<ParentReference> { new ParentReference() { Id = ROOT_DIRECTORY_ID } };

            var request = this.Service.Files.Insert(body, uploadFile.Content, "application/zip");
            request.Upload();

            File file = request.ResponseBody;
            var res = new ZipFileGoogleDriveResponseModel { Id = file.Id, EmbededLink = file.EmbedLink, DownloadLink = file.DownloadUrl };
            return res;
        }
Example #10
0
        public async Task <IActionResult> DeleteProject(int projectId)
        {
            Project project = await projectService.FindAsync(projectId)
                              .ConfigureAwait(false);

            if (project == null)
            {
                ProblemDetails problem = new ProblemDetails
                {
                    Title    = "Failed to delete the project.",
                    Detail   = "The project could not be found in the database.",
                    Instance = "AF63CF48-ECAA-4996-BAA0-BF52926D12AC"
                };
                return(NotFound(problem));
            }

            User user = await HttpContext.GetContextUser(userService)
                        .ConfigureAwait(false);

            bool isAllowed = await authorizationHelper.UserIsAllowed(user,
                                                                     nameof(Defaults.Scopes.ProjectWrite),
                                                                     nameof(Defaults.Scopes.InstitutionProjectWrite),
                                                                     project.UserId);

            if (!(project.UserId == user.Id || isAllowed))
            {
                ProblemDetails problem = new ProblemDetails
                {
                    Title    = "Failed to delete the project.",
                    Detail   = "The user is not allowed to delete the project.",
                    Instance = "D0363680-5B4F-40A1-B381-0A7544C70164"
                };
                return(Unauthorized(problem));
            }

            if (project.ProjectIconId.HasValue)
            {
                // We need to delete the old file.
                File fileToDelete = await fileService.FindAsync(project.ProjectIconId.Value);

                try
                {
                    // Remove the file from the database
                    await fileService.RemoveAsync(fileToDelete.Id)
                    .ConfigureAwait(false);

                    fileService.Save();

                    // Remove the file from the filesystem
                    fileUploader.DeleteFileFromDirectory(fileToDelete);
                } catch (FileNotFoundException)
                {
                    ProblemDetails problem = new ProblemDetails
                    {
                        Title    = "File could not be deleted because the path does not exist.",
                        Detail   = "File could not be found.",
                        Instance = "367594c4-1fab-47ae-beb4-a41b53c65a18"
                    };

                    return(NotFound(problem));
                }
            }

            await projectService.RemoveAsync(projectId)
            .ConfigureAwait(false);

            projectService.Save();

            return(Ok());
        }
Example #11
0
        public async Task <IActionResult> UpdateProject(int projectId, [FromBody] ProjectResource projectResource)
        {
            Project project = await projectService.FindAsync(projectId)
                              .ConfigureAwait(false);

            if (project == null)
            {
                ProblemDetails problem = new ProblemDetails
                {
                    Title    = "Failed to update project.",
                    Detail   = "The specified project could not be found in the database.",
                    Instance = "b27d3600-33b0-42a0-99aa-4b2f28ea07bb"
                };
                return(NotFound(problem));
            }

            User user = await HttpContext.GetContextUser(userService)
                        .ConfigureAwait(false);

            bool isAllowed = userService.UserHasScope(user.IdentityId, nameof(Defaults.Scopes.ProjectWrite));

            if (!(project.UserId == user.Id || isAllowed))
            {
                ProblemDetails problem = new ProblemDetails
                {
                    Title    = "Failed to edit the project.",
                    Detail   = "The user is not allowed to edit the project.",
                    Instance = "906cd8ad-b75c-4efb-9838-849f99e8026b"
                };
                return(Unauthorized(problem));
            }

            if (projectResource.CallToAction != null)
            {
                IEnumerable <CallToActionOption> callToActionOptions =
                    await callToActionOptionService.GetCallToActionOptionFromValueAsync(
                        projectResource.CallToAction.OptionValue);

                if (!callToActionOptions.Any())
                {
                    ProblemDetails problem = new ProblemDetails
                    {
                        Title  = "Call to action value was not found.",
                        Detail =
                            "The specified call to action value was not found while creating the project.",
                        Instance = "40EE82EB-930F-40C8-AE94-0041F7573FE9"
                    };
                    return(BadRequest(problem));
                }
            }

            // Upload the new file if there is one
            File file = null;

            if (projectResource.FileId != 0)
            {
                if (project.ProjectIconId != 0 && project.ProjectIconId != null)
                {
                    if (project.ProjectIconId != projectResource.FileId)
                    {
                        File fileToDelete = await fileService.FindAsync(project.ProjectIconId.Value);

                        // Remove the file from the filesystem
                        fileUploader.DeleteFileFromDirectory(fileToDelete);
                        // Remove file from DB
                        await fileService.RemoveAsync(project.ProjectIconId.Value);


                        fileService.Save();
                    }
                }

                // Get the uploaded file
                file = await fileService.FindAsync(projectResource.FileId);

                if (file != null)
                {
                    project.ProjectIcon = file;
                }
                else
                {
                    ProblemDetails problem = new ProblemDetails
                    {
                        Title    = "File was not found.",
                        Detail   = "The specified file was not found while updating project.",
                        Instance = "69166D3D-6D34-4050-BD25-71F1BEBE43D3"
                    };
                    return(BadRequest(problem));
                }
            }
            mapper.Map(projectResource, project);
            projectService.Update(project);
            projectService.Save();
            return(Ok(mapper.Map <Project, ProjectResourceResult>(project)));
        }
Example #12
0
        public async Task <IActionResult> CreateProjectAsync([FromBody] ProjectResource projectResource)
        {
            if (projectResource == null)
            {
                ProblemDetails problem = new ProblemDetails
                {
                    Title    = "Failed to create a new project.",
                    Detail   = "The specified project resource was null.",
                    Instance = "8D3D9119-0D12-4631-B2DC-56494639A849"
                };
                return(BadRequest(problem));
            }

            if (projectResource.CallToAction != null)
            {
                IEnumerable <CallToActionOption> callToActionOptions =
                    await callToActionOptionService.GetCallToActionOptionFromValueAsync(
                        projectResource.CallToAction.OptionValue);

                if (!callToActionOptions.Any())
                {
                    ProblemDetails problem = new ProblemDetails
                    {
                        Title  = "Call to action value was not found.",
                        Detail =
                            "The specified call to action value was not found while creating the project.",
                        Instance = "40EE82EB-930F-40C8-AE94-0041F7573FE9"
                    };
                    return(BadRequest(problem));
                }
            }

            Project project = mapper.Map <ProjectResource, Project>(projectResource);
            File    file    = await fileService.FindAsync(projectResource.FileId);

            if (projectResource.FileId != 0 &&
                file == null)
            {
                ProblemDetails problem = new ProblemDetails
                {
                    Title    = "File was not found.",
                    Detail   = "The specified file was not found while creating project.",
                    Instance = "8CABE64D-6B73-4C88-BBD8-B32FA9FE6EC7"
                };
                return(BadRequest(problem));
            }

            project.ProjectIcon = file;
            project.User        = await HttpContext.GetContextUser(userService)
                                  .ConfigureAwait(false);

            try
            {
                projectService.Add(project);
                projectService.Save();
                return(Created(nameof(CreateProjectAsync), mapper.Map <Project, ProjectResourceResult>(project)));
            } catch (DbUpdateException e)
            {
                Log.Logger.Error(e, "Database exception");


                ProblemDetails problem = new ProblemDetails
                {
                    Title    = "Failed to save new project.",
                    Detail   = "There was a problem while saving the project to the database.",
                    Instance = "9FEEF001-F91F-44E9-8090-6106703AB033"
                };
                return(BadRequest(problem));
            }
        }