/// <summary> /// Do the actual upload to OneDrive /// </summary> /// <param name="oAuth2Settings">OAuth2Settings</param> /// <param name="surfaceToUpload">ISurface to upload</param> /// <param name="outputSettings">OutputSettings for the image file format</param> /// <param name="title">Title</param> /// <param name="filename">Filename</param> /// <param name="progress">IProgress</param> /// <param name="token">CancellationToken</param> /// <returns>ImgurInfo with details</returns> public static async Task <OneDriveUploadResponse> UploadToOneDriveAsync(OAuth2Settings oAuth2Settings, ISurface surfaceToUpload, SurfaceOutputSettings outputSettings, string title, string filename, IProgress <int> progress = null, CancellationToken token = default) { var uploadUri = new Uri(UrlUtils.GetUploadUrl(filename)); var localBehaviour = Behaviour.ShallowClone(); if (progress != null) { localBehaviour.UploadProgress = percent => { UiContext.RunOn(() => progress.Report((int)(percent * 100)), token); }; } var oauthHttpBehaviour = OAuth2HttpBehaviourFactory.Create(oAuth2Settings, localBehaviour); using (var imageStream = new MemoryStream()) { ImageOutput.SaveToStream(surfaceToUpload, imageStream, outputSettings); imageStream.Position = 0; using (var content = new StreamContent(imageStream)) { content.Headers.Add("Content-Type", "image/" + outputSettings.Format); oauthHttpBehaviour.MakeCurrent(); return(await uploadUri.PostAsync <OneDriveUploadResponse>(content, token)); } } }
/// <summary> /// Export the capture to the specified page /// </summary> /// <param name="oneNoteApplication">IOneNoteApplication</param> /// <param name="surfaceToUpload">ISurface</param> /// <param name="page">OneNotePage</param> /// <returns>bool true if everything worked</returns> private static bool ExportToPage(IOneNoteApplication oneNoteApplication, ISurface surfaceToUpload, OneNotePage page) { if (oneNoteApplication == null) { return(false); } using (var pngStream = new MemoryStream()) { var pngOutputSettings = new SurfaceOutputSettings(OutputFormats.png, 100, false); ImageOutput.SaveToStream(surfaceToUpload, pngStream, pngOutputSettings); var base64String = Convert.ToBase64String(pngStream.GetBuffer()); var imageXmlStr = string.Format(XmlImageContent, base64String, surfaceToUpload.Screenshot.Width, surfaceToUpload.Screenshot.Height); var pageChangesXml = string.Format(XmlOutline, imageXmlStr, page.ID, OnenoteNamespace2010, page.Name); Log.Info().WriteLine("Sending XML: {0}", pageChangesXml); oneNoteApplication.UpdatePageContent(pageChangesXml, DateTime.MinValue, XMLSchema.xs2010, false); try { oneNoteApplication.NavigateTo(page.ID, null, false); } catch (Exception ex) { Log.Warn().WriteLine(ex, "Unable to navigate to the target page"); } return(true); } }
/// <summary> /// Place the bitmap on the clipboard /// </summary> /// <param name="clipboardAccessToken">IClipboardAccessToken</param> /// <param name="surface">ISurface</param> /// <param name="outputSettings">SurfaceOutputSettings specifying how to output the surface</param> public static void SetAsBitmap(this IClipboardAccessToken clipboardAccessToken, ISurface surface, SurfaceOutputSettings outputSettings) { using (var bitmapStream = new MemoryStream()) { ImageOutput.SaveToStream(surface, bitmapStream, outputSettings); bitmapStream.Seek(0, SeekOrigin.Begin); // Set the stream var clipboardFormat = ClipboardFormatExtensions.MapFormatToId(outputSettings.Format.ToString().ToUpperInvariant()); clipboardAccessToken.SetAsStream(clipboardFormat, bitmapStream); } }
/// <summary> /// Place the bitmap on the clipboard as DIB /// </summary> /// <param name="clipboardAccessToken">IClipboardAccessToken</param> /// <param name="surface">ISurface</param> public static void SetAsDeviceIndependendBitmap(this IClipboardAccessToken clipboardAccessToken, ISurface surface) { using (var bitmapStream = new MemoryStream()) { ImageOutput.SaveToStream(surface, bitmapStream, new SurfaceOutputSettings { Format = OutputFormats.bmp }); bitmapStream.Seek(Marshal.SizeOf(typeof(BitmapFileHeader)), SeekOrigin.Begin); // Set the stream clipboardAccessToken.SetAsStream(StandardClipboardFormats.DeviceIndependentBitmap, bitmapStream); } }
/// <summary> /// Place the bitmap as embedded HTML on the clipboard /// </summary> /// <param name="clipboardAccessToken">IClipboardAccessToken</param> /// <param name="surface">ISurface</param> public static void SetAsEmbeddedHtml(this IClipboardAccessToken clipboardAccessToken, ISurface surface) { using (var pngStream = new MemoryStream()) { var pngOutputSettings = new SurfaceOutputSettings(OutputFormats.png, 100, false); ImageOutput.SaveToStream(surface, pngStream, pngOutputSettings); pngStream.Seek(0, SeekOrigin.Begin); // Set the PNG stream var htmlText = GenerateHtmlDataUrlString(new NativeSize(surface.Width, surface.Height), pngStream); clipboardAccessToken.SetAsHtml(htmlText); } }
public static void ExportToPage(ISurface surfaceToUpload, OneNotePage page) { using (MemoryStream pngStream = new MemoryStream()) { SurfaceOutputSettings pngOutputSettings = new SurfaceOutputSettings(OutputFormat.png, 100, false); ImageOutput.SaveToStream(surfaceToUpload, pngStream, pngOutputSettings); string base64String = Convert.ToBase64String(pngStream.GetBuffer()); string imageXmlStr = string.Format(XML_IMAGE_CONTENT, base64String, surfaceToUpload.Image.Width, surfaceToUpload.Image.Height); string pageChangesXml = string.Format(XML_OUTLINE, new object[] { imageXmlStr, page.PageID, ONENOTE_NAMESPACE_2010, page.PageName }); using (IOneNoteApplication oneNoteApplication = COMWrapper.GetOrCreateInstance <IOneNoteApplication>()) { LOG.InfoFormat("Sending XML: {0}", pageChangesXml); oneNoteApplication.UpdatePageContent(pageChangesXml, DateTime.MinValue, XMLSchema.xs2010, false); } } }
public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description); CoreConfiguration config = IniConfig.GetIniSection <CoreConfiguration>(); SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(); string file = FilenameHelper.GetFilename(OutputFormat.png, null); string filePath = Path.Combine(config.OutputFilePath, file); using (FileStream stream = new FileStream(filePath, FileMode.Create)) { ImageOutput.SaveToStream(surface, stream, outputSettings); } exportInformation.Filepath = filePath; exportInformation.ExportMade = true; ProcessExport(exportInformation, surface); return(exportInformation); }
/// <summary> /// Upload the capture to qiniu cloud /// </summary> /// <param name="captureDetails"></param> /// <param name="surfaceToUpload">ISurface</param> /// <param name="albumPath">Path to the album</param> /// <param name="uploadUrl">out string for the url</param> /// <returns>true if the upload succeeded</returns> public bool Upload(ICaptureDetails captureDetails, ISurface surfaceToUpload, out string uploadUrl) { SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(_config.UploadFormat, _config.UploadJpegQuality, _config.UploadReduceColors); try { string filename = _config.ImageNamePrefix + DateTime.Now.ToString("yyyyMMddHHmmss") + "." + _config.UploadFormat.ToString().ToLower(); Path.GetFileName(FilenameHelper.GetFilename(_config.UploadFormat, captureDetails)); string path = Directory.GetCurrentDirectory(); string fullPath = Path.Combine(path, filename); // public static void Save(ISurface surface, string fullPath, bool allowOverwrite, SurfaceOutputSettings outputSettings, bool copyPathToClipboard) // Run upload in the background MemoryStream streamoutput = new MemoryStream(); ImageOutput.SaveToStream(surfaceToUpload, streamoutput, outputSettings); new PleaseWaitForm().ShowAndWait(Attributes.Name, Language.GetString("qiniu", LangKey.communication_wait), delegate { HttpResult result = QiniuUtils.UploadFile(streamoutput, filename); } ); // This causes an exeption if the upload failed :) //Log.DebugFormat("Uploaded to qiniu page: " + qiniuInfo.Page); uploadUrl = _config.DefaultDomain + filename; string markdownURL = "![](" + uploadUrl + ")"; Clipboard.SetText(markdownURL); return(true); } catch (Exception e) { Log.Error(e); MessageBox.Show(Language.GetString("qiniu", LangKey.upload_failure) + " " + e.Message); } uploadUrl = null; return(false); }
/// <summary> /// Run the Windows 10 OCR engine to process the text on the captured image /// </summary> /// <param name="manuallyInitiated"></param> /// <param name="surface"></param> /// <param name="captureDetails"></param> /// <returns>ExportInformation</returns> public override async Task <ExportInformation> ExportCaptureAsync(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { var exportInformation = new ExportInformation(Designation, Description); try { string text; var ocrEngine = OcrEngine.TryCreateFromUserProfileLanguages(); using (var imageStream = new MemoryStream()) { ImageOutput.SaveToStream(surface, imageStream, new SurfaceOutputSettings()); imageStream.Position = 0; var decoder = await BitmapDecoder.CreateAsync(imageStream.AsRandomAccessStream()); var softwareBitmap = await decoder.GetSoftwareBitmapAsync(); var ocrResult = await ocrEngine.RecognizeAsync(softwareBitmap); text = ocrResult.Text; } // Check if we found text if (!string.IsNullOrWhiteSpace(text)) { // Place the OCR text on the clipboard using (var clipboardAccessToken = ClipboardNative.Access()) { clipboardAccessToken.ClearContents(); clipboardAccessToken.SetAsUnicodeString(text); } } exportInformation.ExportMade = true; } catch (Exception ex) { exportInformation.ExportMade = false; exportInformation.ErrorMessage = ex.Message; } ProcessExport(exportInformation, surface); return(exportInformation); }
/// <summary> /// Export the capture to the specified page /// </summary> /// <param name="oneNoteApplication">IOneNoteApplication</param> /// <param name="surfaceToUpload">ISurface</param> /// <param name="page">OneNotePage</param> /// <returns>bool true if everything worked</returns> private static bool ExportToPage(IOneNoteApplication oneNoteApplication, ISurface surfaceToUpload, OneNotePage page) { if (oneNoteApplication == null) { return(false); } using (MemoryStream pngStream = new MemoryStream()) { SurfaceOutputSettings pngOutputSettings = new SurfaceOutputSettings(OutputFormat.png, 100, false); ImageOutput.SaveToStream(surfaceToUpload, pngStream, pngOutputSettings); string base64String = Convert.ToBase64String(pngStream.GetBuffer()); string imageXmlStr = string.Format(XML_IMAGE_CONTENT, base64String, surfaceToUpload.Image.Width, surfaceToUpload.Image.Height); string pageChangesXml = string.Format(XML_OUTLINE, new object[] { imageXmlStr, page.ID, ONENOTE_NAMESPACE_2010, page.Name }); LOG.InfoFormat("Sending XML: {0}", pageChangesXml); oneNoteApplication.UpdatePageContent(pageChangesXml, DateTime.MinValue, XMLSchema.xs2010, false); try { oneNoteApplication.NavigateTo(page.ID, null, false); } catch (Exception ex) { LOG.Warn("Unable to navigate to the target page", ex); } return(true); } }
private static async Task <ImgurImage> AnnonymousUploadToImgurAsync(ISurface surfaceToUpload, SurfaceOutputSettings outputSettings, IDictionary <string, string> otherParameters, IProgress <int> progress = null, CancellationToken token = default) { var uploadUri = new Uri(_imgurConfiguration.ApiUrl).AppendSegments("upload.json").ExtendQuery(otherParameters); var localBehaviour = Behaviour.ShallowClone(); if (progress != null) { localBehaviour.UploadProgress = percent => { UiContext.RunOn(() => progress.Report((int)(percent * 100)), token); }; } using (var imageStream = new MemoryStream()) { ImageOutput.SaveToStream(surfaceToUpload, imageStream, outputSettings); imageStream.Position = 0; using (var content = new StreamContent(imageStream)) { content.Headers.Add("Content-Type", "image/" + outputSettings.Format); localBehaviour.MakeCurrent(); return(await uploadUri.PostAsync <ImgurImage>(content, token).ConfigureAwait(false)); } } }
/// <summary> /// This will be called when the menu item in the Editor is clicked /// </summary> private async Task <string> UploadAsync(ICaptureDetails captureDetails, ISurface surfaceToUpload, CancellationToken cancellationToken = default) { string dropboxUrl = null; var outputSettings = new SurfaceOutputSettings(_dropboxPluginConfiguration.UploadFormat, _dropboxPluginConfiguration.UploadJpegQuality, false); try { var cancellationTokenSource = new CancellationTokenSource(); using (var pleaseWaitForm = new PleaseWaitForm("Dropbox", _dropboxLanguage.CommunicationWait, cancellationTokenSource)) { pleaseWaitForm.Show(); try { var filename = Path.GetFileName(FilenameHelper.GetFilename(_dropboxPluginConfiguration.UploadFormat, captureDetails)); using (var imageStream = new MemoryStream()) { ImageOutput.SaveToStream(surfaceToUpload, imageStream, outputSettings); imageStream.Position = 0; using (var streamContent = new StreamContent(imageStream)) { streamContent.Headers.ContentType = new MediaTypeHeaderValue("image/" + outputSettings.Format); dropboxUrl = await UploadAsync(filename, streamContent, null, cancellationToken); } } } finally { pleaseWaitForm.Close(); } } } catch (Exception e) { Log.Error().WriteLine(e); MessageBox.Show(_dropboxLanguage.UploadFailure + " " + e.Message); } return(dropboxUrl); }
/// <summary> /// /// </summary> /// <param name="surface"></param> /// <param name="progress"></param> /// <param name="token"></param> /// <returns></returns> public async Task <string> UploadToPicasa(ISurface surface, IProgress <int> progress = null, CancellationToken token = default) { string filename = Path.GetFileName(FilenameHelper.GetFilename(_googlePhotosConfiguration.UploadFormat, surface.CaptureDetails)); var outputSettings = new SurfaceOutputSettings(_googlePhotosConfiguration.UploadFormat, _googlePhotosConfiguration.UploadJpegQuality); // Fill the OAuth2Settings var oAuthHttpBehaviour = HttpBehaviour.Current.ShallowClone(); // Use UploadProgress if (progress != null) { oAuthHttpBehaviour.UploadProgress = percent => { UiContext.RunOn(() => progress.Report((int)(percent * 100))); }; } oAuthHttpBehaviour.OnHttpMessageHandlerCreated = httpMessageHandler => new OAuth2HttpMessageHandler(_oAuth2Settings, oAuthHttpBehaviour, httpMessageHandler); if (_googlePhotosConfiguration.AddFilename) { oAuthHttpBehaviour.OnHttpClientCreated = httpClient => httpClient.AddDefaultRequestHeader("Slug", Uri.EscapeDataString(filename)); } string response; var uploadUri = new Uri("https://picasaweb.google.com/data/feed/api/user").AppendSegments(_googlePhotosConfiguration.UploadUser, "albumid", _googlePhotosConfiguration.UploadAlbum); using (var imageStream = new MemoryStream()) { ImageOutput.SaveToStream(surface, imageStream, outputSettings); imageStream.Position = 0; using (var content = new StreamContent(imageStream)) { content.Headers.Add("Content-Type", "image/" + outputSettings.Format); oAuthHttpBehaviour.MakeCurrent(); response = await uploadUri.PostAsync <string>(content, token); } } return(ParseResponse(response)); }
/// <summary> /// Do the actual upload to Imgur /// For more details on the available parameters, see: http://api.imgur.com/resources_anon /// </summary> /// <param name="surfaceToUpload">ISurface to upload</param> /// <param name="outputSettings">OutputSettings for the image file format</param> /// <param name="title">Title</param> /// <param name="filename">Filename</param> /// <returns>ImgurInfo with details</returns> public static ImgurInfo UploadToImgur(ISurface surfaceToUpload, SurfaceOutputSettings outputSettings, string title, string filename) { IDictionary <string, object> uploadParameters = new Dictionary <string, object>(); IDictionary <string, object> otherParameters = new Dictionary <string, object>(); // add title if (title != null && config.AddTitle) { otherParameters.Add("title", title); } // add filename if (filename != null && config.AddFilename) { otherParameters.Add("name", filename); } string responseString = null; if (config.AnonymousAccess) { // add key, we only use the other parameters for the AnonymousAccess otherParameters.Add("key", IMGUR_ANONYMOUS_API_KEY); HttpWebRequest webRequest = (HttpWebRequest)NetworkHelper.CreateWebRequest(config.ImgurApiUrl + "/upload.xml?" + NetworkHelper.GenerateQueryParameters(otherParameters)); webRequest.Method = "POST"; webRequest.ContentType = "image/" + outputSettings.Format.ToString(); webRequest.ServicePoint.Expect100Continue = false; try { using (var requestStream = webRequest.GetRequestStream()) { ImageOutput.SaveToStream(surfaceToUpload, requestStream, outputSettings); } using (WebResponse response = webRequest.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream(), true)) { responseString = reader.ReadToEnd(); } LogCredits(response); } } catch (Exception ex) { LOG.Error("Upload to imgur gave an exeption: ", ex); throw; } } else { OAuthSession oAuth = new OAuthSession(ImgurCredentials.CONSUMER_KEY, ImgurCredentials.CONSUMER_SECRET); oAuth.BrowserSize = new Size(650, 500); oAuth.CallbackUrl = "http://getgreenshot.org"; oAuth.AccessTokenUrl = "http://api.imgur.com/oauth/access_token"; oAuth.AuthorizeUrl = "http://api.imgur.com/oauth/authorize"; oAuth.RequestTokenUrl = "http://api.imgur.com/oauth/request_token"; oAuth.LoginTitle = "Imgur authorization"; oAuth.Token = config.ImgurToken; oAuth.TokenSecret = config.ImgurTokenSecret; if (string.IsNullOrEmpty(oAuth.Token)) { if (!oAuth.Authorize()) { return(null); } if (!string.IsNullOrEmpty(oAuth.Token)) { config.ImgurToken = oAuth.Token; } if (!string.IsNullOrEmpty(oAuth.TokenSecret)) { config.ImgurTokenSecret = oAuth.TokenSecret; } IniConfig.Save(); } try { otherParameters.Add("image", new SurfaceContainer(surfaceToUpload, outputSettings, filename)); responseString = oAuth.MakeOAuthRequest(HTTPMethod.POST, "http://api.imgur.com/2/account/images.xml", uploadParameters, otherParameters, null); } catch (Exception ex) { LOG.Error("Upload to imgur gave an exeption: ", ex); throw; } finally { if (oAuth.Token != null) { config.ImgurToken = oAuth.Token; } if (oAuth.TokenSecret != null) { config.ImgurTokenSecret = oAuth.TokenSecret; } IniConfig.Save(); } } return(ImgurInfo.ParseResponse(responseString)); }
/// <summary> /// Do the actual upload to Imgur /// For more details on the available parameters, see: http://api.imgur.com/resources_anon /// </summary> /// <param name="surfaceToUpload">ISurface to upload</param> /// <param name="outputSettings">OutputSettings for the image file format</param> /// <param name="title">Title</param> /// <param name="filename">Filename</param> /// <returns>ImgurInfo with details</returns> public static ImgurInfo UploadToImgur(ISurface surfaceToUpload, SurfaceOutputSettings outputSettings, string title, string filename) { IDictionary <string, object> otherParameters = new Dictionary <string, object>(); // add title if (title != null && Config.AddTitle) { otherParameters["title"] = title; } // add filename if (filename != null && Config.AddFilename) { otherParameters["name"] = filename; } string responseString = null; if (Config.AnonymousAccess) { // add key, we only use the other parameters for the AnonymousAccess //otherParameters.Add("key", IMGUR_ANONYMOUS_API_KEY); HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(Config.ImgurApi3Url + "/upload.xml?" + NetworkHelper.GenerateQueryParameters(otherParameters), HTTPMethod.POST); webRequest.ContentType = "image/" + outputSettings.Format; webRequest.ServicePoint.Expect100Continue = false; SetClientId(webRequest); try { using (var requestStream = webRequest.GetRequestStream()) { ImageOutput.SaveToStream(surfaceToUpload, requestStream, outputSettings); } using (WebResponse response = webRequest.GetResponse()) { LogRateLimitInfo(response); var responseStream = response.GetResponseStream(); if (responseStream != null) { using (StreamReader reader = new StreamReader(responseStream, true)) { responseString = reader.ReadToEnd(); } } } } catch (Exception ex) { Log.Error("Upload to imgur gave an exeption: ", ex); throw; } } else { var oauth2Settings = new OAuth2Settings { AuthUrlPattern = AuthUrlPattern, TokenUrl = TokenUrl, RedirectUrl = "https://imgur.com", CloudServiceName = "Imgur", ClientId = ImgurCredentials.CONSUMER_KEY, ClientSecret = ImgurCredentials.CONSUMER_SECRET, AuthorizeMode = OAuth2AuthorizeMode.EmbeddedBrowser, BrowserSize = new Size(680, 880), RefreshToken = Config.RefreshToken, AccessToken = Config.AccessToken, AccessTokenExpires = Config.AccessTokenExpires }; // Copy the settings from the config, which is kept in memory and on the disk try { var webRequest = OAuth2Helper.CreateOAuth2WebRequest(HTTPMethod.POST, Config.ImgurApi3Url + "/upload.xml", oauth2Settings); otherParameters["image"] = new SurfaceContainer(surfaceToUpload, outputSettings, filename); NetworkHelper.WriteMultipartFormData(webRequest, otherParameters); responseString = NetworkHelper.GetResponseAsString(webRequest); } finally { // Copy the settings back to the config, so they are stored. Config.RefreshToken = oauth2Settings.RefreshToken; Config.AccessToken = oauth2Settings.AccessToken; Config.AccessTokenExpires = oauth2Settings.AccessTokenExpires; Config.IsDirty = true; IniConfig.Save(); } } if (string.IsNullOrEmpty(responseString)) { return(null); } return(ImgurInfo.ParseResponse(responseString)); }
/// <summary> /// Write the ISurface to the specified stream by using the supplied IFileConfiguration /// </summary> /// <param name="surface">ISurface</param> /// <param name="stream">Stream</param> /// <param name="fileConfiguration">IFileConfiguration</param> /// <param name="destinationFileConfiguration">IDestinationFileConfiguration</param> public static void WriteToStream(this ISurface surface, Stream stream, IFileConfiguration fileConfiguration, IDestinationFileConfiguration destinationFileConfiguration = null) { ImageOutput.SaveToStream(surface, stream, surface.GenerateOutputSettings(fileConfiguration.Choose(destinationFileConfiguration))); }
/// <summary> /// Share the surface by using the Share-UI of Windows 10 /// </summary> /// <param name="shareInfo">ShareInfo</param> /// <param name="handle">IntPtr with the handle for the hosting window</param> /// <param name="surface">ISurface with the bitmap to share</param> /// <param name="captureDetails">ICaptureDetails</param> /// <returns>Task with string, which describes the application which was used to share with</returns> private async Task Share(ShareInfo shareInfo, IntPtr handle, ISurface surface, ICaptureDetails captureDetails) { using (var imageStream = new MemoryRandomAccessStream()) using (var logoStream = new MemoryRandomAccessStream()) using (var thumbnailStream = new MemoryRandomAccessStream()) { var outputSettings = new SurfaceOutputSettings(); outputSettings.PreventGreenshotFormat(); // Create capture for export ImageOutput.SaveToStream(surface, imageStream, outputSettings); imageStream.Position = 0; Log.Debug().WriteLine("Created RandomAccessStreamReference for the image"); var imageRandomAccessStreamReference = RandomAccessStreamReference.CreateFromStream(imageStream); // Create thumbnail RandomAccessStreamReference thumbnailRandomAccessStreamReference; using (var tmpImageForThumbnail = surface.GetBitmapForExport()) using (var thumbnail = tmpImageForThumbnail.CreateThumbnail(240, 160)) { ImageOutput.SaveToStream(thumbnail, null, thumbnailStream, outputSettings); thumbnailStream.Position = 0; thumbnailRandomAccessStreamReference = RandomAccessStreamReference.CreateFromStream(thumbnailStream); Log.Debug().WriteLine("Created RandomAccessStreamReference for the thumbnail"); } // Create logo RandomAccessStreamReference logoRandomAccessStreamReference; using (var logo = GreenshotResources.GetGreenshotIcon().ToBitmap()) using (var logoThumbnail = logo.CreateThumbnail(30, 30)) { ImageOutput.SaveToStream(logoThumbnail, null, logoStream, outputSettings); logoStream.Position = 0; logoRandomAccessStreamReference = RandomAccessStreamReference.CreateFromStream(logoStream); Log.Info().WriteLine("Created RandomAccessStreamReference for the logo"); } var dataTransferManagerHelper = new DataTransferManagerHelper(handle); dataTransferManagerHelper.DataTransferManager.ShareProvidersRequested += (sender, args) => { shareInfo.AreShareProvidersRequested = true; Log.Debug().WriteLine("Share providers requested: {0}", string.Join(",", args.Providers.Select(p => p.Title))); }; dataTransferManagerHelper.DataTransferManager.TargetApplicationChosen += (dtm, args) => { shareInfo.ApplicationName = args.ApplicationName; Log.Debug().WriteLine("TargetApplicationChosen: {0}", args.ApplicationName); }; var filename = FilenameHelper.GetFilename(OutputFormats.png, captureDetails); var storageFile = await StorageFile.CreateStreamedFileAsync(filename, async streamedFileDataRequest => { shareInfo.IsDeferredFileCreated = true; // Information on the "how" was found here: https://socialeboladev.wordpress.com/2013/03/15/how-to-use-createstreamedfileasync/ Log.Debug().WriteLine("Creating deferred file {0}", filename); try { using (var deferredStream = streamedFileDataRequest.AsStreamForWrite()) { await imageStream.CopyToAsync(deferredStream).ConfigureAwait(false); await imageStream.FlushAsync().ConfigureAwait(false); } // Signal that the stream is ready streamedFileDataRequest.Dispose(); } catch (Exception) { streamedFileDataRequest.FailAndClose(StreamedFileFailureMode.Incomplete); } }, imageRandomAccessStreamReference).AsTask().ConfigureAwait(false); dataTransferManagerHelper.DataTransferManager.DataRequested += (dataTransferManager, dataRequestedEventArgs) => { var deferral = dataRequestedEventArgs.Request.GetDeferral(); try { shareInfo.IsDataRequested = true; Log.Debug().WriteLine("DataRequested with operation {0}", dataRequestedEventArgs.Request.Data.RequestedOperation); var dataPackage = dataRequestedEventArgs.Request.Data; dataPackage.OperationCompleted += (dp, eventArgs) => { Log.Debug().WriteLine("OperationCompleted: {0}, shared with", eventArgs.Operation); shareInfo.CompletedWithOperation = eventArgs.Operation; shareInfo.AcceptedFormat = eventArgs.AcceptedFormatId; shareInfo.ShareTask.TrySetResult(true); }; dataPackage.Destroyed += (dp, o) => { shareInfo.IsDestroyed = true; Log.Debug().WriteLine("Destroyed"); shareInfo.ShareTask.TrySetResult(true); }; dataPackage.ShareCompleted += (dp, shareCompletedEventArgs) => { shareInfo.IsShareCompleted = true; Log.Debug().WriteLine("ShareCompleted"); shareInfo.ShareTask.TrySetResult(true); }; dataPackage.Properties.Title = captureDetails.Title; dataPackage.Properties.ApplicationName = "Greenshot"; dataPackage.Properties.Description = "Share a screenshot"; dataPackage.Properties.Thumbnail = thumbnailRandomAccessStreamReference; dataPackage.Properties.Square30x30Logo = logoRandomAccessStreamReference; dataPackage.Properties.LogoBackgroundColor = Color.FromArgb(0xff, 0x3d, 0x3d, 0x3d); dataPackage.SetStorageItems(new[] { storageFile }); dataPackage.SetBitmap(imageRandomAccessStreamReference); } finally { deferral.Complete(); Log.Debug().WriteLine("Called deferral.Complete()"); } }; dataTransferManagerHelper.ShowShareUi(); Log.Debug().WriteLine("ShowShareUi finished."); await shareInfo.ShareTask.Task.ConfigureAwait(false); } }
/// <summary> /// Do the actual upload to Photobucket /// For more details on the available parameters, see: http://api.Photobucket.com/resources_anon /// </summary> /// <returns>PhotobucketResponse</returns> public async Task <PhotobucketInfo> UploadToPhotobucket(ISurface surfaceToUpload, SurfaceOutputSettings outputSettings, string albumPath, string title, string filename, IProgress <int> progress = null, CancellationToken token = default) { string responseString; var oAuthHttpBehaviour = _oAuthHttpBehaviour.ShallowClone(); // Use UploadProgress if (progress != null) { oAuthHttpBehaviour.UploadProgress = percent => { UiContext.RunOn(() => progress.Report((int)(percent * 100)), token); }; } _oAuthHttpBehaviour.MakeCurrent(); if (_photobucketConfiguration.Username == null || _photobucketConfiguration.SubDomain == null) { await PhotobucketApiUri.AppendSegments("users").ExtendQuery("format", "json").GetAsAsync <object>(token); } if (_photobucketConfiguration.Album == null) { _photobucketConfiguration.Album = _photobucketConfiguration.Username; } var uploadUri = PhotobucketApiUri.AppendSegments("album", _photobucketConfiguration.Album, "upload"); var signedParameters = new Dictionary <string, object> { { "type", "image" } }; // add type // add title if (title != null) { signedParameters.Add("title", title); } // add filename if (filename != null) { signedParameters.Add("filename", filename); } // Add image using (var imageStream = new MemoryStream()) { ImageOutput.SaveToStream(surfaceToUpload, imageStream, outputSettings); imageStream.Position = 0; using (var streamContent = new StreamContent(imageStream)) { streamContent.Headers.ContentType = new MediaTypeHeaderValue("image/" + outputSettings.Format); streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "\"uploadfile\"", FileName = "\"" + filename + "\"" }; HttpBehaviour.Current.SetConfig(new HttpRequestMessageConfiguration { Properties = signedParameters }); try { responseString = await uploadUri.PostAsync <string>(streamContent, token); } catch (Exception ex) { Log.Error().WriteLine(ex, "Error uploading to Photobucket."); throw; } } } if (responseString == null) { return(null); } Log.Info().WriteLine(responseString); var photobucketInfo = PhotobucketInfo.FromUploadResponse(responseString); Log.Debug().WriteLine("Upload to Photobucket was finished"); return(photobucketInfo); }
/// <summary> /// Do the actual upload to Flickr /// For more details on the available parameters, see: http://flickrnet.codeplex.com /// </summary> /// <param name="surfaceToUpload"></param> /// <param name="outputSettings"></param> /// <param name="title"></param> /// <param name="filename"></param> /// <param name="progress">IProgres is used to report the progress to</param> /// <param name="token"></param> /// <returns>url to image</returns> public static async Task <string> UploadToFlickrAsync(ISurface surfaceToUpload, SurfaceOutputSettings outputSettings, string title, string filename, CancellationToken token = default) { try { var signedParameters = new Dictionary <string, object> { { "content_type", "2" }, // content = screenshot { "tags", "Greenshot" }, { "is_public", Config.IsPublic ? "1" : "0" }, { "is_friend", Config.IsFriend ? "1" : "0" }, { "is_family", Config.IsFamily ? "1" : "0" }, { "safety_level", $"{(int) Config.SafetyLevel}" }, { "hidden", Config.HiddenFromSearch ? "1" : "2" }, { "format", "json" }, // Doesn't work... :( { "nojsoncallback", "1" } }; string photoId; using (var stream = new MemoryStream()) { ImageOutput.SaveToStream(surfaceToUpload, stream, outputSettings); stream.Position = 0; using (var streamContent = new StreamContent(stream)) { streamContent.Headers.ContentType = new MediaTypeHeaderValue("image/" + outputSettings.Format); streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "\"photo\"", FileName = "\"" + filename + "\"" }; HttpBehaviour.Current.SetConfig(new HttpRequestMessageConfiguration { Properties = signedParameters }); var response = await FlickrUploadUri.PostAsync <XDocument>(streamContent, token); photoId = (from element in response.Root.Elements() where element.Name == "photoid" select element.Value).First(); } } // Get Photo Info signedParameters = new Dictionary <string, object> { { "photo_id", photoId }, { "format", "json" }, { "nojsoncallback", "1" } }; HttpBehaviour.Current.SetConfig(new HttpRequestMessageConfiguration { Properties = signedParameters }); var photoInfo = await FlickrGetInfoUrl.PostAsync <dynamic>(signedParameters, token); if (Config.UsePageLink) { return(photoInfo.photo.urls.url[0]._content); } return(string.Format(FlickrFarmUrl, photoInfo.photo.farm, photoInfo.photo.server, photoId, photoInfo.photo.secret)); } catch (Exception ex) { Log.Error().WriteLine(ex, "Upload error: "); throw; } }
/// <summary> /// Do the actual upload to Box /// For more details on the available parameters, see: /// http://developers.box.net/w/page/12923951/ApiFunction_Upload%20and%20Download /// </summary> /// <param name="surface">ICapture</param> /// <param name="progress">IProgress</param> /// <param name="cancellationToken">CancellationToken</param> /// <returns>url to uploaded image</returns> public async Task <string> UploadToBoxAsync(ICaptureDetails captureDetails, ISurface surface, IProgress <int> progress = null, CancellationToken cancellationToken = default) { string filename = Path.GetFileName(FilenameHelper.GetFilename(_boxConfiguration.UploadFormat, captureDetails)); var outputSettings = new SurfaceOutputSettings(_boxConfiguration.UploadFormat, _boxConfiguration.UploadJpegQuality, false); var oauthHttpBehaviour = HttpBehaviour.Current.ShallowClone(); // Use UploadProgress if (progress != null) { oauthHttpBehaviour.UploadProgress = percent => { UiContext.RunOn(() => progress.Report((int)(percent * 100))); }; } oauthHttpBehaviour.OnHttpMessageHandlerCreated = httpMessageHandler => new OAuth2HttpMessageHandler(_oauth2Settings, oauthHttpBehaviour, httpMessageHandler); // TODO: See if the PostAsync<Bitmap> can be used? Or at least the HttpContentFactory? using (var imageStream = new MemoryStream()) { var multiPartContent = new MultipartFormDataContent(); var parentIdContent = new StringContent(_boxConfiguration.FolderId); parentIdContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "\"parent_id\"" }; multiPartContent.Add(parentIdContent); ImageOutput.SaveToStream(surface, imageStream, outputSettings); imageStream.Position = 0; BoxFile response; using (var streamContent = new StreamContent(imageStream)) { streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); //"image/" + outputSettings.Format); streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "\"file\"", FileName = "\"" + filename + "\"" }; // the extra quotes are important here multiPartContent.Add(streamContent); oauthHttpBehaviour.MakeCurrent(); response = await UploadFileUri.PostAsync <BoxFile>(multiPartContent, cancellationToken); } if (response == null) { return(null); } if (_boxConfiguration.UseSharedLink) { if (response.SharedLink?.Url == null) { var uriForSharedLink = FilesUri.AppendSegments(response.Id); var updateAccess = new { shared_link = new { access = "open" } }; oauthHttpBehaviour.MakeCurrent(); response = await uriForSharedLink.PostAsync <BoxFile>(updateAccess, cancellationToken); } return(response.SharedLink.Url); } return($"http://www.box.com/files/0/f/0/1/f_{response.Id}"); } }
/// <summary> /// Share the screenshot with a windows app /// </summary> /// <param name="manuallyInitiated"></param> /// <param name="surface"></param> /// <param name="captureDetails"></param> /// <returns>ExportInformation</returns> public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { var exportInformation = new ExportInformation(Designation, Description); try { var handle = PluginUtils.Host.GreenshotForm.Handle; var exportTarget = Task.Run(async() => { var taskCompletionSource = new TaskCompletionSource <string>(); using (var imageStream = new MemoryRandomAccessStream()) using (var logoStream = new MemoryRandomAccessStream()) using (var thumbnailStream = new MemoryRandomAccessStream()) { var outputSettings = new SurfaceOutputSettings(); outputSettings.PreventGreenshotFormat(); // Create capture for export ImageOutput.SaveToStream(surface, imageStream, outputSettings); imageStream.Position = 0; Log.Info("Created RandomAccessStreamReference for the image"); var imageRandomAccessStreamReference = RandomAccessStreamReference.CreateFromStream(imageStream); RandomAccessStreamReference thumbnailRandomAccessStreamReference; RandomAccessStreamReference logoRandomAccessStreamReference; // Create thumbnail using (var tmpImageForThumbnail = surface.GetImageForExport()) { using (var thumbnail = ImageHelper.CreateThumbnail(tmpImageForThumbnail, 240, 160)) { ImageOutput.SaveToStream(thumbnail, null, thumbnailStream, outputSettings); thumbnailStream.Position = 0; thumbnailRandomAccessStreamReference = RandomAccessStreamReference.CreateFromStream(thumbnailStream); Log.Info("Created RandomAccessStreamReference for the thumbnail"); } } // Create logo using (var logo = GreenshotResources.getGreenshotIcon().ToBitmap()) { using (var logoThumbnail = ImageHelper.CreateThumbnail(logo, 30, 30)) { ImageOutput.SaveToStream(logoThumbnail, null, logoStream, outputSettings); logoStream.Position = 0; logoRandomAccessStreamReference = RandomAccessStreamReference.CreateFromStream(logoStream); Log.Info("Created RandomAccessStreamReference for the logo"); } } string applicationName = null; var dataTransferManagerHelper = new DataTransferManagerHelper(handle); dataTransferManagerHelper.DataTransferManager.TargetApplicationChosen += (dtm, args) => { Log.InfoFormat("Trying to share with {0}", args.ApplicationName); applicationName = args.ApplicationName; }; var filename = FilenameHelper.GetFilename(OutputFormat.png, captureDetails); var storageFile = await StorageFile.CreateStreamedFileAsync(filename, async streamedFileDataRequest => { // Information on how was found here: https://socialeboladev.wordpress.com/2013/03/15/how-to-use-createstreamedfileasync/ Log.DebugFormat("Creating deferred file {0}", filename); try { using (var deferredStream = streamedFileDataRequest.AsStreamForWrite()) { await imageStream.CopyToAsync(deferredStream).ConfigureAwait(false); await imageStream.FlushAsync().ConfigureAwait(false); } // Signal that the stream is ready streamedFileDataRequest.Dispose(); } catch (Exception) { streamedFileDataRequest.FailAndClose(StreamedFileFailureMode.Incomplete); } // Signal transfer ready to the await down below taskCompletionSource.TrySetResult(applicationName); }, imageRandomAccessStreamReference).AsTask().ConfigureAwait(false); dataTransferManagerHelper.DataTransferManager.DataRequested += (sender, args) => { var deferral = args.Request.GetDeferral(); args.Request.Data.OperationCompleted += (dp, eventArgs) => { Log.DebugFormat("OperationCompleted: {0}, shared with", eventArgs.Operation); taskCompletionSource.TrySetResult(applicationName); }; var dataPackage = args.Request.Data; dataPackage.Properties.Title = captureDetails.Title; dataPackage.Properties.ApplicationName = "Greenshot"; dataPackage.Properties.Description = "Share a screenshot"; dataPackage.Properties.Thumbnail = thumbnailRandomAccessStreamReference; dataPackage.Properties.Square30x30Logo = logoRandomAccessStreamReference; dataPackage.Properties.LogoBackgroundColor = Color.FromArgb(0xff, 0x3d, 0x3d, 0x3d); dataPackage.SetStorageItems(new List <IStorageItem> { storageFile }); dataPackage.SetBitmap(imageRandomAccessStreamReference); dataPackage.Destroyed += (dp, o) => { Log.Debug("Destroyed."); }; deferral.Complete(); }; dataTransferManagerHelper.ShowShareUi(); return(await taskCompletionSource.Task.ConfigureAwait(false)); } }).Result; if (string.IsNullOrWhiteSpace(exportTarget)) { exportInformation.ExportMade = false; } else { exportInformation.ExportMade = true; exportInformation.DestinationDescription = exportTarget; } } catch (Exception ex) { exportInformation.ExportMade = false; exportInformation.ErrorMessage = ex.Message; } ProcessExport(exportInformation, surface); return(exportInformation); }
public bool Upload(ICaptureDetails captureDetails, Image image) { using (MemoryStream stream = new MemoryStream()) { SurfaceOutputSettings outputSettings = new SurfaceOutputSettings { Format = config.UploadFormat, JPGQuality = config.UploadJpegQuality }; ImageOutput.SaveToStream(image, null, stream, outputSettings); byte[] buffer = stream.GetBuffer(); try { string filename = Path.GetFileName(FilenameHelper.GetFilename(config.UploadFormat, captureDetails)); string contentType = $"image/{config.UploadFormat}"; TFSInfo tfsInfo = TFSUtils.UploadToTFS(buffer, captureDetails.DateTime.ToString(CultureInfo.CurrentCulture), filename, contentType); if (tfsInfo == null) { return(false); } else { if (config.TfsUploadHistory == null) { config.TfsUploadHistory = new Dictionary <string, string>(); } if (tfsInfo.ID != null) { LOG.InfoFormat("Storing TFS upload for id {0}", tfsInfo.ID); config.TfsUploadHistory.Add(tfsInfo.ID, tfsInfo.ID); config.runtimeTfsHistory.Add(tfsInfo.ID, tfsInfo); } // Make sure the configuration is save, so we don't lose the deleteHash IniConfig.Save(); // Make sure the history is loaded, will be done only once TFSUtils.LoadHistory(); // Show if (config.AfterUploadOpenHistory) { TFSHistory.ShowHistory(); } if (config.AfterUploadLinkToClipBoard && !string.IsNullOrEmpty(tfsInfo.WebEditUrl)) { Clipboard.SetText(tfsInfo.WebEditUrl); } if (config.AfterUploadOpenWorkItem && !string.IsNullOrEmpty(tfsInfo.WebEditUrl)) { System.Diagnostics.Process.Start(tfsInfo.WebEditUrl); } return(true); } } catch (Exception e) { MessageBox.Show(Language.GetString("tfs", $"{LangKey.upload_failure} {e}")); } finally { //backgroundForm.CloseDialog(); } } return(false); }