Exemplo n.º 1
0
        public void UploadFile(ConversationMessageModel message, FileModel file)
        {
            try
            {
                IsBusy = true;
                _writer.Write(MessageDictionary.UploadFile);
                if (_reader.ReadByte() == MessageDictionary.OK)
                {
                    _writer.Write(file.Name);
                    _writer.Write(file.ContentType.MediaType);
                    _writer.Write(file.DateAdded.ToString("dd-MM-yyyy"));

                    SendFile(new MemoryStream(file.Data));

                    string fileId = _reader.ReadString();

                    file.Id = fileId;

                    FileUploaded?.Invoke(this, new FileUploadedEventArgs()
                    {
                        Message = message, File = file
                    });
                }
                IsBusy = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
                ErrorHelper.LogError(ex);
                Logout();
            }
        }
Exemplo n.º 2
0
        private void InitializeAppResponders(AppConf[] configs)
        {
            string currentMode = ProcessMode.Current.Mode.ToString();

            configs.Where(c => c.ProcessMode.Equals(currentMode)).Each(ac =>
            {
                OnAppContentResponderInitializing(ac);
                Logger.RestartLoggingThread();
                AppContentResponder responder = new AppContentResponder(this, ac)
                {
                    Logger = Logger
                };
                Subscribers.Each(logger =>
                {
                    logger.RestartLoggingThread();
                    responder.Subscribe(logger);
                });
                string appName = ac.Name.ToLowerInvariant();
                responder.Initialize();
                responder.FileUploading      += (o, a) => FileUploading?.Invoke(o, a);
                responder.FileUploaded       += (o, a) => FileUploaded?.Invoke(o, a);
                responder.Responded          += (r, context) => OnResponded(context);
                responder.NotResponded       += (r, context) => OnNotResponded(context);
                AppContentResponders[appName] = responder;

                OnAppContentResponderInitialized(ac);
            });
        }
Exemplo n.º 3
0
        private async void Upload(FileResult file)
        {
            try
            {
                using (Busy())
                {
                    using (var stream = await file.OpenReadAsync())
                    {
                        using (var client = new HttpClient())
                            using (var formData = new MultipartFormDataContent())
                            {
                                formData.Add(new StreamContent(stream), "file1", file.FileName);

                                formData.Headers.TryAddWithoutValidation("session-handle", (await SessionHandler.Session.Ping()).Handle);

                                var response = await client.PostAsync(new Uri(SessionHandler.Session.Configuration.Uri(), "/majaocr"), formData);

                                response.EnsureSuccessStatusCode();
                                var id = await response.Content.ReadAsStringAsync();

                                await SessionHandler.ExecuteOpenbiCommand((s, t) => s.AnalyzeOcrDocument(id));

                                FileUploaded?.Invoke(this, new StringEventArgs(id));
                            }
                    }
                }
            }
            catch (Exception ex)
            {
                DisplayException(ex);
            }
        }
Exemplo n.º 4
0
 protected void SetContentResponder()
 {
     _contentResponder = new ContentResponder(GetCurrentConf(true), MainLogger);
     _contentResponder.FileUploading += (o, a) => FileUploading?.Invoke(o, a);
     _contentResponder.FileUploaded  += (o, a) => FileUploaded?.Invoke(o, a);
     AddResponder(_contentResponder);
 }
        public async Task <FileCommon> UploadFile(FileCommon file)
        {
            var uploadedFile = await _httpService.Post <FileCommon, FileCommon>("api/file/upload", file);

            FileUploaded?.Invoke(uploadedFile);

            return(uploadedFile);
        }
Exemplo n.º 6
0
 public DialogResult ShowDialog()
 {
     FileUploadButton.SimulateClick();
     FileUploadButton.Command =
         new ParameterizedCommand(
             parameter =>
             FileUploaded?.Invoke(this,
                                  new OpenFileDialogEventArgs(parameter.Parameter as FileUploadEventArgs)));
     return(DialogResult.Unspecified);
 }
Exemplo n.º 7
0
        private async Task ProcessChannelMessageAsync(Message message)
        {
            if (message.Type != MessageType.Photo)
            {
                return;
            }

            var maxResolutionPhoto = message.Photo.First(x => x.FileSize == message.Photo.Max(x => x.FileSize));

            var ms     = new MemoryStream();
            var stream = await _client.GetInfoAndDownloadFileAsync(maxResolutionPhoto.FileId, ms);

            await Task.Delay(5000);

            FileUploaded?.Invoke(ms, message.Caption);
        }
        public async Task UploadAsync(Entities.RequestFile file)
        {
            var imageObject = await _client.UploadObjectAsync(
                bucket : file.Bucket,
                objectName : file.Name,
                contentType : file.ContentType,
                source : new MemoryStream(file.Data)
                );

            var response = new ResponseFile {
                Name = file.Name, Uri = new Uri(imageObject.MediaLink)
            };
            var args = new UploadFileEventArgs {
                Response = response, Request = file
            };

            FileUploaded?.Invoke(this, args);
        }
Exemplo n.º 9
0
        private void InitializeAppResponders(AppConf[] configs)
        {
            configs.Each(ac =>
            {
                OnAppContentResponderInitializing(ac);
                Logger.RestartLoggingThread();
                AppContentResponder responder = new AppContentResponder(this, ac);
                responder.Logger = Logger;
                Subscribers.Each(logger =>
                {
                    logger.RestartLoggingThread();
                    responder.Subscribe(logger);
                });
                string appName = ac.Name.ToLowerInvariant();
                responder.Initialize();
                responder.FileUploading      += (o, a) => FileUploading?.Invoke(o, a);
                responder.FileUploaded       += (o, a) => FileUploaded?.Invoke(o, a);
                AppContentResponders[appName] = responder;

                OnAppContentResponderInitialized(ac);
            });
        }
