Ejemplo n.º 1
0
        /// <summary>
        ///     Do the actual upload to OneDrive
        /// </summary>
        /// <param name="oAuth2Settings">OAuth2Settings</param>
        /// <param name="surfaceToUpload">ISurface to upload</param>
        /// <param name="progress">IProgress</param>
        /// <param name="token">CancellationToken</param>
        /// <returns>OneDriveUploadResponse with details</returns>
        private async Task <OneDriveUploadResponse> UploadToOneDriveAsync(OAuth2Settings oAuth2Settings,
                                                                          ISurface surfaceToUpload, IProgress <int> progress = null,
                                                                          CancellationToken token = default)
        {
            var filename       = surfaceToUpload.GenerateFilename(CoreConfiguration, _oneDriveConfiguration);
            var uploadUri      = OneDriveUri.AppendSegments("root:", "Screenshots", filename + ":", "content");
            var localBehaviour = _oneDriveHttpBehaviour.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())
            {
                surfaceToUpload.WriteToStream(imageStream, CoreConfiguration, _oneDriveConfiguration);
                imageStream.Position = 0;
                using (var content = new StreamContent(imageStream))
                {
                    content.Headers.Add("Content-Type", surfaceToUpload.GenerateMimeType(CoreConfiguration, _oneDriveConfiguration));
                    oauthHttpBehaviour.MakeCurrent();
                    return(await uploadUri.PutAsync <OneDriveUploadResponse>(content, token));
                }
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// See <a href="https://docs.microsoft.com/en-us/rest/api/vsts/wit/attachments/create">here</a>
        /// </summary>
        /// <param name="surface">ISurface to attach</param>
        /// <returns></returns>
        public async Task <CreateAttachmentResult> CreateAttachment(ISurface surface)
        {
            _tfsHttpBehaviour.MakeCurrent();

            var client = HttpClientFactory.Create(_tfsConfiguration.TfsUri).SetBasicAuthorization("", _tfsConfiguration.ApiKey);
            Uri apiUri = _tfsConfiguration.TfsUri.AppendSegments("_apis").ExtendQuery("api-version", "3.0");

            var filename      = surface.GenerateFilename(_coreConfiguration, _tfsConfiguration);
            var attachmentUri = apiUri.AppendSegments("wit", "attachments").ExtendQuery("fileName", filename);

            using (var imageStream = new MemoryStream())
            {
                surface.WriteToStream(imageStream, _coreConfiguration, _tfsConfiguration);
                imageStream.Position = 0;
                using (var content = new StreamContent(imageStream))
                {
                    content.SetContentType("application/octet-stream");
                    var createAttachmentresult = await client.PostAsync <HttpResponse <CreateAttachmentResult, string> >(attachmentUri, content).ConfigureAwait(false);

                    if (createAttachmentresult.HasError)
                    {
                        throw new Exception(createAttachmentresult.ErrorResponse);
                    }
                    return(createAttachmentresult.Response);
                }
            }
        }
Ejemplo n.º 3
0
        /// <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="title">Title</param>
        /// <param name="progress">IProgress</param>
        /// <param name="token">CancellationToken</param>
        /// <returns>ImgurInfo with details</returns>
        public async Task <ImgurImage> UploadToImgurAsync(ISurface surfaceToUpload, string title, IProgress <int> progress = null, CancellationToken token = default)
        {
            var filename = surfaceToUpload.GenerateFilename(_coreConfiguration, _imgurConfiguration);
            IDictionary <string, string> otherParameters = new Dictionary <string, string>();

            // add title
            if (title != null && _imgurConfiguration.AddTitle)
            {
                otherParameters.Add("title", title);
            }
            // add filename
            if (filename != null && _imgurConfiguration.AddFilename)
            {
                otherParameters.Add("name", filename);
            }
            if (_imgurConfiguration.AnonymousAccess)
            {
                return(await AnnonymousUploadToImgurAsync(surfaceToUpload, otherParameters, progress, token).ConfigureAwait(false));
            }
            return(await AuthenticatedUploadToImgurAsync(_oauth2Settings, surfaceToUpload, otherParameters, progress, token).ConfigureAwait(false));
        }
Ejemplo n.º 4
0
        /// <summary>
        ///     This will be called when the menu item in the Editor is clicked
        /// </summary>
        private async Task <string> UploadAsync(ISurface surfaceToUpload, CancellationToken cancellationToken = default)
        {
            string dropboxUrl = null;

            try
            {
                var cancellationTokenSource = new CancellationTokenSource();
                using (var ownedPleaseWaitForm = _pleaseWaitFormFactory(cancellationTokenSource))
                {
                    ownedPleaseWaitForm.Value.SetDetails("Dropbox", _dropboxLanguage.CommunicationWait);
                    ownedPleaseWaitForm.Value.Show();
                    try
                    {
                        var filename = surfaceToUpload.GenerateFilename(CoreConfiguration, _dropboxPluginConfiguration);
                        using (var imageStream = new MemoryStream())
                        {
                            surfaceToUpload.WriteToStream(imageStream, CoreConfiguration, _dropboxPluginConfiguration);
                            imageStream.Position = 0;
                            using (var streamContent = new StreamContent(imageStream))
                            {
                                streamContent.Headers.ContentType = new MediaTypeHeaderValue(surfaceToUpload.GenerateMimeType(CoreConfiguration, _dropboxPluginConfiguration));
                                dropboxUrl = await UploadAsync(filename, streamContent, null, cancellationToken).ConfigureAwait(false);
                            }
                        }
                    }
                    finally
                    {
                        ownedPleaseWaitForm.Value.Close();
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error().WriteLine(e);
                MessageBox.Show(_dropboxLanguage.UploadFailure + @" " + e.Message);
            }
            return(dropboxUrl);
        }
Ejemplo n.º 5
0
        /// <summary>
        ///     Attach the content to the jira
        /// </summary>
        /// <param name="issueKey"></param>
        /// <param name="surface">ISurface</param>
        /// <param name="cancellationToken"></param>
        /// <returns>Task</returns>
        public async Task AttachAsync(string issueKey, ISurface surface, string filename = null, CancellationToken cancellationToken = default)
        {
            await CheckCredentialsAsync(cancellationToken).ConfigureAwait(true);

            using (var memoryStream = new MemoryStream())
            {
                surface.WriteToStream(memoryStream, _coreConfiguration, _jiraConfiguration);
                memoryStream.Seek(0, SeekOrigin.Begin);
                var contentType = surface.GenerateMimeType(_coreConfiguration, _jiraConfiguration);
                await _jiraClient.Attachment.AttachAsync(issueKey, memoryStream, filename ?? surface.GenerateFilename(_coreConfiguration, _jiraConfiguration), contentType, cancellationToken).ConfigureAwait(false);
            }
        }
Ejemplo n.º 6
0
        /// <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="title"></param>
        /// <param name="token"></param>
        /// <returns>url to image</returns>
        public async Task <string> UploadToFlickrAsync(ISurface surfaceToUpload, string title, CancellationToken token = default)
        {
            var filename = surfaceToUpload.GenerateFilename(CoreConfiguration, _flickrConfiguration);

            try
            {
                var signedParameters = new Dictionary <string, object>
                {
                    { "content_type", "2" }, // content = screenshot
                    { "tags", "Greenshot" },
                    { "is_public", _flickrConfiguration.IsPublic ? "1" : "0" },
                    { "is_friend", _flickrConfiguration.IsFriend ? "1" : "0" },
                    { "is_family", _flickrConfiguration.IsFamily ? "1" : "0" },
                    { "safety_level", $"{(int) _flickrConfiguration.SafetyLevel}" },
                    { "hidden", _flickrConfiguration.HiddenFromSearch ? "1" : "2" },
                    { "format", "json" }, // Doesn't work... :(
                    { "nojsoncallback", "1" }
                };

                string photoId;
                using (var stream = new MemoryStream())
                {
                    surfaceToUpload.WriteToStream(stream, CoreConfiguration, _flickrConfiguration);
                    stream.Position = 0;
                    using (var streamContent = new StreamContent(stream))
                    {
                        streamContent.Headers.ContentType        = new MediaTypeHeaderValue(surfaceToUpload.GenerateMimeType(CoreConfiguration, _flickrConfiguration));
                        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).ConfigureAwait(false);

                        photoId = (from element in response?.Root?.Elements() ?? Enumerable.Empty <XElement>()
                                   where element.Name == "photoid"
                                   select element.Value).FirstOrDefault();
                    }
                }

                // 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).ConfigureAwait(false);

                if (_flickrConfiguration.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;
            }
        }
Ejemplo n.º 7
0
        /// <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, string albumPath, string title, IProgress <int> progress = null, CancellationToken token = default)
        {
            string responseString;
            var    filename           = surfaceToUpload.GenerateFilename(CoreConfiguration, _photobucketConfiguration);
            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())
            {
                surfaceToUpload.WriteToStream(imageStream, CoreConfiguration, _photobucketConfiguration);
                imageStream.Position = 0;
                using (var streamContent = new StreamContent(imageStream))
                {
                    streamContent.Headers.ContentType        = new MediaTypeHeaderValue(surfaceToUpload.GenerateMimeType(CoreConfiguration, _photobucketConfiguration));
                    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);
        }