Exemple #1
0
        protected virtual void DefaultUpload(string filePath)
        {
            Uploading?.Invoke(this, new ElementActionEventArgs(this));

            WrappedElement.SendKeys(filePath);

            Uploaded?.Invoke(this, new ElementActionEventArgs(this));
        }
        public void Upload(string source, string target, Func <string, string> renameCallback, bool deleteSourceFile = false)
        {
            if (string.IsNullOrWhiteSpace(source))
            {
                throw new ArgumentNullException(nameof(source));
            }

            if (string.IsNullOrWhiteSpace(target))
            {
                throw new ArgumentNullException(nameof(target));
            }

            if (!IsConnected)
            {
                throw new SftpProviderException("Connect to server before upload.");
            }

            var   random     = new Random();
            var   totalBytes = (ulong)random.Next(1024 * 10, 1024 * 1024);
            ulong bytes      = 0;

            while (bytes < totalBytes)
            {
                _log.Debug(m => m("Uploading {0} to {1}", source, target));
                var uploaded = (ulong)random.Next(1024, 2048);
                if (bytes + uploaded < totalBytes)
                {
                    bytes += uploaded;
                }
                else
                {
                    bytes = totalBytes;
                }

                if (bytes < totalBytes)
                {
                    _log.Debug(m => m("Uploading {0} to {1} {2}/{3}", source, target, bytes, totalBytes));
                }
                else
                {
                    _log.Info(m => m("Upload {0} to {1} completed.", source, target));
                }
                Uploading?.Invoke(target, bytes, totalBytes);
                renameCallback?.Invoke(target);
            }

            if (!deleteSourceFile)
            {
                return;
            }

            _log.Debug($"{source} deleted.");
        }
