public static string ToPath(this UploadLocationEnum location)
        {
            switch (location)
            {
            case UploadLocationEnum.Avatars:
            {
                return(UploadFolders.AvatarFolder);
            }

            case UploadLocationEnum.Articles:
            {
                return(UploadFolders.ArticleFolder);
            }

            case UploadLocationEnum.Bugs:
            {
                return(UploadFolders.BugContentFolder);
            }

            case UploadLocationEnum.Temp:
            {
                return(UploadFolders.TempFoler);
            }
            }
            throw new ArgumentException("Location does not exist!");
        }
Exemple #2
0
        public MethodResult CanUpload(HttpPostedFileBase file, UploadLocationEnum location, bool isTemporary = false)
        {
            var result = base.CanUpload(file, location);

            if (result.IsError)
            {
                return(result);
            }

            var extension = Path.GetExtension(file.FileName).Replace(".", "").ToLower();

            if (AllowedExtension.Contains(extension) == false)
            {
                return(new MethodResult("You cannot use this extension!"));
            }

            if (isTemporary == false)
            {
                result = ChackIfAvatarIsCorrectImage(file);
                if (result.IsError)
                {
                    return(result);
                }
            }

            return(MethodResult.Success);
        }
Exemple #3
0
        public string GetRelativePathForLocation(string filename, UploadLocationEnum location)
        {
            var locationPath = location.ToPath().Replace("~", "");

            //by removing ~ we will start with /content/ not ~/content/

            return(Path.Combine(locationPath, filename));
        }
Exemple #4
0
        public string GetStorePath(string uploadForlderName,
                                   UploadLocationEnum uploadLocation             = UploadLocationEnum.LocalHost,
                                   UploadLinkAccessibilityEnum linkAccessibility = UploadLinkAccessibilityEnum.Private)
        {
            UploadFolderName = uploadForlderName;
            using (var scope = Services.CreateScope())
            {
                var httpContextAccessor =
                    scope.ServiceProvider
                    .GetRequiredService <IHttpContextAccessor>();

                var context =
                    scope.ServiceProvider
                    .GetRequiredService <DataContext>();

                User user = null;

                var refreshToken = httpContextAccessor.HttpContext?.Request.Cookies["refreshToken"];

                if (refreshToken != null)
                {
                    var token = context.Tokens.SingleOrDefault(x => x.RefreshToken == refreshToken);
                    user = token != null ? token.CreatedBy : null;
                }

                var userUploadSubFolderName = user != null ? user.UserName : "******";

                if (linkAccessibility == UploadLinkAccessibilityEnum.Public)
                {
                    if (uploadLocation == UploadLocationEnum.LocalHost)
                    {
                        var relativePath = user != null?
                                           Path.Combine("wwwroot", uploadForlderName, user.UserName) :
                                               Path.Combine("wwwroot", uploadForlderName, "unknown");

                        return(relativePath);
                    }

                    if (uploadLocation == UploadLocationEnum.FtpServer)
                    {
                        var relativePath = user != null?
                                           Path.Combine("public_html", uploadForlderName, user.UserName) :
                                               Path.Combine("public_html", uploadForlderName, "unknown");

                        return(relativePath);
                    }
                }

                var storePath = Path.Combine(uploadForlderName, userUploadSubFolderName);

                return(storePath);
            }
        }
Exemple #5
0
        public virtual MethodResult CanUpload(HttpPostedFileBase file, UploadLocationEnum location)
        {
            if (file == null || file.ContentLength == 0)
            {
                return(new MethodResult("File is empty or does not exist"));
            }

            if (file.ContentLength >= 5_000_000)
            {
                return(new MethodResult("File is too big! Upload something smaller than 5MB"));
            }

            return(MethodResult.Success);
        }
Exemple #6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="location"></param>
        /// <param name="extension">Without dot</param>
        /// <returns></returns>
        public string GetUniqueFilePath(UploadLocationEnum location, string extension)
        {
            string filename = "";

            if (extension.StartsWith(".") == false)
            {
                extension = "." + extension;
            }
            do
            {
                filename  = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
                filename += extension;
                filename  = GetFilePathForLocation(filename, location);
            } while (File.Exists(filename) == true);

            return(filename);
        }
