Beispiel #1
0
        public async Task AddDiscoveredFile(Stream fileStream, string title, string extension, string originalLocation, string metadata, string sourceName)
        {
            using (var dbContext = new ApplicationDbContext(_dbContextOptions))
            {
                var source = await dbContext.Sources.Where(s => s.Name.ToLower() == sourceName.ToLower()).FirstOrDefaultAsync();

                if (source == null)
                {
                    source = new Source
                    {
                        Name = sourceName
                    };
                    await dbContext.AddAsync(source);

                    await dbContext.SaveChangesAsync();
                }

                string hash = CalculateMD5(fileStream);
                fileStream.Seek(0, SeekOrigin.Begin);
                var file = await dbContext.Files.Where(f => f.Hash == hash).FirstOrDefaultAsync();

                if (file != null)
                {
                    // a matching file was found, but maybe it's a hash collision
                    if (!StreamsAreEqual(fileStream, _blobStore.Get(file.Id)))
                    {
                        // the files are actually different, force recreation of the file
                        file = null;
                    }
                }

                if (file == null)
                {
                    file = new File
                    {
                        Hash      = hash,
                        Title     = title,
                        Extension = extension
                    };
                    await dbContext.AddAsync(file);

                    await dbContext.SaveChangesAsync();

                    await _blobStore.PutAsync(fileStream, file.Id);
                }

                var fileSource = new FileSource
                {
                    FileId    = file.Id,
                    Metadata  = metadata,
                    SourceUri = originalLocation,
                    SourceId  = source.Id,
                };
                await dbContext.AddAsync(fileSource);

                await dbContext.SaveChangesAsync();
            }
        }