Exemple #3
0
        /// <summary>
        /// upload file
        /// </summary>
        /// <param name="url"></param>
        /// <param name="uploadFileInfo"></param>
        /// <param name="ct"></param>
        /// <returns></returns>
        public async Task <bool> Upload(Uri url, FileInfo uploadFileInfo, CancellationToken ct = default(CancellationToken))
        {
            var headResult = await _tusCore.Head(url, ct);

            long offset = long.Parse(headResult["Upload-Offset"]);

            var tusUploadFileContext = new TusUploadContext(totalSize: uploadFileInfo.Length,
                                                            uploadedSize: offset, uploadFileInfo: uploadFileInfo, uploadFileUrl: url);

            using (var fileStream = new FileStream(uploadFileInfo.FullName, FileMode.Open, FileAccess.Read))
            {
                while (!ct.IsCancellationRequested)
                {
                    if (offset == uploadFileInfo.Length)
                    {
                        UploadFinish?.Invoke(tusUploadFileContext);
                        break;
                    }

                    //get buffer of file
                    fileStream.Seek(offset, SeekOrigin.Begin);

                    int uploadSize = GetUploadSize(tusUploadFileContext);

                    byte[] buffer    = new byte[uploadSize];
                    var    readCount = await fileStream.ReadAsync(buffer, 0, uploadSize);

                    if (readCount < uploadSize)
                    {
                        Array.Resize(ref buffer, readCount);
                    }

                    var uploadResult = await _tusCore.Patch(url, buffer, offset, ct);

                    offset = long.Parse(uploadResult["Upload-Offset"]);
                    tusUploadFileContext.UploadedSize = offset;
                    Uploading?.Invoke(tusUploadFileContext);
                }
            }

            return(true);
        }
        public void Upload(string source, string target, Func <string, string> renameCallback, bool deleteSourceFile = false)
        {
            if (string.IsNullOrWhiteSpace(source))
            {
                throw new ArgumentNullException(nameof(source));
            }

            if (string.IsNullOrWhiteSpace(target))
            {
                throw new ArgumentNullException(nameof(target));
            }

            if (!File.Exists(source))
            {
                throw new SftpProviderException($"{source} does not exist.");
            }

            if (!IsConnected)
            {
                throw new SftpProviderException("Connect to server before upload.");
            }

            var targetPath = target;

            try
            {
                CreateDirectory(targetPath);

                var completed = new ManualResetEvent(false);

                using (var fileStream = File.Open(source, FileMode.Open))
                {
                    _log.Debug(m => m("Uploading {0} to {1}", source, _host));

                    var totalBytes = (ulong)fileStream.Length;

                    if (totalBytes == 0)
                    {
                        if (!_client.Exists(target))
                        {
                            _client.Create(target).Close();
                        }
                        Uploading?.Invoke(target, 0, 0);

                        _log.Info(m => m("Upload {0} to {1} completed.", source, _host));
                    }
                    else
                    {
                        _client.UploadFile(fileStream, target, bytes =>
                        {
                            Uploading?.Invoke(target, bytes, totalBytes);

                            if (bytes == totalBytes)
                            {
                                _log.Info(m => m("Upload {0} to {1} completed.", source, _host));
                                completed.Set();
                            }
                            else
                            {
                                _log.Debug(m => m("Uploading {0} to {1} {2}/{3}", source, _host, bytes, totalBytes));
                            }
                        });

                        completed.WaitOne();
                    }

                    fileStream.Close();

                    if (renameCallback != null)
                    {
                        var renamedFile = renameCallback(targetPath);
                        if (string.CompareOrdinal(targetPath, renamedFile) != 0)
                        {
                            _client.RenameFile(targetPath, renamedFile);
                        }
                    }

                    if (!deleteSourceFile)
                    {
                        return;
                    }

                    File.Delete(source);
                    _log.Debug($"{source} deleted.");
                }
            }
            catch (Exception e)
            {
                throw new SftpProviderException(e.Message, e);
            }
        }
 protected virtual void RaiseUploadingEvent(int count)
 {
     Uploading?.Invoke(this, new UploadingEventArgs(count));
 }
        public void Upload(string source, string target, Func <string, string> renameCallback, bool deleteSourceFile = false)
        {
            if (string.IsNullOrWhiteSpace(source))
            {
                throw new ArgumentNullException(nameof(source));
            }

            if (string.IsNullOrWhiteSpace(target))
            {
                throw new ArgumentNullException(nameof(target));
            }

            if (!File.Exists(source))
            {
                throw new SftpProviderException($"{source} does not exist.");
            }

            if (string.CompareOrdinal(source, target) == 0)
            {
                throw new SftpProviderException("Target cannot be same as source.");
            }

            if (!IsConnected)
            {
                throw new SftpProviderException("Connect to server before upload.");
            }

            try
            {
                if (target.IndexOf("\\", StringComparison.InvariantCulture) != -1)
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(target));
                }

                _log.Debug(m => m("Uploading {0} to {1}", source, target));
                var   buffer = new byte[2048];
                ulong bytes  = 0;

                using (var fileStream = File.Open(source, FileMode.Open))
                {
                    var totalBytes = (ulong)fileStream.Length;

                    if (totalBytes == 0)
                    {
                        File.Create(target).Close();
                        Uploading?.Invoke(target, 0, 0);
                        _log.Info(m => m("Upload {0} to {1} completed.", source, target));
                    }
                    else
                    {
                        using (var targetFileStream = File.Create(target))
                        {
                            long bytesRead;
                            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                bytes += (ulong)bytesRead;
                                targetFileStream.Write(buffer, 0, buffer.Length);

                                _log.Debug(m => m("Uploading {0} to {1} {2}/{3}", source, target, bytes, totalBytes));
                                Uploading?.Invoke(target, bytes, totalBytes);
                            }
                            _log.Info(m => m("Upload {0} to {1} completed.", source, target));
                            Uploading?.Invoke(target, bytes, totalBytes);

                            targetFileStream.Close();
                        }
                        fileStream.Close();

                        if (renameCallback != null)
                        {
                            File.Move(target, renameCallback(target));
                        }

                        if (!deleteSourceFile)
                        {
                            return;
                        }

                        File.Delete(source);
                        _log.Debug($"{source} deleted.");
                    }
                }
            }
            catch (Exception e)
            {
                throw new SftpProviderException(e.Message, e);
            }
        }
