Пример #1
0
        private void loadImagesToSelectPhotos()
        {
            noPhotosLabel.Visibility = Visibility.Hidden;
            string cwd          = System.Reflection.Assembly.GetExecutingAssembly().Location;
            string solutionPath = cwd.Replace("\\bin\\Debug\\StarPix.exe", "");
            string directory    = solutionPath + "\\images\\new_photos\\";

            string[] images = System.IO.Directory.GetFiles(directory);
            images = images.Where(F => ImageExtensions.Contains(System.IO.Path.GetExtension(F))).ToArray();
            foreach (string path in images)
            {
                OleDbConnection connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\StarPix.accdb");
                connection.Open();
                DataTable dt = new DataTable();
                DataSet   ds = new DataSet();
                ds.Tables.Add(dt);
                string           fileName = getFileName(path);
                OleDbDataAdapter da       = new OleDbDataAdapter("SELECT ImagePath from Images WHERE ImagePath LIKE '%" + fileName + "%' ORDER BY ImagePath ASC", connection);
                da.Fill(dt);
                if (dt.Rows.Count == 0)
                {
                    addPhoto(path);
                }
            }

            if (selectListBox.Items.Count == 0)
            {
                noPhotosLabel.Visibility = Visibility.Visible;
            }
        }
Пример #2
0
        public static bool CheckIfFileIsForbidden(IFormFile file)
        {
            var ext = Path.GetExtension(file.FileName).ToLowerInvariant();

            if (string.IsNullOrEmpty(ext) || !ImageExtensions.Contains(ext))
            {
                return(true);
            }
            return(false);
        }
Пример #3
0
        Task ICanAcceptFiles.Import(params string[] paths)
        {
            Schedule(() =>
            {
                var firstFile = new FileInfo(paths.First());

                if (ImageExtensions.Contains(firstFile.Extension))
                {
                    ChangeBackgroundImage(firstFile.FullName);
                }
                else if (AudioExtensions.Contains(firstFile.Extension))
                {
                    audioTrackTextBox.Text = firstFile.FullName;
                }
            });
            return(Task.CompletedTask);
        }
Пример #4
0
        /// <summary>
        ///     Determines whether [is allowed extension] [the specified extension].
        /// </summary>
        /// <param name="extension">The extension.</param>
        /// <param name="fileType">Type of the file.</param>
        /// <returns></returns>
        /// <createdOn>1/27/2016 8:00 AM</createdOn>
        /// <exception cref="System.ArgumentOutOfRangeException">null</exception>
        public static bool IsAllowedExtension(string extension, FileType fileType = FileType.Image)
        {
            var isAllowed = false;

            switch (fileType)
            {
            case FileType.Image:
                isAllowed = ImageExtensions.Contains(extension);
                break;

            case FileType.Document:
                isAllowed = DocumentExtensions.Contains(extension);
                break;

            case FileType.Presentation:
                isAllowed = PresentationExtensions.Contains(extension);
                break;

            case FileType.Spreadsheet:
                isAllowed = SpreadsheetExtensions.Contains(extension);
                break;

            case FileType.CompressedFile:
                isAllowed = CompressedFileExtensions.Contains(extension);
                break;

            case FileType.Website:
                isAllowed = WebsiteExtensions.Contains(extension);
                break;

            case FileType.Sound:
                isAllowed = SoundExtensions.Contains(extension);
                break;

            case FileType.Video:
                isAllowed = VideoExtensions.Contains(extension);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null);
            }

            return(isAllowed);
        }
Пример #5
0
        private UploadMedia(string path)
        {
            var ext = System.IO.Path.GetExtension(path);

            if (ImageExtensions.Contains(ext, StringComparer.OrdinalIgnoreCase))
            {
                var uri = new Uri(path, UriKind.Absolute);

                if (ext.Equals(".gif", StringComparison.OrdinalIgnoreCase) && ImageUtil.IsAnimatedGif(uri))
                {
                    this.MediaType    = MediaType.AnimatedGifFile;
                    this.PreviewImage = ImageUtil.FromFile(uri);
                }
                else
                {
                    this.MediaType = MediaType.ImageFile;

                    if (!ext.Equals(".webp", StringComparison.OrdinalIgnoreCase))
                    {
                        this.PreviewImage = ImageUtil.FromFile(uri);
                    }
                }
            }
            else if (VideoExtensions.Contains(ext, StringComparer.OrdinalIgnoreCase))
            {
                this.MediaType = MediaType.VideoFile;
            }
            else
            {
                throw new NotSupportedException();
            }

            this.Path             = path;
            this.DisplayExtension = ext.Substring(1).ToUpper();

            if (this.PreviewImage?.CanFreeze ?? false)
            {
                this.PreviewImage.Freeze();
            }
        }
Пример #6
0
        private UploadMedia(string filePath)
        {
            var ext = Path.GetExtension(filePath).ToLower();

            if (ext.Equals(".gif") && IsAnimatedGif(ext))
            {
                MediaType    = MediaType.AnimatedGifFile;
                PreviewImage = new BitmapImage(new Uri(filePath));
            }
            else if (VideoExtensions.Contains(ext))
            {
                MediaType        = MediaType.VideoFile;
                UseChunkedUpload = true;
            }
            else if (ImageExtensions.Contains(ext))
            {
                MediaType = MediaType.ImageFile;

                if (ext != ".webp")
                {
                    PreviewImage = new BitmapImage(new Uri(filePath));
                }
            }
            else
            {
                throw new NotSupportedException();
            }

            FilePath      = filePath;
            filePath      = Path.GetFileName(filePath);
            ViewExtension = ext.Substring(1).ToUpper();
            SourceStream  = File.OpenRead(FilePath);

            if (PreviewImage?.CanFreeze ?? false)
            {
                PreviewImage.Freeze();
            }
        }
