Example #1
0
        public async Task <bool> TryDeleteFileAsync(string path)
        {
            path = GetPhysicalPath(path);
            var fileInfo = await getGridFSFileInfoAsync(path);

            await _bucket.DeleteAsync(fileInfo.Id);

            return(true);
        }
Example #2
0
        public override async Task Delete(Expression <Func <File, bool> > where)
        {
            var filesToDelete = await Get(where);

            foreach (var file in filesToDelete)
            {
                await _bucket.DeleteAsync(file.Id.ToObjectId());
            }
            await base.Delete(where);
        }
Example #3
0
        public async Task <object> DeleteFiledAsync(object Id)
        {
            var fileId = (ObjectId)Id;
            await bucket.DeleteAsync(fileId);

            return(true);
        }
Example #4
0
        public async Task <bool> TryRollback(ObjectId pictureId)
        {
            var pictures = await _pictures.FindAsync(p => p.Id == pictureId);

            var pictureEntities = pictures.Current.ToList();

            if (!pictureEntities.Any())
            {
                return(false);
            }
            var picture = pictures.First();

            if (picture.GridFsIds.Count < 2)
            {
                return(false);
            }

            var old = picture.GridFsIds.Last();

            picture.GridFsIds.RemoveAt(picture.GridFsIds.Count - 1);

            await _gridFs.DeleteAsync(old);

            await _pictures.ReplaceOneAsync(new FilterDefinitionBuilder <PictureEntity>().Eq("_id", picture.Id),
                                            picture);

            return(true);
        }
Example #5
0
 public async Task DeleteFile(ObjectId id, CancellationToken token = default(CancellationToken))
 {
     if (_bucket == null)
     {
         return;
     }
     await _bucket.DeleteAsync(id, token);
 }
Example #6
0
        public async Task <string> DeleteFileAsync(string id)
        {
            var collection = fileInfoDB.GetCollection <FileDetails>(fileInfoDbName);
            await collection.DeleteOneAsync(info => info.Id == id);

            await fsBucket.DeleteAsync(ObjectId.Parse(id));

            return(id);
        }
        public async Task UpdateChallengeAsync(Challenge toUpdate)
        {
            if (string.IsNullOrWhiteSpace(toUpdate.Id))
            {
                throw new Exception("The id must be provided in the body");
            }
            if (string.IsNullOrWhiteSpace(toUpdate.Name))
            {
                throw new Exception("You must provide a name to the challenge");
            }
            if (string.IsNullOrWhiteSpace(toUpdate.Description))
            {
                throw new Exception("You must provide a description to the challenge");
            }

            var oldChallenge = await GetChallengeAsync(toUpdate.Id);

            if (oldChallenge == null)
            {
                throw new Exception("The challenge you wan't to update doesn't exist");
            }

            if (toUpdate.ImageId == "modified")
            {
                // If we don't do it manally old images are never deleted
                if (!string.IsNullOrWhiteSpace(oldChallenge.ImageId))
                {
                    await _gridFS.DeleteAsync(new ObjectId(oldChallenge.ImageId));
                }

                var challengeImage = await _gridFS.UploadFromBytesAsync($"challenge_{toUpdate.Id}", toUpdate.Image);

                toUpdate.Image   = null;
                toUpdate.ImageId = challengeImage.ToString();
            }
            else
            {
                toUpdate.ImageId = oldChallenge.ImageId;
            }

            await _challenges.ReplaceOneAsync(challenge => challenge.Id == toUpdate.Id, toUpdate);
        }
        public async Task DeleteFileByPostGuidAsync(string postguid)
        {
            var files = await FindfileByPostId(postguid, false);

            var gridFsBucket = new GridFSBucket(this.database);

            foreach (var file in files)
            {
                await gridFsBucket.DeleteAsync(file.Id);
            }
        }
