/// <summary> /// Event triggered ich time when "uploadFile" or "updateFile" send 1 part ChunkSize /// </summary> private static void Upload_ProgressChanged(IUploadProgress progress) { Pause(); Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { if (progress.Exception != null && progress.Exception.HResult == -2146233088) { log.Error("Error[27]: Probably an error of network connections. Details: " + progress.Exception.HResult); return; } else if (progress.Exception != null && progress.Exception.HResult != -2146233088) { log.Error("Error[28]: " + progress.Exception.HResult); new ArgumentException("Error[26]: " + progress.Exception); } else if (progress.Status.ToString() == "Uploading") { if (fileSize == 0) dProgress = 0; else dProgress = 100.00 * progress.BytesSent / fileSize; ((MainWindow)Application.Current.MainWindow).pro_curr.Value = dProgress; ((MainWindow)Application.Current.MainWindow).lb_currUpload.Content = "Upload: " + FileName + " [" + FormatBytes(progress.BytesSent) + "/" + FormatBytes(fileSize) + "]"; _send_ChunkSize += _ChunkSize; if (_send_ChunkSize > fileSize) { _ChunkSize = _send_ChunkSize - fileSize; } ((MainWindow)Application.Current.MainWindow).ALLprogressBarUpdate(_ChunkSize); } else if (progress.Status.ToString() == "Completed") { if (fileSize == 0) dProgress = 0; else dProgress = 100.00 * progress.BytesSent / fileSize; if (fileSize < _ChunkSize) ((MainWindow)Application.Current.MainWindow).ALLprogressBarUpdate(fileSize); else ((MainWindow)Application.Current.MainWindow).ALLprogressBarUpdate(fileSize - _send_ChunkSize); ((MainWindow)Application.Current.MainWindow).pro_curr.Value = dProgress; ((MainWindow)Application.Current.MainWindow).lb_currUpload.Content = "Upload: " + FileName + " [" + FormatBytes(progress.BytesSent) + "/" + FormatBytes(fileSize) + "]"; log.Info("Succes upload file: " + FileName); } else if (progress.Status.ToString() == "Starting") { _send_ChunkSize = 0; ((MainWindow)Application.Current.MainWindow).lb_currUpload.Content = "Upload: " + FileName + " [0/" + FormatBytes(fileSize) + "]"; ((MainWindow)Application.Current.MainWindow).pro_curr.Value = 0; } })); }
void videosInsertRequest_ProgressChanged(IUploadProgress progress) { switch (progress.Status) { case UploadStatus.Starting: Debug.WriteLine("Starting"); new Task(() => { UpdateUIAsync(progress, "starting"); }).Start(); break; case UploadStatus.Uploading: Debug.WriteLine(progress.BytesSent + " bytes sent. Please wait."); new Task(() => { UpdateUIAsync(progress, "uploading"); }).Start(); break; case UploadStatus.Completed: Debug.WriteLine("Upload completed on YouTube."); new Task(() => { UpdateUIAsync(progress, "completed"); }).Start(); break; case UploadStatus.Failed: Debug.WriteLine("An error prevented the upload from completing.\n" + progress.Exception); new Task(() => { UpdateUIAsync(progress, "failed"); }).Start(); break; } }
/// <summary> /// Asynchronously uploads the file. /// </summary> /// <returns></returns> protected override async Task <SerializableAPIResult <CloudStorageServiceAPIFile> > UploadFileAsync() { SerializableAPIResult <CloudStorageServiceAPIFile> result = new SerializableAPIResult <CloudStorageServiceAPIFile>(); try { m_fileId = m_fileId ?? await GetFileIdAsync().ConfigureAwait(false); byte[] content = Util.GZipCompress(SettingsFileContentByteArray).ToArray(); using (DriveService client = GetClient()) using (Stream stream = Util.GetMemoryStream(content)) { ResumableUpload <GoogleFile, GoogleFile> request; GoogleFile fileMetadata = new GoogleFile { Name = SettingsFileNameWithoutExtension }; if (String.IsNullOrWhiteSpace(m_fileId)) { //Upload fileMetadata.Parents = new List <string> { Spaces }; request = client.Files.Create(fileMetadata, stream, ContentType); ((FilesResource.CreateMediaUpload)request).Fields = "id, name"; } else { //Update request = client.Files.Update(fileMetadata, m_fileId, stream, ContentType); ((FilesResource.UpdateMediaUpload)request).AddParents = Spaces; ((FilesResource.UpdateMediaUpload)request).Fields = "id, name"; } // Do the actual upload IUploadProgress response = await request.UploadAsync().ConfigureAwait(false); m_fileId = request.ResponseBody?.Id; // Chceck response for exception if (response.Exception != null) { result.Error = new SerializableAPIError { ErrorMessage = response.Exception.Message }; } } } catch (GoogleApiException exc) { result.Error = new SerializableAPIError { ErrorMessage = exc.Error.Message }; } catch (TokenResponseException exc) { IsAuthenticated = false; result.Error = new SerializableAPIError { ErrorMessage = exc.Error.ErrorDescription ?? exc.Error.Error }; } catch (Exception exc) { result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } return(result); }
private void ReqOnProgressChanged(IUploadProgress progress) { var uploadingPercent = (int)(progress.BytesSent * 100 / fileForUploadSize); UploadFileProgressChanged?.Invoke(progress.Status.ToString(), progress.BytesSent, fileForUploadSize, uploadingPercent); }
protected void DriveService_ProgressChanged(IUploadProgress uploadProgress) { try { var status = StatusType.NotStarted; long bytesProcessed = uploadProgress.BytesSent; long totalBytes = FileSize; Exception processException = uploadProgress.Exception; if (uploadProgress.Status == UploadStatus.Completed) { status = StatusType.Completed; } else if (uploadProgress.Status == UploadStatus.Uploading) { status = StatusType.Processing; } else if (uploadProgress.Status == UploadStatus.Failed) { status = StatusType.Failed; } else { status = StatusType.Starting; } UpdateProgress(status, bytesProcessed, totalBytes, processException); if (Processed) { try { if (Completed) { _LastWriteTime = API.DriveService.GetFileLastWriteTime(FilePath); DateTime modifiedDate = _FileInfo.ModifiedDate; if (!API.DriveService.IsDateTimeEqual(_LastWriteTime, modifiedDate)) { try { _LastWriteTime = API.DriveService.SetFileLastWriteTime(FilePath, modifiedDate); } catch (Exception exception) { Log.Error(exception, false, false); System.Threading.Thread.Sleep(500); } } if (!API.DriveService.IsDateTimeEqual(_LastWriteTime, modifiedDate)) { try { using (API.DriveService.Connection connection = API.DriveService.Connection.Create()) { File file = _FileInfo._file; file.ModifiedDate = _LastWriteTime.ToUniversalTime(); Google.Apis.Drive.v2.FilesResource.UpdateRequest updateRequest = connection.Service.Files.Update(file, file.Id); updateRequest.SetModifiedDate = true; _FileInfo._file = updateRequest.Execute(); modifiedDate = _FileInfo.ModifiedDate; } } catch (Exception exception) { Log.Error(exception, false, false); System.Threading.Thread.Sleep(500); } } if (!API.DriveService.IsDateTimeEqual(_LastWriteTime, modifiedDate)) { try { using (API.DriveService.Connection connection = API.DriveService.Connection.Create()) { File file = _FileInfo._file; file.ModifiedDate = _LastWriteTime.ToUniversalTime(); Google.Apis.Drive.v2.FilesResource.PatchRequest patchRequest = connection.Service.Files.Patch( file, file .Id); patchRequest.SetModifiedDate = true; _FileInfo._file = patchRequest.Execute(); modifiedDate = _FileInfo.ModifiedDate; } } catch (Exception exception) { Log.Error(exception, false, false); System.Threading.Thread.Sleep(500); } } if (!API.DriveService.IsDateTimeEqual(_LastWriteTime, modifiedDate)) { // hopefully at least this will keep the upload process from firing off _FileInfo._file.ModifiedDate = _LastWriteTime.ToUniversalTime(); } } } catch (Exception exception) { Log.Error(exception, false); if (!Failed) { _ExceptionMessage = exception.Message; _Status = StatusType.Failed; } } } InvokeOnProgressEvent(); } catch (Exception exception) { Log.Error(exception, false); } }
/// <summary> /// Separate callback which is used in response processing when progress changed. /// </summary> /// <param name="progress">Reporting upload progress.</param> private static void Upload_ProgressChanged(IUploadProgress progress) { _logger.Info($"{progress.Status} {progress.BytesSent}"); GlobalMessageHandler.OutputMessage($"{progress.Status} {progress.BytesSent}"); }
private static void Request_ProgressChanged(IUploadProgress obj) { throw new NotImplementedException(); }
void VideosInsertRequest_ProgressChanged(IUploadProgress progress) { BytesSent?.Invoke(progress.BytesSent); }
// ReSharper disable once UnusedMethodReturnValue.Local private bool UploadApk(string apkFileName, string expansionFileName, string track, List <UpdateInfo> apkChanges) { if (_serviceThread != null) { return(false); } if (!File.Exists(apkFileName)) { UpdateStatus("Apk file not existing"); return(false); } if (!string.IsNullOrEmpty(expansionFileName)) { if (expansionFileName != ExpansionKeep) { if (!File.Exists(expansionFileName)) { UpdateStatus("Expansion file not existing"); return(false); } } } UpdateStatus(string.Empty); _cts = new CancellationTokenSource(); _serviceThread = new Thread(async() => { UpdateStatus(string.Empty); StringBuilder sb = new StringBuilder(); try { if (apkChanges != null) { sb.Append("Changes info for languages: "); foreach (UpdateInfo updateInfo in apkChanges) { sb.Append($"{updateInfo.Language} "); } sb.AppendLine(); UpdateStatus(sb.ToString()); } UserCredential credential = await GetCredatials(); using (AndroidPublisherService service = new AndroidPublisherService(GetInitializer(credential))) { EditsResource edits = service.Edits; EditsResource.InsertRequest editRequest = edits.Insert(null, PackageName); AppEdit appEdit = await editRequest.ExecuteAsync(_cts.Token); bool reuseExpansion = false; ExpansionInfo expansionInfo = await GetNewestExpansionFile(edits, appEdit); if (expansionInfo != null) { sb.AppendLine($"Latest expansion: apk version={expansionInfo.ApkVersion}, expansion version={expansionInfo.ExpansionVersion}, size={expansionInfo.FileSize}"); if (!string.IsNullOrEmpty(expansionFileName)) { if (expansionFileName == ExpansionKeep) { sb.AppendLine("Reusing old expansion file"); reuseExpansion = true; } else { FileInfo fileInfo = new FileInfo(expansionFileName); if (fileInfo.Exists && fileInfo.Length == expansionInfo.FileSize) { sb.AppendLine("Size unchanged, reusing old expansion file"); reuseExpansion = true; } } } } Apk apkUploaded = null; using (FileStream apkStream = new FileStream(apkFileName, FileMode.Open, FileAccess.Read)) { long fileLength = (apkStream.Length > 0) ? apkStream.Length : 1; EditsResource.ApksResource.UploadMediaUpload upload = edits.Apks.Upload(PackageName, appEdit.Id, apkStream, "application/vnd.android.package-archive"); upload.ChunkSize = ResumableUpload.MinimumChunkSize; upload.ProgressChanged += progress => { UpdateStatus(sb.ToString() + $"Apk progress: {100 * progress.BytesSent / fileLength}%"); }; upload.ResponseReceived += apk => { apkUploaded = apk; }; IUploadProgress uploadProgress = await upload.UploadAsync(_cts.Token); sb.AppendLine($"Upload status: {uploadProgress.Status.ToString()}"); UpdateStatus(sb.ToString()); if (uploadProgress.Exception != null) { throw uploadProgress.Exception; } } int?versionCode = apkUploaded?.VersionCode; if (!versionCode.HasValue) { throw new Exception("No apk version code"); } sb.AppendLine($"Version code uploaded: {versionCode.Value}"); UpdateStatus(sb.ToString()); if (!string.IsNullOrEmpty(expansionFileName) && !reuseExpansion) { using (FileStream expansionStream = new FileStream(expansionFileName, FileMode.Open, FileAccess.Read)) { long fileLength = (expansionStream.Length > 0) ? expansionStream.Length : 1; EditsResource.ExpansionfilesResource.UploadMediaUpload upload = edits.Expansionfiles.Upload(PackageName, appEdit.Id, versionCode.Value, EditsResource.ExpansionfilesResource.UploadMediaUpload.ExpansionFileTypeEnum.Main, expansionStream, "application/octet-stream"); upload.ChunkSize = ResumableUpload.MinimumChunkSize; upload.ProgressChanged += progress => { UpdateStatus(sb.ToString() + $"Expansion progress: {100 * progress.BytesSent / fileLength}%"); }; IUploadProgress uploadProgress = await upload.UploadAsync(_cts.Token); sb.AppendLine($"Upload status: {uploadProgress.Status.ToString()}"); UpdateStatus(sb.ToString()); if (uploadProgress.Exception != null) { throw uploadProgress.Exception; } } } else { if (expansionInfo != null) { ExpansionFile expansionRef = new ExpansionFile { ReferencesVersion = expansionInfo.ExpansionVersion }; await edits.Expansionfiles.Update(expansionRef, PackageName, appEdit.Id, versionCode.Value, EditsResource.ExpansionfilesResource.UpdateRequest.ExpansionFileTypeEnum.Main).ExecuteAsync(_cts.Token); sb.AppendLine($"Expansion version {expansionInfo.ExpansionVersion} assigned"); } else { sb.AppendLine("No existing expansion found!"); } } Track updateTrack = new Track { VersionCodes = new List <int?> { versionCode.Value } }; EditsResource.TracksResource.UpdateRequest updateRequest = edits.Tracks.Update(updateTrack, PackageName, appEdit.Id, track); Track updatedTrack = await updateRequest.ExecuteAsync(_cts.Token); sb.AppendLine($"Track updated: {updatedTrack.TrackValue}"); UpdateStatus(sb.ToString()); if (apkChanges != null) { foreach (UpdateInfo updateInfo in apkChanges) { ApkListing apkListing = new ApkListing { RecentChanges = updateInfo.Changes }; await edits.Apklistings.Update(apkListing, PackageName, appEdit.Id, versionCode.Value, updateInfo.Language).ExecuteAsync(_cts.Token); sb.AppendLine($"Changes for language {updateInfo.Language} updated"); UpdateStatus(sb.ToString()); } } EditsResource.CommitRequest commitRequest = edits.Commit(PackageName, appEdit.Id); AppEdit appEditCommit = await commitRequest.ExecuteAsync(_cts.Token); sb.AppendLine($"App edit committed: {appEditCommit.Id}"); UpdateStatus(sb.ToString()); } } catch (Exception e) { sb.AppendLine($"Exception: {e.Message}"); } finally { _serviceThread = null; _cts.Dispose(); UpdateStatus(sb.ToString()); } }); _serviceThread.Start(); return(true); }
private void GoogleDriveUploadProgress(IUploadProgress progress) { this.m_uploadProgressChangedCallback?.Invoke(progress); }
static void Upload_ProgressChanged(IUploadProgress progress) { Console.WriteLine(progress.Status + " " + progress.BytesSent); }
public void Report(IUploadProgress value) => Interlocked.Exchange(ref _bytesProcessed, value.BytesSent);
public static string UploadByGoogleDrive(byte[] bytes, string fileName, string mimeType, out bool status) { status = false; var fileDownloadLink = string.Empty; var workingDirectory = Environment.CurrentDirectory; string projectDirectory = Directory.GetParent(workingDirectory).Parent.FullName; var _filePath = $"{projectDirectory}/files/"; var filesPath = Path.Combine(_filePath, fileName); DriveService service = GetService(); using (FileStream file = File.Create(filesPath)) { file.Write(bytes, 0, bytes.Length); } var FileMetaData = new google.File() { Name = fileName, MimeType = mimeType, Parents = new List <string> { //"1xT8DV-wjRRFzV9v8gjP0WbllAuJMK_Mi"//google drive folder id "1hyvrLDIOddffCwGqJt_fAlo8PrFlD5hS" } }; IUploadProgress response = null; FilesResource.CreateMediaUpload request; using (var stream = new System.IO.FileStream(filesPath, System.IO.FileMode.Open)) { request = service.Files.Create(FileMetaData, stream, FileMetaData.MimeType); request.Fields = "id"; request.Fields = "name"; request.Fields = "mimeType"; request.Fields = "webViewLink"; response = request.Upload(); } var result = (int)response.Status; if (result == (int)UploadStatus.Completed) { status = true; //Console.WriteLine($"File is successfully uploaded on Google Drive"); } else { ErrorLog.InfoMessage("File is not uploaded on Google Drive for this contact"); Console.WriteLine("File is not uploaded on Google Drive for this contact"); } var fileResponse = request.ResponseBody; if (fileResponse != null) { fileDownloadLink = fileResponse.WebViewLink; ErrorLog.InfoMessage($"File is successfully uploaded on Google Drive {fileDownloadLink}"); Console.WriteLine($"File is successfully uploaded on Google Drive {fileDownloadLink}"); } return(fileDownloadLink); }
private void Upload_ProgressChanged(IUploadProgress progress) { var uploadingPercent = (int)(progress.BytesSent * 100 / uploadingFileBytesAll); UploadFileProgressChanged?.Invoke(progress.Status.ToString(), progress.BytesSent, uploadingFileBytesAll, uploadingPercent); }
void Upload_ProgressChanged(IUploadProgress progress) { #if DEBUG System.Diagnostics.Debug.WriteLine(progress.Status + " " + progress.BytesSent); #endif }
static void VideosInsertRequestProgressChanged(IUploadProgress progress) { switch (progress.Status) { case UploadStatus.Uploading: Debug.WriteLine("{0} bytes sent.", progress.BytesSent); break; case UploadStatus.Failed: MainForm.LogMessageToFile(String.Format("Upload to YouTube failed ({0})", progress.Exception)); break; } }
private static void RequestProgressChanged(IUploadProgress obj) { switch (obj.Status) { case UploadStatus.Completed: MainForm.LogMessageToFile("Uploaded file to google drive"); break; case UploadStatus.Failed: if (obj.Exception!=null) MainForm.LogErrorToFile("Upload to google drive failed ("+obj.Exception.Message+")"); else { MainForm.LogErrorToFile("Upload to google drive failed"); } break; } if (obj.Exception != null) { MainForm.LogExceptionToFile(obj.Exception); } }
private void DriveService_ProgressChanged(IUploadProgress uploadProgress) { try { var status = StatusType.NotStarted; long bytesProcessed = uploadProgress.BytesSent; long totalBytes = FileSize; Exception processException = uploadProgress.Exception; if (uploadProgress.Status == UploadStatus.Completed) { status = StatusType.Completed; } else if (uploadProgress.Status == UploadStatus.Uploading) { status = StatusType.Processing; } else if (uploadProgress.Status == UploadStatus.Failed) { status = StatusType.Failed; } else { status = StatusType.Starting; } UpdateProgress(status, bytesProcessed, totalBytes, processException); if (Processed) { try { API.DriveService.DeleteFile(_filePath); if (Completed) { if (!FileInfo.IsFolder) { _filePath = _FileInfo.FilePath; } } else { _filePath = ""; } } catch (Exception exception) { Log.Error(exception, false); if (!Failed) { _ExceptionMessage = exception.Message; _Status = StatusType.Failed; } } } InvokeOnProgressEvent(); } catch (Exception exception) { Log.Error(exception, false); } }
public static void Upload_Progress(IUploadProgress progress) { BytesProgress = (progress.BytesSent * 100) / BytesTotal; StatusInConsole(progress.BytesSent, BytesTotal, FirstExec); FirstExec = false; }
private static void RequestProgressChanged(IUploadProgress obj) { switch (obj.Status) { case UploadStatus.Failed: if (obj.Exception!=null) Logger.LogErrorToFile("Upload to Google Drive failed ("+obj.Exception.Message+")"); else { Logger.LogErrorToFile("Upload to Google Drive failed"); } break; } if (obj.Exception != null) { Logger.LogExceptionToFile(obj.Exception); } }
static void VideosInsertRequestProgressChanged(IUploadProgress progress) { switch (progress.Status) { case UploadStatus.Uploading: //Debug.WriteLine("{0} bytes sent.", progress.BytesSent); break; case UploadStatus.Failed: Logger.LogMessageToFile($"Upload to YouTube failed ({progress.Exception})"); break; } }
public async Task <string> UploadVideo(string filePath, string title, string description, CancellationToken cancellationToken, Action <double, double> progressChanged = null) { var youtubeService = this.ConnectToYoutubeService(); var video = new Video { Snippet = new VideoSnippet { Title = title, Description = description, Tags = new[] { "Sports" }, DefaultLanguage = "en" }, Status = new VideoStatus { PrivacyStatus = "unlisted" } }; string createdVideoId; using (var fileStream = new FileStream(filePath, FileMode.Open)) { long bytesSent = 0; var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*"); if (progressChanged != null) { videosInsertRequest.ProgressChanged += progress => { bytesSent = progress.BytesSent; progressChanged(videosInsertRequest.ContentStream.Length, progress.BytesSent); }; } const int Kb = 1024; const int MinimumChunkSize = 256 * Kb; videosInsertRequest.ChunkSize = MinimumChunkSize; IUploadProgress uploadProgress = null; try { uploadProgress = await videosInsertRequest.UploadAsync(cancellationToken); if (uploadProgress.Exception != null) { throw uploadProgress.Exception; } } catch (TaskCanceledException) when(cancellationToken.IsCancellationRequested) { throw; } catch (Exception e) { var lastException = e; int maxRetrievesCount = 3; int retriesCount = 0; long previousBytesSent = 0; long minimalKbToProlongUpload = 500; while (maxRetrievesCount > retriesCount && (uploadProgress == null || uploadProgress.Status != UploadStatus.Completed)) { retriesCount++; try { uploadProgress = await videosInsertRequest.ResumeAsync(cancellationToken); } catch (Exception exception) { lastException = exception; // Если мы залили хотябы 500кб с предыдущего разрыва, значит обнуляем счетчик попыток. Так понемногу и всё видео зальём. if (Math.Abs(bytesSent - previousBytesSent) > minimalKbToProlongUpload) { retriesCount = 0; } previousBytesSent = bytesSent; Task.Delay(TimeSpan.FromSeconds(2), cancellationToken).Wait(cancellationToken); } } if (uploadProgress == null || uploadProgress.Status != UploadStatus.Completed) { throw new YoutubeException($"Video upload failed (Retries count = {retriesCount}). See inner exception for details.", lastException); } } createdVideoId = videosInsertRequest.ResponseBody.Id; if (createdVideoId == null) { throw new YoutubeException(videosInsertRequest.ResponseBody.Status.UploadStatus); } } return(createdVideoId); }