Exemplo n.º 1
0
 public SendFileModel(SendFileData data)
 {
     Id       = data.Id;
     FileName = data.FileName;
     Size     = data.SizeString;
     SizeName = CoreHelpers.ReadableBytesSize(data.Size);
 }
Exemplo n.º 2
0
 public SendFileModel(SendFileData data, GlobalSettings globalSettings)
 {
     Id       = data.Id;
     Url      = $"{globalSettings.Send.BaseUrl}/{data.Id}";
     FileName = data.FileName;
     Size     = data.SizeString;
     SizeName = CoreHelpers.ReadableBytesSize(data.Size);
 }
Exemplo n.º 3
0
 public SendFile(SendFileData file, bool alreadyEncrypted = false) : base()
 {
     Size = file.Size;
     BuildDomainModel(this, file, new HashSet <string> {
         "Id", "SizeName", "FileName"
     }, alreadyEncrypted, new HashSet <string> {
         "Id", "SizeName"
     });
 }
Exemplo n.º 4
0
        public static LinkedCorpMassResult SendFile(string accessTokenOrAppKey, SendFileData data, int timeOut = Config.TIME_OUT)
        {
            return(ApiHandlerWapper.TryCommonApi(accessToken =>
            {
                JsonSetting jsonSetting = new JsonSetting(true);

                return Senparc.Weixin.CommonAPIs.CommonJsonSend.Send <LinkedCorpMassResult>(accessToken, _urlFormat, data, CommonJsonSendType.POST, timeOut, jsonSetting: jsonSetting);
            }, accessTokenOrAppKey));
        }
Exemplo n.º 5
0
        public async void SaveFileSendAsync_HasEnouphStorage_SendFileThrows_CleansUp(SutProvider <SendService> sutProvider,
                                                                                     Send send)
        {
            var user = new User
            {
                Id            = Guid.NewGuid(),
                EmailVerified = true,
                MaxStorageGb  = 10,
            };

            var data = new SendFileData
            {
            };

            send.UserId = user.Id;
            send.Type   = SendType.File;

            var testUrl = "https://test.com/";

            sutProvider.GetDependency <IUserRepository>()
            .GetByIdAsync(user.Id)
            .Returns(user);

            sutProvider.GetDependency <IUserService>()
            .CanAccessPremium(user)
            .Returns(true);

            sutProvider.GetDependency <ISendFileStorageService>()
            .GetSendFileUploadUrlAsync(send, Arg.Any <string>())
            .Returns <string>(callInfo => throw new Exception("Problem"));

            var utcNow = DateTime.UtcNow;

            var exception = await Assert.ThrowsAsync <Exception>(() =>
                                                                 sutProvider.Sut.SaveFileSendAsync(send, data, 1 * Models.Tables.UserTests.Multiplier)
                                                                 );

            Assert.True(send.RevisionDate - utcNow < TimeSpan.FromSeconds(1));
            Assert.Equal("Problem", exception.Message);

            await sutProvider.GetDependency <ISendFileStorageService>()
            .Received(1)
            .GetSendFileUploadUrlAsync(send, Arg.Any <string>());

            await sutProvider.GetDependency <ISendRepository>()
            .Received(1)
            .UpsertAsync(send);

            await sutProvider.GetDependency <IPushNotificationService>()
            .Received(1)
            .PushSyncSendUpdateAsync(send);

            await sutProvider.GetDependency <ISendFileStorageService>()
            .Received(1)
            .DeleteFileAsync(send, Arg.Any <string>());
        }
Exemplo n.º 6
0
        public (Send, SendFileData) ToSend(Guid userId, string fileName, ISendService sendService)
        {
            var send = ToSendBase(new Send
            {
                Type   = Type,
                UserId = (Guid?)userId
            }, sendService);
            var data = new SendFileData(Name, Notes, fileName);

            return(send, data);
        }