Example #9
0
        /*
         * Edition stuff
         */
        public async Task UpdateUserAsync(User toUpdate)
        {
            if (string.IsNullOrWhiteSpace(toUpdate.Id))
            {
                throw new Exception("The id must be provided in the body");
            }

            // If we don't do it manally old images are never deleted
            var oldUser = await(await _users.FindAsync(databaseUser => databaseUser.Id == toUpdate.Id)).FirstOrDefaultAsync();

            if (oldUser == null)
            {
                throw new Exception("The user doesn't exist");
            }

            if (toUpdate.ProfilePictureId == "modified")
            {
                if (!string.IsNullOrWhiteSpace(oldUser.ProfilePictureId))
                {
                    await _gridFS.DeleteAsync(new ObjectId(oldUser.ProfilePictureId));
                }

                var userImage = await _gridFS.UploadFromBytesAsync($"user_{toUpdate.Id}", toUpdate.ProfilePicture);

                toUpdate.ProfilePicture   = null;
                toUpdate.ProfilePictureId = userImage.ToString();
            }
            else
            {
                toUpdate.ProfilePictureId = oldUser.ProfilePictureId;
            }

            toUpdate.WaitingCallenges  = oldUser.WaitingCallenges;
            toUpdate.FinishedCallenges = oldUser.FinishedCallenges;
            toUpdate.PasswordHash      = oldUser.PasswordHash;
            toUpdate.PasswordSalt      = oldUser.PasswordSalt;

            await _users.ReplaceOneAsync(databaseUser => databaseUser.Id == toUpdate.Id, toUpdate);
        }
Example #10
0
        static async Task Main(string[] args)
        {
            var mongoSettings = MongoClientSettings.FromConnectionString(args[0]);
            var client        = new MongoClient(mongoSettings);
            var mongoDatabase = client.GetDatabase("dr-move-public-api");
            var bucket        = new GridFSBucket(mongoDatabase, new GridFSBucketOptions
            {
                BucketName = "packages",
            });


            if (!int.TryParse(args[1], out var numberOfDays))
            {
                Console.WriteLine($"Could not parse {args[1]} to an int.");
                return;
            }

            if (numberOfDays < 30)
            {
                Console.WriteLine("Minimum number of days = 30");
                return;
            }

            var mongoFilter =
                Builders <GridFSFileInfo <ObjectId> > .Filter.Lt(x => x.UploadDateTime, DateTime.UtcNow.AddDays(-numberOfDays));

            var options = new GridFSFindOptions
            {
                BatchSize = 50,
            };

            var batchnum = 0;
            var numFiles = 0;

            using (var cursor = await bucket.FindAsync(mongoFilter, options))
            {
                while (await cursor.MoveNextAsync())
                {
                    var batch = cursor.Current;
                    Console.WriteLine($"Deleting from batch {++batchnum}");

                    foreach (var item in batch)
                    {
                        numFiles++;
                        await bucket.DeleteAsync(item.Id);
                    }
                }
            }

            Console.WriteLine($"Deleted {numFiles} number of files");
        }
Example #11
0
        /// <inheritdoc />
        public async Task Delete(string id)
        {
            try
            {
                var result = await GetGridFsFileInfo(id);

                await _bucket.DeleteAsync(result.Id);
            }
            catch (GridFSFileNotFoundException)
            {
            }
            catch (Exception exception)
            {
                throw new ArgumentException($"Could not delete attachment with ID '{id}'", exception);
            }
        }
Example #12
0
        public async Task RunDemoAsync(IMongoCollection <ClubMember> collection)
        {
            Console.WriteLine("Starting GridFSDemo");
            IMongoDatabase database     = collection.Database;
            var            gridFsBucket = new GridFSBucket(database);
            const string   filePath     = @"..\..\Images\mars996.png";
            //the name of the uploaded GridFS file
            const string fileName = @"mars996";

            try
            {
                await DemoUploadAsync(database, filePath, fileName);
            }
            catch (Exception e)
            {
                Console.WriteLine("***GridFS Error " + e.Message);
            }

            await DemoCreateIndexAsync(database, "PhotoIndex");

            IMongoCollection <GridFSFileInfo> filesCollection = database.GetCollection <GridFSFileInfo>("fs.files");
            List <GridFSFileInfo>             fileInfos       = await DemoFindFilesAsync(filesCollection);

            foreach (GridFSFileInfo gridFsFileInfo in fileInfos)
            {
                Console.WriteLine("Found file {0} Length {1} ID= {2}", gridFsFileInfo.Filename, gridFsFileInfo.Length, gridFsFileInfo.Id);
            }
            try
            {
                await DemoDownloadFileAsync(database, filePath, fileName);
            }
            catch (Exception e)
            {
                Console.WriteLine("***GridFS Error " + e.Message);
            }
            var fileInfo = fileInfos.FirstOrDefault(fInfo => fInfo.Filename == fileName);

            if (fileInfo != null)
            {
                await gridFsBucket.DeleteAsync(fileInfo.Id);

                Console.WriteLine("\r\n{0} has been deleted", fileName);
                //to delete everything in the gridBucket use   await gridFsBucket.DropAsync();
            }
        }