Exemplo n.º 10
0
 protected virtual void OnFileUploaded(FileUploadedEventArgs e)
 {
     FileUploaded?.Invoke(this, e);
 }
        private void UploadEntry(FileTransferTask fileTransferTask)
        {
            fileTransferTask.State     = FileProcessEntryState.Preparing;
            fileTransferTask.IsWorking = true;

            try
            {
                var fileInfo = new FileInfo(fileTransferTask.Path);
                if (!fileInfo.Exists)
                {
                    fileTransferTask.State = FileProcessEntryState.FileNotFound;
                    return;
                }

                using (var fileStream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read))
                {
                    fileTransferTask.Size = fileStream.Length;

                    using (var md5Service = new MD5CryptoServiceProvider())
                        fileTransferTask.HashValue = md5Service.ComputeHash(fileStream);

                    fileStream.Position = 0;

                    fileTransferTask.State = FileProcessEntryState.Busy;

                    var sessionGuid = _fileExplorerCommand.RequestFileUpload(fileTransferTask.TargetPath,
                                                                             fileTransferTask.HashValue, fileStream.Length);

                    var packets              = (int)Math.Ceiling(fileStream.Length / (double)BufferSize);
                    var remainingLength      = fileStream.Length;
                    var lastSlowValuesUpdate = DateTime.UtcNow;
                    var lastProgressUpdate   = DateTime.UtcNow;

                    int dataDownloadedSinceLastUpdate = 0;

                    for (int i = 0; i < packets; i++)
                    {
                        int currentPacketLength;
                        if (remainingLength > BufferSize)
                        {
                            currentPacketLength = BufferSize;
                            remainingLength    -= BufferSize;
                        }
                        else
                        {
                            currentPacketLength = (int)remainingLength;
                        }

                        var buffer = new byte[currentPacketLength];
                        fileStream.Read(buffer, 0, currentPacketLength);
                        _fileExplorerCommand.SendUploadPackage(sessionGuid, buffer);

                        dataDownloadedSinceLastUpdate += currentPacketLength;

                        var slowUpdateTimeDifference = DateTime.UtcNow - lastSlowValuesUpdate;
                        if (slowUpdateTimeDifference > TimeSpan.FromMilliseconds(400))
                        {
                            fileTransferTask.Speed         = dataDownloadedSinceLastUpdate / slowUpdateTimeDifference.TotalSeconds;
                            fileTransferTask.EstimatedTime = TimeSpan.FromSeconds(remainingLength / fileTransferTask.Speed);

                            lastSlowValuesUpdate          = DateTime.UtcNow;
                            dataDownloadedSinceLastUpdate = 0;
                        }

                        if (DateTime.UtcNow - lastProgressUpdate > TimeSpan.FromMilliseconds(50))
                        {
                            fileTransferTask.Progress      = fileTransferTask.ProcessedSize / (double)fileStream.Length;
                            fileTransferTask.ProcessedSize = fileStream.Length - remainingLength;
                            UpdateProgress();

                            lastProgressUpdate = DateTime.UtcNow;
                        }

                        if (fileTransferTask.IsCanceled)
                        {
                            fileTransferTask.State         = FileProcessEntryState.Canceled;
                            fileTransferTask.EstimatedTime = TimeSpan.Zero;
                            fileTransferTask.Speed         = 0;

                            _fileExplorerCommand.CancelFileUpload(sessionGuid);
                            return;
                        }

                        fileTransferTask.UpdateProgress();
                    }

                    fileTransferTask.Progress      = 1;
                    fileTransferTask.ProcessedSize = fileStream.Length;
                    fileTransferTask.EstimatedTime = TimeSpan.Zero;
                    UpdateProgress();
                    fileTransferTask.UpdateProgress();

                    var finished = _fileExplorerCommand.FinishFileUpload(sessionGuid);
                    switch (finished)
                    {
                    case UploadResult.Succeed:
                        fileTransferTask.State = FileProcessEntryState.Succeed;

                        FileUploaded?.Invoke(this,
                                             new FileEntry
                        {
                            CreationTime = fileInfo.CreationTime,
                            LastAccess   = fileInfo.LastAccessTime,
                            Name         = fileInfo.Name,
                            Path         = fileTransferTask.TargetPath,
                            Size         = fileInfo.Length
                        });
                        break;

                    case UploadResult.HashValuesDoNotMatch:
                        fileTransferTask.State = FileProcessEntryState.HashValuesNotMatch;
                        break;

                    case UploadResult.InvalidFileLength:
                        fileTransferTask.State = FileProcessEntryState.InvalidFileLength;
                        break;

                    default:
                        fileTransferTask.State = FileProcessEntryState.Failed;
                        break;
                    }

                    fileTransferTask.Progress      = 1;
                    fileTransferTask.EstimatedTime = TimeSpan.Zero;
                    fileTransferTask.Speed         = 0;
                }
            }
            catch (Exception exception)
            {
                fileTransferTask.State = FileProcessEntryState.Failed;
                LogManager.GetCurrentClassLogger().Error(exception, "Upload failed");
            }
            finally
            {
                fileTransferTask.IsWorking  = false;
                fileTransferTask.IsFinished = true;
            }
        }