Exemple #7
0
        //
        public async Task <MemoryStream> GetImageAsync(string imageRelativePath, UploadLocationEnum uploadLocation)
        {
            if (uploadLocation == UploadLocationEnum.LocalHost)
            {
                var root = _env.ContentRootPath;
                var imageAbsolutePath = $"{root}{imageRelativePath}";
                if (File.Exists(imageAbsolutePath))
                {
                    var memory = new MemoryStream();
                    using (var stream = new FileStream(imageAbsolutePath, FileMode.Open))
                    {
                        await stream.CopyToAsync(memory);
                    }

                    memory.Position = 0;
                    return(memory);
                }
                throw new Exception("The requested image does not exist!");
            }

            if (uploadLocation == UploadLocationEnum.FtpServer)
            {
                // create an FTP client
                FtpClient client = new FtpClient(_baseUri, _port, _username, _password);
                // begin connecting to the server
                await client.ConnectAsync();

                if (await client.FileExistsAsync(imageRelativePath))
                {
                    var memory = new MemoryStream();
                    using (var stream = await client.OpenReadAsync(imageRelativePath))
                    {
                        await stream.CopyToAsync(memory);
                    }

                    memory.Position = 0;
                    // disconnect!
                    await client.DisconnectAsync();

                    return(memory);
                }
                throw new Exception("The requested image does not exist!");
            }

            throw new Exception("Problem getting the requested image!");
        }
Exemple #8
0
        //
        public async Task <string> DeleteFileAsync(string fileRelativePath, UploadLocationEnum uploadLocation)
        {
            if (uploadLocation == UploadLocationEnum.LocalHost)
            {
                var filePath = $"{_env.ContentRootPath}{fileRelativePath}";

                try
                {
                    if (File.Exists(filePath))
                    {
                        File.Delete(filePath);
                        return("ok");
                    }
                    else
                    {
                        throw new Exception("File not found!");
                    }
                }
                catch (IOException ioexception)
                {
                    throw new IOException(ioexception.Message);
                }
            }

            if (uploadLocation == UploadLocationEnum.FtpServer)
            {
                // create an FTP client
                FtpClient client = new FtpClient(_baseUri, _port, _username, _password);
                // begin connecting to the server
                await client.ConnectAsync();

                // check if a file exists
                if (await client.FileExistsAsync(fileRelativePath))
                {
                    // delete the file
                    await client.DeleteFileAsync(fileRelativePath);

                    return("ok");
                }
            }

            throw new Exception("Problem deleting the file!");
        }
Exemple #9
0
        /// <returns>Virtual path to the file with extension</returns>
        public MethodResult <string> UploadImage(HttpPostedFileBase file, UploadLocationEnum location, bool enableSizeValidation = true)
        {
            MethodResult <string> result = MethodResult <string> .Success;

            if (file == null || file.ContentLength == 0)
            {
                throw new UserReadableException("File is empty or does not exist");
            }

            var tempPath = Path.GetTempFileName();

            file.SaveAs(tempPath);

            Image img = Image.FromFile(tempPath);

            if (enableSizeValidation)
            {
                result.Merge(checkIfImageIsCorrect(img));
            }

            if (result.IsError)
            {
                return(result);
            }

            var fileName = GetUniqueFilePath(location, ".png");

            Directory.CreateDirectory(Path.GetDirectoryName(fileName));
            var imageFile = File.Create(fileName);


            img.Save(imageFile, ImageFormat.Png);
            img.Dispose();
            File.Delete(tempPath);
            imageFile.Close();


            result.ReturnValue = "\\" + fileName.Replace(HttpContext.Current.Request.ServerVariables["APPL_PHYSICAL_PATH"], string.Empty);
            return(result);
        }
Exemple #10
0
        public Upload Upload(HttpPostedFileBase file, UploadLocationEnum location, Citizen citizen)
        {
            var filePath = GetUniqueFilePath(location, ".png");

            Directory.CreateDirectory(Path.GetDirectoryName(filePath));
            file.SaveAs(filePath);

            var fileName = Path.GetFileName(filePath);
            var upload   = new Upload()
            {
                UploadedByCitizenID = citizen.ID,
                Day              = GameHelper.CurrentDay,
                Time             = DateTime.Now,
                UploadLocationID = (int)location,
                Filename         = fileName,
            };

            uploadRepository.Add(upload);
            uploadRepository.SaveChanges();

            return(upload);
        }