Пример #7
0
        private async Task GatherSubFolderAndFiles(StorageFolder folder, Directory parent, bool singleVideo = false)
        {
            LogMessage.AppendLine($"***********************");
            LogMessage.AppendLine($"Folder: {folder.Name}");

            bool folderHasImage = false;

            foreach (var file in await folder.GetFilesAsync())
            {
                if (ImageExtensions.Contains(file.FileType.ToUpper()) && !folderHasImage)
                {
                    var copy = await file.CopyAsync(await Cache.GetThumbnailFolder());

                    await copy.RenameAsync(Cache.GetName(parent.Id.Value));

                    folderHasImage = true;
                }

                if (AllowedExtension.Contains(file.FileType.ToUpper()))
                {
                    LogMessage.AppendLine($"    {file.Name}");
                    VideoProperties videoProperties = await file.Properties.GetVideoPropertiesAsync();

                    var title    = videoProperties.Title;
                    var fileName = string.IsNullOrEmpty(title) ? file.Name : title;
                    var video    = new Video()
                    {
                        Name        = file.DisplayName,
                        Parent      = parent,
                        Path        = file.Path,
                        FileName    = fileName,
                        ParentDirId = parent.Id.Value,
                        Id          = Guid.NewGuid(),
                        Markers     = new List <Markers>(),
                    };

                    var thumbnail = await file.GetThumbnailAsync(ThumbnailMode.VideosView);

                    using (var reader = new DataReader(thumbnail.GetInputStreamAt(0)))
                    {
                        await reader.LoadAsync((uint)thumbnail.Size);

                        var buffer = new byte[(int)thumbnail.Size];
                        reader.ReadBytes(buffer);
                        Cache.SaveThumbnail(buffer, video.Id.Value);
                    }
                    parent.Videos.Add(video);

                    if (singleVideo)
                    {
                        return;
                    }
                }
            }

            foreach (var subFolder in await folder.GetFoldersAsync())
            {
                if (subFolder.Name.ToLower() == "sample" || subFolder.Name.ToLower() == "subtitles" || subFolder.Name.ToLower() == "subs")
                {
                    continue;
                }
                var directory = new Directory()
                {
                    Name        = subFolder.Name,
                    Parent      = parent,
                    Path        = subFolder.Path,
                    Id          = Guid.NewGuid(),
                    ParentDirId = parent.Id.Value
                };
                parent.Directories.Add(directory);
                await GatherSubFolderAndFiles(subFolder, directory);
            }
        }
Пример #8
0
        private bool FileIsImage(string fileName)
        {
            string ext = Path.GetExtension(fileName).TrimStart('.');

            return(ImageExtensions.Contains(ext));
        }
Пример #9
0
 public static bool IsImage(string path) => ImageExtensions.Contains($"*{Path.GetExtension(path).ToLowerInvariant()}");
Пример #10
0
        private async Task <Result> AddOrReplace(IFormFile file, string fileName, AgentContext agentContext)
        {
            return(await Validate()
                   .Bind(Upload)
                   .Tap(StoreLink));


            async Task <Result <byte[]> > Validate()
            {
                return(await Result.Success()
                       .Ensure(() => file != default, "Could not get the file")
                       .Ensure(() => ImageExtensions.Contains(Path.GetExtension(file?.FileName)?.ToLowerInvariant()),
                               "The file must have extension of a jpeg image")
                       .Map(GetImageBytes)
                       .Bind(ValidateImage));


                async Task <byte[]> GetImageBytes()
                {
                    await using var stream = file.OpenReadStream();
                    using var binaryReader = new BinaryReader(stream);
                    return(binaryReader.ReadBytes((int)file.Length));
                }

                async Task <Result <byte[]> > ValidateImage(byte[] imageBytes)
                {
                    // Here should be checks like aspect ratio, for now only resolution checks
                    var imageInfo = await ImageJob.GetImageInfo(new BytesSource(imageBytes));

                    return(Result.Success()
                           .Ensure(() => imageInfo.ImageWidth >= MinimumWidth && imageInfo.ImageWidth <= MaximumWidth,
                                   $"Image width must be in range from {MinimumWidth} to {MaximumWidth}")
                           .Ensure(() => imageInfo.ImageHeight >= MinimumHeight && imageInfo.ImageHeight <= MaximumHeight,
                                   $"Image height must be in range from {MinimumWidth} to {MaximumWidth}")
                           .Map(() => imageBytes));
                }
            }

            async Task <Result <string> > Upload(byte[] imageBytes)
            {
                await using var stream = new MemoryStream(imageBytes);
                return(await _amazonS3ClientService.Add(_bucketName, GetKey(agentContext.AgencyId, fileName), stream, S3CannedACL.PublicRead));
            }

            async Task StoreLink(string url)
            {
                var oldUploadedImage = await _edoContext.UploadedImages
                                       .SingleOrDefaultAsync(i => i.AgencyId == agentContext.AgentId && i.FileName == fileName);

                if (oldUploadedImage == null)
                {
                    var now = _dateTimeProvider.UtcNow();

                    var newUploadedImage = new UploadedImage
                    {
                        AgencyId = agentContext.AgencyId,
                        Url      = url,
                        FileName = fileName,
                        Created  = now,
                        Updated  = now
                    };

                    _edoContext.Add(newUploadedImage);
                }
                else
                {
                    oldUploadedImage.Updated = _dateTimeProvider.UtcNow();
                    oldUploadedImage.Url     = url;

                    _edoContext.Update(oldUploadedImage);
                }

                await _edoContext.SaveChangesAsync();
            }
        }