Exemplo n.º 7
0
        public void HandleSendList(ClientObject client, string[] sha256sums)
        {
            SendFileData sfd = new SendFileData(sha256sums);

            lock (filesToSend)
            {
                if (filesToSend.ContainsKey(client))
                {
                    filesToSend.Remove(client);
                }
                filesToSend.Add(client, sfd);
            }
        }
Exemplo n.º 8
0
        public async void SaveFileSendAsync_HasEnouphStorage_Success(SutProvider <SendService> sutProvider,
                                                                     Send send)
        {
            var user = new User
            {
                Id            = Guid.NewGuid(),
                EmailVerified = true,
                MaxStorageGb  = 10,
            };

            var data = new SendFileData
            {
            };

            send.UserId = user.Id;
            send.Type   = SendType.File;

            var testUrl = "https://test.com/";

            sutProvider.GetDependency <IUserRepository>()
            .GetByIdAsync(user.Id)
            .Returns(user);

            sutProvider.GetDependency <IUserService>()
            .CanAccessPremium(user)
            .Returns(true);

            sutProvider.GetDependency <ISendFileStorageService>()
            .GetSendFileUploadUrlAsync(send, Arg.Any <string>())
            .Returns(testUrl);

            var utcNow = DateTime.UtcNow;

            var url = await sutProvider.Sut.SaveFileSendAsync(send, data, 1 *UserTests.Multiplier);

            Assert.Equal(testUrl, url);
            Assert.True(send.RevisionDate - utcNow < TimeSpan.FromSeconds(1));

            await sutProvider.GetDependency <ISendFileStorageService>()
            .Received(1)
            .GetSendFileUploadUrlAsync(send, Arg.Any <string>());

            await sutProvider.GetDependency <ISendRepository>()
            .Received(1)
            .UpsertAsync(send);

            await sutProvider.GetDependency <IPushNotificationService>()
            .Received(1)
            .PushSyncSendUpdateAsync(send);
        }
Exemplo n.º 9
0
        public void Serialize_Success()
        {
            var sut = new SendFileData
            {
                Id        = "test",
                Size      = 100,
                FileName  = "thing.pdf",
                Validated = true,
            };

            var json     = JsonSerializer.Serialize(sut);
            var document = JsonDocument.Parse(json);
            var root     = document.RootElement;

            AssertHelper.AssertJsonProperty(root, "Size", JsonValueKind.String);
            Assert.False(root.TryGetProperty("SizeString", out _));
        }
Exemplo n.º 10
0
        public async Task <string> SaveFileSendAsync(Send send, SendFileData data, long fileLength)
        {
            if (send.Type != SendType.File)
            {
                throw new BadRequestException("Send is not of type \"file\".");
            }

            if (fileLength < 1)
            {
                throw new BadRequestException("No file data.");
            }

            var storageBytesRemaining = await StorageRemainingForSendAsync(send);

            if (storageBytesRemaining < fileLength)
            {
                throw new BadRequestException("Not enough storage available.");
            }

            var fileId = Utilities.CoreHelpers.SecureRandomString(32, upper: false, special: false);

            try
            {
                data.Id        = fileId;
                data.Size      = fileLength;
                data.Validated = false;
                send.Data      = JsonConvert.SerializeObject(data,
                                                             new JsonSerializerSettings {
                    NullValueHandling = NullValueHandling.Ignore
                });
                await SaveSendAsync(send);

                return(await _sendFileStorageService.GetSendFileUploadUrlAsync(send, fileId));
            }
            catch
            {
                // Clean up since this is not transactional
                await _sendFileStorageService.DeleteFileAsync(send, fileId);

                throw;
            }
        }
Exemplo n.º 11
0
        public async void UpdateFileToExistingSendAsync_Success(SutProvider <SendService> sutProvider,
                                                                Send send)
        {
            var fileContents = "Test file content";

            var sendFileData = new SendFileData
            {
                Id   = "TEST",
                Size = fileContents.Length,
            };

            send.Type = SendType.File;
            send.Data = JsonConvert.SerializeObject(sendFileData);

            sutProvider.GetDependency <ISendFileStorageService>()
            .ValidateFileAsync(send, sendFileData.Id, sendFileData.Size, Arg.Any <long>())
            .Returns((true, sendFileData.Size));

            await sutProvider.Sut.UploadFileToExistingSendAsync(new MemoryStream(Encoding.UTF8.GetBytes(fileContents)), send);
        }