Exemple #11
0
        public Upload CropUploadAndMoveToAnotherLocation(Upload upload, CropRectangle crop, UploadLocationEnum newLocation)
        {
            Bitmap bitmap;
            Upload newUpload;

            using (var image = Image.FromFile(GetFilePathForLocation(upload)))
            {
                bitmap = cropImage(image, crop);
            }

            using (var resized = new Bitmap(bitmap, new Size(crop.Width, crop.Height)))
            {
                var path = GetUniqueFilePath(newLocation, Path.GetExtension(upload.Filename).Replace(".", ""));
                resized.Save(path);
                newUpload = new Entities.Upload()
                {
                    UploadedByCitizenID = upload.UploadedByCitizenID,
                    UploadLocationID    = (int)newLocation,
                    Time     = DateTime.Now,
                    Day      = GameHelper.CurrentDay,
                    Filename = Path.GetFileName(path)
                };

                uploadRepository.Add(newUpload);
                uploadRepository.SaveChanges();
            }
            bitmap.Dispose();

            return(newUpload);
        }
Exemple #12
0
        public string GetFilePathForLocation(string fileName, UploadLocationEnum location)
        {
            var locationPath = location.ToPath();

            return(Path.Combine(HttpContext.Current.Server.MapPath(locationPath), fileName));
        }
Exemple #13
0
        //
        public async Task <Stream> DownloadFileAsync(string fileRelativePath, long fileSize, UploadLocationEnum uploadLocation)
        {
            var root             = _env.ContentRootPath;
            var fileAbsolutePath = Path.Combine(root, fileRelativePath);

            if (uploadLocation == UploadLocationEnum.LocalHost)
            {
                if (File.Exists(fileAbsolutePath))
                {
                    var fileStream = new FileStream(fileAbsolutePath, FileMode.Open);
                    return(fileStream);
                }
                throw new Exception("The requested file does not exist!");
            }

            if (uploadLocation == UploadLocationEnum.FtpServer)
            {
                // create an FTP client
                FtpClient client = new FtpClient(_baseUri, _port, _username, _password);
                // begin connecting to the server
                await client.ConnectAsync();

                if (await client.FileExistsAsync(Path.Combine("public_html", fileRelativePath)))
                {
                    var stream = await client.OpenReadAsync(fileRelativePath);

                    // disconnect!
                    await client.DisconnectAsync();

                    return(stream);
                }
                throw new Exception("The requested file does not exist!");
            }

            throw new Exception("Problem downloading the requested file!");
        }
Exemple #14
0
        public async Task SaveTusFileInfoAsync(ITusFile file, SiteTypeEnum siteType, string refreshToken, UploadLocationEnum location, UploadLinkAccessibilityEnum linkAccessibility, CancellationToken cancellationToken)
        {
            var metadata = await file.GetMetadataAsync(cancellationToken);

            string name = metadata["name"].GetString(Encoding.UTF8);
            string type = metadata["type"].GetString(Encoding.UTF8);


            using (var scope = Services.CreateScope())
            {
                var httpContextAccessor =
                    scope.ServiceProvider
                    .GetRequiredService <IHttpContextAccessor>();

                var context =
                    scope.ServiceProvider
                    .GetRequiredService <DataContext>();

                var logger =
                    scope.ServiceProvider
                    .GetRequiredService <IActivityLogger>();

                var token = context.Tokens.SingleOrDefault(x => x.RefreshToken == refreshToken);
                var user  = token.CreatedBy;

                var    storePath         = Path.Combine(UploadFolderName, user.UserName);
                var    extension         = Path.GetExtension(name);
                var    fileName          = file.Id;
                var    filePublicName    = name;
                var    mimeType          = type;
                var    fileRelativePath  = Path.Combine(storePath, fileName);
                long   size              = 0;
                string fileThumbnailPath = "";
                var    fileType          = TusCheckFileType(type);

                if (location == UploadLocationEnum.LocalHost)
                {
                    size = new FileInfo(Path.Combine(UploadFolderName, user.UserName, fileName)).Length;
                    fileThumbnailPath = fileType == AttachmentTypeEnum.Photo ? await GenerateImageThumbnailAsync(file, extension, storePath, user.UserName, cancellationToken) : "";
                }
                if (location == UploadLocationEnum.FtpServer)
                {
                    // create an FTP client
                    FtpClient client = new FtpClient(_baseUri, _port, _username, _password);
                    // begin connecting to the server
                    await client.ConnectAsync();

                    size = await client.GetFileSizeAsync($"{storePath}/{fileName}");

                    //
                    await client.DisconnectAsync();
                }

                var site = await context.Sites.SingleOrDefaultAsync(x => x.SiteType == siteType);

                user.CreatedAttachments.Add(new Attachment
                {
                    SiteId            = site.Id,
                    UploadLocation    = location,
                    Type              = fileType,
                    RelativePath      = fileRelativePath,
                    ThumbnailPath     = fileThumbnailPath,
                    MimeType          = mimeType,
                    FileName          = fileName,
                    PublicFileName    = filePublicName,
                    FileExtension     = extension,
                    FileSize          = size,
                    LinkAccessibility = linkAccessibility
                });

                var success = await context.SaveChangesAsync() > 0;

                if (success)
                {
                    await logger.LogActivity(
                        site.Id,
                        ActivityCodeEnum.AttachmentAdd,
                        ActivitySeverityEnum.Medium,
                        ActivityObjectEnum.Attachemnt,
                        $"The {fileType} file with the name {fileName} has been uploaded");
                }
                else
                {
                    throw new Exception("Problem saving file information in database!");
                }
            }
        }
