Ejemplo n.º 1
0
        public async Task <List <FileInfoVm> > GetFilesInfoAsync(DateTime navigationTime, long?uploaderId = null, int limit = 100)
        {
            using (MessengerDbContext context = contextFactory.Create())
            {
                IQueryable <FileInfo> query;
                if (uploaderId == null)
                {
                    query = from file in context.FilesInfo
                            .Where(fileInfo => fileInfo.Deleted == false)
                            select file;
                }
                else
                {
                    query = from file in context.FilesInfo
                            .Where(fileInfo => fileInfo.Deleted == false)
                            where file.UploaderId == uploaderId
                            select file;
                }
                List <FileInfo> filesInfo = await query
                                            .AsNoTracking()
                                            .Take(limit)
                                            .OrderBy(file => file.UploadDate)
                                            .Where(file => file.UploadDate >= navigationTime.ToUnixTime())
                                            .ToListAsync()
                                            .ConfigureAwait(false);

                return(FileInfoConverter.GetFilesInfoVm(filesInfo, uploaderId != null));
            }
        }
Ejemplo n.º 2
0
        public async Task <List <FileInfoVm> > SearchAsync(string prefix)
        {
            var files = Directory.GetFiles(DIR_NAME);

            if (!files.IsNullOrEmpty())
            {
                List <FileInfoVm> resultFiles = new List <FileInfoVm>();
                foreach (var fileName in files)
                {
                    try
                    {
                        if (fileName.ToLowerInvariant().Contains(prefix.ToLowerInvariant()))
                        {
                            var fileInfo = await filesService.GetFileInfoAsync(fileName);

                            if (fileInfo != null)
                            {
                                resultFiles.Add(FileInfoConverter.GetFileInfoVm(fileInfo, false));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.WriteLog(ex);
                    }
                }
                return(resultFiles);
            }
            return(new List <FileInfoVm>());
        }
Ejemplo n.º 3
0
        public void BasicUsage(string fileString)
        {
            FileInfoConverter c  = new FileInfoConverter();
            FileInfo          fi = c.ConvertFromString(fileString) as FileInfo;

            Assert.Equal <string>(fileString, fi.FullName);
        }
Ejemplo n.º 4
0
        public async Task <FileInfoVm> SaveFileAsync(long?userId, string filename, string url, long fileSize, byte[] fileHash, string storageType, ImageMetadata imageMetadata = null)
        {
            using (MessengerDbContext context = contextFactory.Create())
            {
                FileInfo newFile = new FileInfo
                {
                    Id            = RandomExtensions.NextString(64),
                    FileName      = filename,
                    Url           = url,
                    UploaderId    = userId,
                    UploadDate    = DateTime.UtcNow.ToUnixTime(),
                    NodeId        = NodeSettings.Configs.Node.Id,
                    Size          = fileSize,
                    Hash          = fileHash,
                    Storage       = storageType,
                    NumericId     = await poolsService.GetFileIdAsync().ConfigureAwait(false),
                    ImageMetadata = imageMetadata
                };
                await context.FilesInfo.AddAsync(newFile).ConfigureAwait(false);

                await context.SaveChangesAsync().ConfigureAwait(false);

                return(FileInfoConverter.GetFileInfoVm(newFile, false));
            }
        }
        public void CanConvertFrom()
        {
            FileInfoConverter vrt = new FileInfoConverter();

            Assert.IsTrue(vrt.CanConvertFrom(typeof(string)), "Conversion from a string instance must be supported.");
            Assert.IsFalse(vrt.CanConvertFrom(typeof(int)));
        }
        public void ConvertFrom()
        {
            FileInfoConverter vrt  = new FileInfoConverter();
            object            file = vrt.ConvertFrom("././ManAhShoahDoLoveThoseGrits");

            Assert.IsNotNull(file);
            Assert.AreEqual(typeof(FileInfo), file.GetType());
        }
Ejemplo n.º 7
0
        public void ConvertFile_WithInvalidFilename_ThrowsFormatException()
        {
            var input     = "folder\\fi||le.txt";
            var converter = new FileInfoConverter();

            Assert.ThrowsException <FormatException>(
                () => converter.ConvertFromInvariantString(input));
        }
        public void FileConverter()
        {
            FileInfoConverter converter = new FileInfoConverter();
            object            file      = converter.ConvertFrom("C:/test/myfile.txt");

            Assert.IsNotNull(file);
            Assert.IsTrue(file is FileInfo);
            Assert.AreEqual(new FileInfo("C:/test/myfile.txt").FullName, ((FileInfo)file).FullName);
        }
Ejemplo n.º 9
0
        public void ConvertFile_WithExistingFilename_FileInfoExistsIsTrue()
        {
            var input     = "folder\\sample.txt";
            var converter = new FileInfoConverter();

            var actual = (FileInfo)converter.ConvertFromInvariantString(input);

            Assert.IsTrue(actual.Exists);
        }
Ejemplo n.º 10
0
        public void ConvertFile_WithExistingFilename_ReturnsFileInfoObject()
        {
            var expected = new FileInfo("folder\\sample.txt").FullName;

            var input     = "folder\\sample.txt";
            var converter = new FileInfoConverter();

            var actual = (FileInfo)converter.ConvertFromInvariantString(input);

            Assert.AreEqual(expected, actual.FullName);
        }
Ejemplo n.º 11
0
        public async Task <FileInfoVm> UpdateFileInformationAsync(string fileName, string fileId)
        {
            using (MessengerDbContext context = contextFactory.Create())
            {
                FileInfo fileInfo = await context.FilesInfo.FindAsync(fileId).ConfigureAwait(false);

                fileInfo.Url = fileName;
                context.Update(fileInfo);
                await context.SaveChangesAsync().ConfigureAwait(false);

                return(FileInfoConverter.GetFileInfoVm(fileInfo));
            }
        }
Ejemplo n.º 12
0
        public async Task <List <FileInfoVm> > GetFilesInfoAsync(List <string> filesId, int limit = 100)
        {
            using (MessengerDbContext context = contextFactory.Create())
            {
                var filesCondition = PredicateBuilder.New <FileInfo>();
                filesCondition = filesId.Aggregate(filesCondition,
                                                   (current, value) => current.Or(file => file.Id == value).Expand());
                List <FileInfo> filesInfo = await context.FilesInfo
                                            .AsNoTracking()
                                            .Where(filesCondition)
                                            .Where(file => file.Deleted == false)
                                            .ToListAsync()
                                            .ConfigureAwait(false);

                return(FileInfoConverter.GetFilesInfoVm(filesInfo));
            }
        }
Ejemplo n.º 13
0
        public async Task <FileInfoVm> SaveFileAsync(FileInfoVm fileInfo, long userId, string url = null)
        {
            try
            {
                using (MessengerDbContext context = contextFactory.Create())
                {
                    FileInfo newFile = new FileInfo(fileInfo, url, userId);
                    await context.FilesInfo.AddAsync(newFile).ConfigureAwait(false);

                    await context.SaveChangesAsync().ConfigureAwait(false);

                    return(FileInfoConverter.GetFileInfoVm(newFile));
                }
            }
            catch (Exception ex)
            {
                throw new SaveFileInformationException("Failed to save file information", ex);
            }
        }
Ejemplo n.º 14
0
 /// <summary>
 /// Returns a <see cref="CacheValidator"/> from the specified <paramref name="fileName"/>.
 /// </summary>
 /// <param name="fileName">The fully qualified name of the file.</param>
 /// <param name="bytesToRead">The maximum size of a byte-for-byte that promotes a medium/strong integrity check of the specified <paramref name="fileName"/>. A value of 0 (or less) leaves the integrity check at weak.</param>
 /// <param name="setup">The <see cref="CacheValidatorOptions"/> which need to be configured.</param>
 /// <returns>A <see cref="CacheValidator"/> that represents either a weak, medium or strong integrity check of the specified <paramref name="fileName"/>.</returns>
 /// <exception cref="System.ArgumentNullException">
 /// <paramref name="fileName"/> is null.
 /// </exception>
 /// <remarks>Should the specified <paramref name="fileName"/> trigger any sort of exception, a <see cref="CacheValidator.Default"/> is returned.</remarks>
 public static CacheValidator GetCacheValidator(this string fileName, int bytesToRead = 0, Action <CacheValidatorOptions> setup = null)
 {
     Validator.ThrowIfNullOrWhitespace(fileName, nameof(fileName));
     try
     {
         return(FileInfoConverter.Convert(fileName, bytesToRead, (fi, checksumBytes) =>
         {
             if (checksumBytes.Length > 0)
             {
                 return new CacheValidator(fi.CreationTimeUtc, fi.LastWriteTimeUtc, checksumBytes.GetHashCode64(), setup);
             }
             var fileNameHashCode64 = fileName.GetHashCode64();
             return new CacheValidator(fi.CreationTimeUtc, fi.LastWriteTimeUtc, fileNameHashCode64, setup);
         }));
     }
     catch (Exception)
     {
         return(CacheValidator.Default);
     }
 }
Ejemplo n.º 15
0
        public async Task GetFileInfo()
        {
            var uploader = fillTestDbHelper.Users.FirstOrDefault();
            var expected = new FileInfoVm
            {
                Filename   = "Filename",
                Hash       = RandomExtensions.NextBytes(26),
                NumericId  = 0,
                UploaderId = uploader.Id,
                Uploaded   = DateTime.UtcNow.ToUnixTime(),
                Size       = 1024,
                NodeId     = 1
            };

            expected = await filesService.SaveFileAsync(expected, uploader.Id, "ssylca");

            var actual = FileInfoConverter.GetFileInfoVm(await filesService.GetFileInfoAsync(expected.FileId));

            Assert.Equal(expected.ToJson(), actual.ToJson());
        }
Ejemplo n.º 16
0
        public async Task <FileInfoVm> LoadFileInfoAsync(string fileId)
        {
            using (MessengerDbContext context = contextFactory.Create())
            {
                var fileInfo = await context.FilesInfo
                               .AsNoTracking()
                               .FirstOrDefaultAsync(file => file.Id == fileId && file.Deleted == false).ConfigureAwait(false);

                if (fileInfo == null)
                {
                    List <FileInfoVm> filesInfo = await _nodeRequestSender.GetFilesInformationAsync(new List <string> {
                        fileId
                    }, null).ConfigureAwait(false);

                    if (!filesInfo.IsNullOrEmpty())
                    {
                        return(filesInfo.FirstOrDefault());
                    }
                }
                return(FileInfoConverter.GetFileInfoVm(fileInfo));
            }
        }
Ejemplo n.º 17
0
        public async Task DeleteFiles()
        {
            var uploader = fillTestDbHelper.Users.Skip(1).FirstOrDefault();
            var fileinfo = new FileInfoVm
            {
                Filename   = "Filename",
                Hash       = RandomExtensions.NextBytes(26),
                NumericId  = 0,
                UploaderId = uploader.Id,
                Uploaded   = DateTime.UtcNow.ToUnixTime(),
                Size       = 1024,
                NodeId     = 1
            };

            fileinfo = await filesService.SaveFileAsync(fileinfo, uploader.Id, "ssylca");

            var expected = FileInfoConverter.GetFileInfoVm(await filesService.GetFileInfoAsync(fileinfo.FileId));
            await filesService.DeleteFilesAsync(new List <string> {
                expected.FileId
            }, uploader.Id);

            Assert.Null(fillTestDbHelper.Files.FirstOrDefault(opt => opt.Id == expected.FileId && !opt.Deleted));
        }
Ejemplo n.º 18
0
        public async Task <List <FileInfoVm> > CreateFilesInformationAsync(List <FileInfoVm> filesInfo)
        {
            var filesCondition = PredicateBuilder.New <FileInfo>();

            filesCondition = filesInfo.Aggregate(filesCondition,
                                                 (current, value) => current.Or(opt => opt.Id == value.FileId).Expand());
            using (MessengerDbContext context = contextFactory.Create())
            {
                List <FileInfo> existingFiles = await context.FilesInfo
                                                .Where(filesCondition)
                                                .ToListAsync()
                                                .ConfigureAwait(false);

                List <FileInfoVm> nonExistingFiles = filesInfo.Where(fileVm => !existingFiles.Any(file => file.Id == fileVm.FileId))?.ToList();
                if (!nonExistingFiles.IsNullOrEmpty())
                {
                    List <FileInfo> newFiles = FileInfoConverter.GetFilesInfo(nonExistingFiles);
                    await context.FilesInfo.AddRangeAsync(newFiles).ConfigureAwait(false);

                    await context.SaveChangesAsync().ConfigureAwait(false);
                }
            }
            return(filesInfo);
        }
        public void ConvertFromNullReference()
        {
            FileInfoConverter vrt = new FileInfoConverter();

            vrt.ConvertFrom(null);
        }
        public void ConvertFromNonSupportedOptionBails()
        {
            FileInfoConverter vrt = new FileInfoConverter();

            vrt.ConvertFrom(12);
        }