Exemplo n.º 12
0
        public async void UpdateFileToExistingSendAsync_InvalidSize(SutProvider <SendService> sutProvider,
                                                                    Send send)
        {
            var fileContents = "Test file content";

            var sendFileData = new SendFileData
            {
                Id   = "TEST",
                Size = fileContents.Length,
            };

            send.Type = SendType.File;
            send.Data = JsonSerializer.Serialize(sendFileData);

            sutProvider.GetDependency <ISendFileStorageService>()
            .ValidateFileAsync(send, sendFileData.Id, sendFileData.Size, Arg.Any <long>())
            .Returns((false, sendFileData.Size));

            var badRequest = await Assert.ThrowsAsync <BadRequestException>(() =>
                                                                            sutProvider.Sut.UploadFileToExistingSendAsync(new MemoryStream(Encoding.UTF8.GetBytes(fileContents)), send)
                                                                            );
        }
Exemplo n.º 13
0
        public async Task CreateSendAsync(Send send, SendFileData data, Stream stream, long requestLength)
        {
            if (send.Type != SendType.File)
            {
                throw new BadRequestException("Send is not of type \"file\".");
            }

            if (requestLength < 1)
            {
                throw new BadRequestException("No file data.");
            }

            var storageBytesRemaining = 0L;

            if (send.UserId.HasValue)
            {
                var user = await _userRepository.GetByIdAsync(send.UserId.Value);

                if (!(await _userService.CanAccessPremium(user)))
                {
                    throw new BadRequestException("You must have premium status to use file sends.");
                }

                if (user.Premium)
                {
                    storageBytesRemaining = user.StorageBytesRemaining();
                }
                else
                {
                    // Users that get access to file storage/premium from their organization get the default
                    // 1 GB max storage.
                    storageBytesRemaining = user.StorageBytesRemaining(
                        _globalSettings.SelfHosted ? (short)10240 : (short)1);
                }
            }
            else if (send.OrganizationId.HasValue)
            {
                var org = await _organizationRepository.GetByIdAsync(send.OrganizationId.Value);

                if (!org.MaxStorageGb.HasValue)
                {
                    throw new BadRequestException("This organization cannot use file sends.");
                }

                storageBytesRemaining = org.StorageBytesRemaining();
            }

            if (storageBytesRemaining < requestLength)
            {
                throw new BadRequestException("Not enough storage available.");
            }

            var fileId = Utilities.CoreHelpers.SecureRandomString(32, upper: false, special: false);
            await _sendFileStorageService.UploadNewFileAsync(stream, send, fileId);

            try
            {
                data.Id   = fileId;
                data.Size = stream.Length;
                send.Data = JsonConvert.SerializeObject(data,
                                                        new JsonSerializerSettings {
                    NullValueHandling = NullValueHandling.Ignore
                });
                await SaveSendAsync(send);
            }
            catch
            {
                // Clean up since this is not transactional
                await _sendFileStorageService.DeleteFileAsync(fileId);

                throw;
            }
        }
Exemplo n.º 14
0
        public static async Task <LinkedCorpMassResult> SendFileAsync(string accessTokenOrAppKey, SendFileData data, int timeOut = Config.TIME_OUT)
        {
            return(await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
            {
                JsonSetting jsonSetting = new JsonSetting(true);

                return await Senparc.Weixin.CommonAPIs.CommonJsonSend.SendAsync <LinkedCorpMassResult>(accessToken, _urlFormat, data, CommonJsonSendType.POST, timeOut, jsonSetting: jsonSetting).ConfigureAwait(false);
            }, accessTokenOrAppKey).ConfigureAwait(false));
        }