Exemple #7
0
        public async Task <UploadResult> UploadStart(DataChunkSize dataChunkSize = DataChunkSize.ChunkSize_10MB)
        {
            youtubeSession.TryGetTarget(out YouTubeSession session);

            if (UploadingStatus == UploadingStatus.UploadCanceled)
            {
                UploadingStatus = UploadingStatus.Queued;
                video.Id        = null;
                if (mediaStream != null)
                {
                    mediaStream.Dispose();
                }
                mediaStream        = null;
                Progress           = 0;
                TotalUploaded      = 0;
                TimeRemaining      = new TimeSpan();
                videoInsertRequest = null;
                IsManuallyPaused   = false;
            }

            if (video.Id != null && (
                    UploadingStatus == UploadingStatus.UploadFailed ||
                    UploadingStatus == UploadingStatus.UploadCompleted ||
                    UploadingStatus == UploadingStatus.UpdateFailed ||
                    UploadingStatus == UploadingStatus.UpdateComplete
                    ))
            {
                UploadingStatus = UploadingStatus.UpdateStart;

                await UploadThumbnail(video.Id);

                var videoUpdateRequest = session.YouTubeService.Videos.Update(video, "snippet,status");
                var result             = await videoUpdateRequest.ExecuteAsync();

                if (result != null)
                {
                    UploadingStatus = UploadingStatus.UpdateComplete;
                    PC(nameof(UploadingStatus));
                    Completed?.Invoke(this, EventArgs.Empty);
                    return(UploadResult.Succeed);
                }
                else
                {
                    UploadingStatus = UploadingStatus.UpdateFailed;
                    PC(nameof(UploadingStatus));
                    Failed?.Invoke(this, EventArgs.Empty);
                    return(UploadResult.Succeed);
                }
            }

            if (!(UploadingStatus == UploadingStatus.Queued || UploadingStatus == UploadingStatus.UploadFailed))
            {
                return(UploadResult.AlreadyUploading);
            }

            UploadingStatus = UploadingStatus.PrepareUpload;

            bool virIsNull = videoInsertRequest == null;

            if (virIsNull)
            {
                videoInsertRequest = session.YouTubeService.Videos.Insert(video, "snippet,status", mediaStream, "video/*");
                if (videoInsertRequest == null)
                {
                    UploadingStatus = UploadingStatus.UploadFailed;
                    return(UploadResult.FailedUploadRequest);
                }

                DataChunkSize = dataChunkSize;
                videoInsertRequest.ProgressChanged += (uploadProgress) =>
                {
                    TotalUploaded = uploadProgress.BytesSent;
                    Progress      = uploadProgress.BytesSent / ( double )mediaStream.Length;
                    double percentage = (uploadProgress.BytesSent - lastSentBytes) / ( double )mediaStream.Length;
                    lastSentBytes = uploadProgress.BytesSent;
                    double totalSeconds = (DateTime.Now.TimeOfDay - startTime).TotalSeconds;
                    TimeRemaining = Progress != 0 ? TimeSpan.FromSeconds((totalSeconds / Progress) * (1 - Progress)) : TimeSpan.FromDays(999);

                    switch (uploadProgress.Status)
                    {
                    case UploadStatus.Starting:
                        startTime       = DateTime.Now.TimeOfDay;
                        UploadingStatus = UploadingStatus.UploadStart;
                        Started?.Invoke(this, EventArgs.Empty);
                        break;

                    case UploadStatus.Uploading:
                        UploadingStatus = UploadingStatus.Uploading;
                        Uploading?.Invoke(this, EventArgs.Empty);
                        break;

                    case UploadStatus.Failed:
                        UploadingStatus = UploadingStatus.UploadFailed;
                        Failed?.Invoke(this, EventArgs.Empty);
                        break;

                    case UploadStatus.Completed:
                        UploadingStatus = UploadingStatus.UploadCompleted;
                        Uploading?.Invoke(this, EventArgs.Empty);
                        Completed?.Invoke(this, EventArgs.Empty);
                        mediaStream.Dispose();
                        mediaStream = null;
                        break;
                    }

                    PC(nameof(Progress));
                    PC(nameof(UploadingStatus));
                    PC(nameof(TotalUploaded));
                    PC(nameof(TimeRemaining));
                };
                videoInsertRequest.ResponseReceived += async(video) =>
                {
                    await UploadThumbnail(video.Id);

                    foreach (var playlist in Playlists)
                    {
                        playlist.AddVideo(video.Id);
                    }
                };
            }

            try
            {
                startTime = DateTime.Now.TimeOfDay;
                cancellationTokenSource = new CancellationTokenSource();
                var uploadStatus = virIsNull ?
                                   await videoInsertRequest.UploadAsync(cancellationTokenSource.Token) :
                                   await videoInsertRequest.ResumeAsync(cancellationTokenSource.Token);

                cancellationTokenSource.Dispose();
                video = videoInsertRequest.ResponseBody ?? video;
                if (uploadStatus.Status == UploadStatus.NotStarted)
                {
                    UploadingStatus = UploadingStatus.UploadFailed;
                    return(UploadResult.CannotStartUpload);
                }
            }
            catch
            {
                UploadingStatus = UploadingStatus.UploadFailed;
                return(UploadResult.UploadCanceled);
            }

            return(UploadResult.Succeed);
        }
Exemple #8
0
 private void _adapter_Uploading(string file, ulong uploaded, ulong totalBytes)
 {
     Uploading?.Invoke(file, uploaded, totalBytes);
 }