Exemple #15
0
        public async Task <FileUploadResult> AddFileAsync(IFormFile file, UploadLocationEnum uploadLocation)
        {
            var uploadFolderName              = "uploads";
            var userUploadSubFolderName       = _userAccessor.GetCurrentUsername();
            var userUploadSubFolderByDateName = DateTime.UtcNow.ToString("yyyy-MM-dd");
            var extension = Path.GetExtension(file.FileName);
            var fileName  = $"{DateTime.UtcNow.ToString("H:mm:ss")}__{Path.GetRandomFileName()}{extension}";
            var mimeType  = file.ContentType;
            var size      = file.Length;
            var option    = await _optionAccessor.GetOptionByKeyDescriptionAsync(mimeType);

            if (option.Value == ValueEnum.Attachments__NotAllowed)
            {
                throw new Exception("You are not allowed to upload this type of file!");
            }

            if (size > 0)
            {
                var    fileType         = CheckFileType(file);
                string fileRelativePath = null;

                if (uploadLocation == UploadLocationEnum.LocalHost)
                {
                    var root = _env.ContentRootPath;
                    Directory.CreateDirectory($"{_env.ContentRootPath}/{uploadFolderName}/{userUploadSubFolderName}/{userUploadSubFolderByDateName}/{fileType.ToString().ToLowerInvariant()}");
                    fileRelativePath = $"/{uploadFolderName}/{userUploadSubFolderName}/{userUploadSubFolderByDateName}/{fileType.ToString().ToLowerInvariant()}/{fileName}";
                    var fileAbsolutePath = $"{root}{fileRelativePath}";


                    using (var stream = File.Create(fileAbsolutePath))
                    {
                        if (IsFileTypeVerified(file, stream))
                        {
                            await file.CopyToAsync(stream);
                        }
                    }
                }
                if (uploadLocation == UploadLocationEnum.FtpServer)
                {
                    var path = $"/{uploadFolderName}/{userUploadSubFolderName}/{userUploadSubFolderByDateName}/{fileType.ToString().ToLowerInvariant()}";
                    fileRelativePath = $"/{uploadFolderName}/{userUploadSubFolderName}/{userUploadSubFolderByDateName}/{fileType.ToString().ToLowerInvariant()}/{fileName}";
                    // create an FTP client
                    FtpClient client = new FtpClient(_baseUri, _port, _username, _password);
                    // begin connecting to the server
                    await client.ConnectAsync();

                    // check if a folder doesn't exist
                    if (!await client.DirectoryExistsAsync(path))
                    {
                        await client.CreateDirectoryAsync(path);
                    }

                    using (var stream = file.OpenReadStream())
                    {
                        if (IsFileTypeVerified(file, stream))
                        {
                            // Upload file
                            var ftpStatus = await client.UploadAsync(stream, fileRelativePath);

                            if (ftpStatus.IsFailure())
                            {
                                await client.DisconnectAsync();

                                throw new Exception("Uploading file failed!");
                            }
                        }
                    }
                    // disconnect!
                    await client.DisconnectAsync();
                }

                return(new FileUploadResult
                {
                    Type = fileType,
                    RelativePath = fileRelativePath,
                    MimeType = mimeType,
                    FileName = fileName,
                    FileExtension = extension,
                    FileSize = size,
                });
            }

            throw new Exception("Problem uploading the file!");
        }