Example #13
0
        public async Task <bool> DeleteAsync(string fileReference)
        {
            if (string.IsNullOrEmpty(fileReference))
            {
                return(false);
            }
            try
            {
                var fs = new GridFSBucket(_context.Database);
                await fs.DeleteAsync(new ObjectId(fileReference));

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Example #14
0
 public async Task DeleteFile(string fileId)
 {
     try
     {
         await gridFs.DeleteAsync(ObjectId.Parse(fileId));
     }
     catch (Exception exception)
     {
         if (exception is GridFSFileNotFoundException)
         {
             return;
         }
         else
         {
             throw exception;
         }
     }
 }
Example #15
0
        public async Task <string> UploadFile(string filename, byte[] fileBytes, bool shouldOverride = true)
        {
            if (shouldOverride)
            {
                var filter = Builders <GridFSFileInfo <ObjectId> > .Filter.Eq(x => x.Filename, filename);

                var currentFile = await(await _gridFS.FindAsync(filter)).FirstOrDefaultAsync();

                if (currentFile != null)
                {
                    await _gridFS.DeleteAsync(currentFile.Id);
                }
            }

            var file = await _gridFS.UploadFromBytesAsync(filename, fileBytes);

            return(file.ToString());
        }
        private async Task <int> NormalizeAudio(FileReference fileReference, CreateSongRequest requestBody, string authorName)
        {
            var oldId = fileReference._id;
            var newId = ObjectId.GenerateNewId();

            var gridFsBucket   = new GridFSBucket <ObjectId>(MongoWrapper.Database);
            var downloadStream = await gridFsBucket.OpenDownloadStreamAsync(oldId);

            (Stream newAudio, int seconds) = await AudioHandlerService.ProcessAudio
                                             (
                downloadStream,
                requestBody.Autoral?null : new int?(15),
                requestBody.Nome,
                authorName,
                fileReference.FileInfo.FileMetadata.ContentType
                                             );

            fileReference._id = newId;
            if (fileReference.FileInfo == null)
            {
                fileReference.FileInfo = new Models.FileInfo();
            }
            fileReference.FileInfo.FileMetadata.ContentType = "audio/mpeg";
            fileReference.FileInfo.FileMetadata.FileType    = FileType.Audio;

            var uploadStream = await gridFsBucket.OpenUploadStreamAsync
                               (
                newId,
                newId.ToString(),
                new GridFSUploadOptions
            {
                Metadata = fileReference.FileInfo.FileMetadata.ToBsonDocument(),
            }
                               );

            await newAudio.CopyToAsync(uploadStream);

            await uploadStream.CloseAsync();

            var deleteOldTask = gridFsBucket.DeleteAsync(oldId);

            return(seconds);
        }
Example #17
0
        public static async Task PutAsync(string filename, Stream stream)
        {
            var db         = DbConnection.db;
            var collection = db.GetCollection <GridFSFileInfo>("fs.files");
            var bucket     = new GridFSBucket(db);

            var builder = Builders <GridFSFileInfo> .Filter;
            var filter  = builder.Eq(i => i.Filename, filename);
            var foo     = await collection.FindAsync <GridFSFileInfo>(filter);

            var foooo = foo.ToList();

            foreach (var el in foooo)
            {
                await bucket.DeleteAsync(el.Id);
            }

            var id = await bucket.UploadFromStreamAsync(filename, stream);
        }
        protected override async Task Handle(DeletePlayerCommand request, CancellationToken cancellationToken)
        {
            var collection = _database.GetCollection <Party>("players");
            await collection.DeleteOneAsync(x => x.Name == request.Name, cancellationToken);

            var bucket = new GridFSBucket(_database, new GridFSBucketOptions
            {
                BucketName = "portraits"
            });

            var filter = Builders <GridFSFileInfo> .Filter.And(
                Builders <GridFSFileInfo> .Filter.Eq(x => x.Filename, request.Name));

            var files = await bucket.FindAsync(filter, null, cancellationToken);

            var file = await files.FirstOrDefaultAsync(cancellationToken);

            if (file != null)
            {
                await bucket.DeleteAsync(file.Id, cancellationToken);
            }
        }
Example #19
0
 protected Task InvokeMethodAsync(GridFSBucket bucket)
 {
     return(bucket.DeleteAsync(_id));
 }
 public async Task RemoveAsync(ObjectId objectId)
 => await _mediaBucket.DeleteAsync(objectId);
Example #21
0
 public async Task DeleteOne(string id) => await GridFSBucket.DeleteAsync(id.ToObjectId());
Example #22
0
        /// <summary>
        /// Deletes a file from GridFS.
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Task DeleteAsync(ObjectId id)
        {
            var bucket = new GridFSBucket(base.GetDatabase(), BucketOptions);

            return(bucket.DeleteAsync(id));
        }
 public async Task DeleteFileAsync(string id)
 {
     var gridFsBucket = new GridFSBucket(this.database);
     await gridFsBucket.DeleteAsync(new ObjectId(id));
 }
Example #24
0
 public async Task DeleteFileAsync(string id)
 {
     await fsBucket.DeleteAsync(ObjectId.Parse(id));
 }
Example #25
0
 /// <summary>
 /// 删除文件
 /// </summary>
 public async Task DeleteFileAsync(string id)
 {
     await _bucket.DeleteAsync(new ObjectId(id));
 }
Example #26
0
 protected Task InvokeMethodAsync(GridFSBucket bucket)
 {
     return bucket.DeleteAsync(_id);
 }
Example #27
0
 public async Task DeleteAsync(string id)
 {
     var gridFs = new GridFSBucket(_database);
     await gridFs.DeleteAsync(new ObjectId(id));
 }
        [AllowAnonymous] // No authorization required for Register Request, obviously
        public async Task <dynamic> Post([FromBody] TBody requestBody)
        {
            this.EnsureModelValidation();

            var userCollection = MongoWrapper.Database.GetCollection <Models.User>(nameof(Models.User));

            await RegistrarUtils.TestUserExists(this, userCollection, requestBody.Email);

            ResponseBody responseBody = new ResponseBody();

            DateTime creationDate = DateTime.UtcNow;

            var user = await BindUser(requestBody, creationDate);

            // 300MB file storage limit default
            user.FileBytesLimit = 300_000_000;

            var gridFsBucket = new GridFSBucket <ObjectId>(MongoWrapper.Database);

            Task photoTask = this.UploadPhoto(requestBody.Foto, gridFsBucket, user, creationDate);

            var insertTask = userCollection.InsertOneAsync(user);

            try
            {
                await insertTask;
            }
            catch (Exception e)
            {
                Logger.LogError("Error while registering user", e);
                try
                {
                    await    photoTask;
                    ObjectId?photoId = user?.Avatar?._id;
                    if (photoId.HasValue)
                    {
                        var deleteLingeringPhotoTask = gridFsBucket.DeleteAsync(photoId.Value);
                    }
                }
                catch
                {
                    // Ignore, no need to erase photo or log anything: User's insert has failed anyways.
                }
                throw;
            }

            // Não esperamos o e-mail ser enviado, apenas disparamos. Caso não tenha sido enviado vai ter um botão na home depois enchendo o saco pro usuário confirmar o e-mail dele.
            var sendEmailTask = EmailUtils.SendConfirmationEmail(MongoWrapper, SmtpConfiguration, user);

            var(tokenCreationDate, tokenExpiryDate, token) = await AuthenticationUtils.GenerateJwtTokenForUser(user._id.ToString(), TokenConfigurations, SigningConfigurations);

            responseBody.Message = "Registro efetuado com sucesso. Não se esqueça de confirmar seu e-mail!";
            responseBody.Code    = ResponseCode.GenericSuccess;
            responseBody.Success = true;
            responseBody.Data    = new
            {
                tokenData = new
                {
                    created     = tokenCreationDate,
                    expiration  = tokenExpiryDate,
                    accessToken = token,
                }
            };
            Response.StatusCode = (int)HttpStatusCode.OK;
            return(responseBody);
        }
        public async void UploadFileRealTest()
        {
            //prepare
            var(gridFs, fileAgent) = Configure();
            var byteData = new byte[] { 2, 0, 2, 0, 0, 4, 1, 8, 1, 0, 3, 8 };

            var testId = new Guid().ToString("N");
            var f      = await gridFs.FindAsync(
                new ExpressionFilterDefinition <GridFSFileInfo <ObjectId> >(x => x.Filename == testId));

            var existFile = await f.FirstOrDefaultAsync();

            if (existFile != null)
            {
                await gridFs.DeleteAsync(existFile.Id);
            }

            //execute
            await fileAgent.ProcessMessageAsync(byteData, new Dictionary <string, string>
            {
                ["Task"] = testId
            });

            //checks
            f = await gridFs.FindAsync(
                new ExpressionFilterDefinition <GridFSFileInfo <ObjectId> >(x => x.Filename == testId));

            var fileInFs = await f.FirstOrDefaultAsync();

            Assert.NotNull(fileInFs);
            Assert.Equal(testId, fileInFs.Filename);
            Assert.Equal(byteData.Length, fileInFs.Length);

            // executeGet
            var data = await fileAgent.ProcessRpcAsync(new AgentMessage <RpcRequest>
            {
                MessageType = MessageType.FileRequest,
                Data        = new RpcRequest
                {
                    Args = new[] { testId }
                }
            });

            var resBytes = data.To <byte[]>().Data;

            //checks
            Assert.Equal(resBytes, byteData);

            //clear
            await fileAgent.ProcessMessageAsync(new AgentMessage
            {
                MessageType = MessageType.DeleteFile,
                Data        = testId
            });

            //checks
            f = await gridFs.FindAsync(
                new ExpressionFilterDefinition <GridFSFileInfo <ObjectId> >(x => x.Filename == testId));

            Assert.False(await f.AnyAsync());
        }
Example #30
0
        public override async Task DeleteAsync(string id)
        {
            ObjectId oid = new ObjectId(id);

            await _bucket.DeleteAsync(oid);
        }
Example #31
0
        public async Task UpdateTeamAsync(Team toUpdate)
        {
            if (string.IsNullOrWhiteSpace(toUpdate.Id))
            {
                throw new Exception("The id must be provided in the body");
            }
            if (string.IsNullOrWhiteSpace(toUpdate.Name))
            {
                throw new ArgumentException("You must provide a name for the team", "name");
            }
            if (string.IsNullOrWhiteSpace(toUpdate.CaptainId))
            {
                throw new ArgumentException("You must provide a captain for the team", "captainId");
            }

            Team current = await(await _teams.FindAsync(databaseTeam => databaseTeam.Id == toUpdate.Id)).FirstOrDefaultAsync();

            if (current == null)
            {
                throw new Exception("The team you want to update doesn't exist");
            }

            // We need to change the role of the old captain
            if (current.CaptainId != toUpdate.CaptainId)
            {
                User oldCaptain = await(await _users.FindAsync(databaseUser => databaseUser.Id == current.CaptainId)).FirstOrDefaultAsync();
                User newCaptain = await(await _users.FindAsync(databaseUser => databaseUser.Id == toUpdate.CaptainId)).FirstOrDefaultAsync();

                // We must remove the new captain from it's current team
                Team oldTeam = await GetUserTeamAsync(newCaptain.Id);

                if (oldTeam != null)
                {
                    oldTeam.Members.Remove(newCaptain.Id);
                    await _teams.ReplaceOneAsync(databaseTeam => databaseTeam.Id == oldTeam.Id, oldTeam);
                }

                // We add the old captain to the team cause we are nice =P
                current.Members.Add(oldCaptain.Id);

                if (oldCaptain.Role != UserRoles.Administrator)
                {
                    oldCaptain.Role = UserRoles.Default;
                    await _users.ReplaceOneAsync(databaseUser => databaseUser.Id == oldCaptain.Id, oldCaptain);
                }

                if (newCaptain.Role != UserRoles.Administrator)
                {
                    newCaptain.Role = UserRoles.Captain;
                    await _users.ReplaceOneAsync(databaseUser => databaseUser.Id == newCaptain.Id, newCaptain);
                }
            }

            // We finally update the team, based on the current to keep members and score
            current.Name      = toUpdate.Name;
            current.CaptainId = toUpdate.CaptainId;
            current.Score     = toUpdate.Score;

            if (toUpdate.ImageId == "modified")
            {
                if (!string.IsNullOrWhiteSpace(current.ImageId))
                {
                    await _gridFS.DeleteAsync(new ObjectId(current.ImageId));
                }

                var teamImage = await _gridFS.UploadFromBytesAsync($"team_{current.Id}", toUpdate.Image);

                current.Image   = null;
                current.ImageId = teamImage.ToString();
            }


            await _teams.ReplaceOneAsync(databaseTeam => databaseTeam.Id == toUpdate.Id, current);
        }