Esempio n. 1
0
        /// <summary>
        /// This will be called when the menu item in the Editor is clicked
        /// </summary>
        public string Upload(ICaptureDetails captureDetails, ISurface surfaceToUpload)
        {
            SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(config.UploadFormat, config.UploadJpegQuality, false);

            try {
                string           url           = null;
                string           filename      = Path.GetFileName(FilenameHelper.GetFilename(config.UploadFormat, captureDetails));
                SurfaceContainer imageToUpload = new SurfaceContainer(surfaceToUpload, outputSettings, filename);

                new PleaseWaitForm().ShowAndWait("Box plug-in", Language.GetString("box", LangKey.communication_wait),
                                                 delegate() {
                    url = BoxUtils.UploadToBox(imageToUpload, captureDetails.Title, filename);
                }
                                                 );

                if (url != null && config.AfterUploadLinkToClipBoard)
                {
                    ClipboardHelper.SetClipboardData(url);
                }

                return(url);
            } catch (Exception ex) {
                LOG.Error("Error uploading.", ex);
                MessageBox.Show(Language.GetString("box", LangKey.upload_failure) + " " + ex.ToString());
                return(null);
            }
        }
Esempio n. 2
0
    public void CancelBtnClick()
    {
        gameObject.SetActive(false);

        SurfaceContainer container = UIRoot.list[0].gameObject.GetComponent <SurfaceContainer>();
        SurfaceDownload  download  = container.GetSurface <SurfaceDownload>();

        download.CancelTask();
    }
Esempio n. 3
0
        /// <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="image">Image for box upload</param>
        /// <param name="title">Title of box upload</param>
        /// <param name="filename">Filename of box upload</param>
        /// <returns>url to uploaded image</returns>
        public static string UploadToBox(SurfaceContainer image, string title, string filename)
        {
            // Fill the OAuth2Settings
            var settings = new OAuth2Settings
            {
                AuthUrlPattern     = "https://app.box.com/api/oauth2/authorize?client_id={ClientId}&response_type=code&state={State}&redirect_uri={RedirectUrl}",
                TokenUrl           = "https://api.box.com/oauth2/token",
                CloudServiceName   = "Box",
                ClientId           = BoxCredentials.ClientId,
                ClientSecret       = BoxCredentials.ClientSecret,
                RedirectUrl        = "https://www.box.com/home/",
                BrowserSize        = new Size(1060, 600),
                AuthorizeMode      = OAuth2AuthorizeMode.EmbeddedBrowser,
                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, UploadFileUri, settings);
                IDictionary <string, object> parameters = new Dictionary <string, object>();
                parameters.Add("file", image);
                parameters.Add("parent_id", Config.FolderId);

                NetworkHelper.WriteMultipartFormData(webRequest, parameters);

                var response = NetworkHelper.GetResponseAsString(webRequest);

                Log.DebugFormat("Box response: {0}", response);

                var upload = JsonSerializer.Deserialize <Upload>(response);
                if (upload?.Entries == null || upload.Entries.Count == 0)
                {
                    return(null);
                }

                if (Config.UseSharedLink)
                {
                    string filesResponse = HttpPut(string.Format(FilesUri, upload.Entries[0].Id), "{\"shared_link\": {\"access\": \"open\"}}", settings);
                    var    file          = JsonSerializer.Deserialize <FileEntry>(filesResponse);
                    return(file.SharedLink.Url);
                }
                return($"http://www.box.com/files/0/f/0/1/f_{upload.Entries[0].Id}");
            } finally {
                // Copy the settings back to the config, so they are stored.
                Config.RefreshToken       = settings.RefreshToken;
                Config.AccessToken        = settings.AccessToken;
                Config.AccessTokenExpires = settings.AccessTokenExpires;
                Config.IsDirty            = true;
                IniConfig.Save();
            }
        }
Esempio n. 4
0
        /// <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="image">Image for box upload</param>
        /// <param name="title">Title of box upload</param>
        /// <param name="filename">Filename of box upload</param>
        /// <returns>url to uploaded image</returns>
        public static string UploadToBox(SurfaceContainer image, string title, string filename)
        {
            while (true)
            {
                const string folderId = "0";
                if (string.IsNullOrEmpty(Config.BoxToken))
                {
                    if (!Authorize())
                    {
                        return(null);
                    }
                }

                IDictionary <string, object> parameters = new Dictionary <string, object>();
                parameters.Add("filename", image);
                parameters.Add("parent_id", folderId);

                var response = "";
                try {
                    response = HttpPost(UploadFileUri, parameters);
                } catch (WebException ex) {
                    if (ex.Status == WebExceptionStatus.ProtocolError)
                    {
                        Config.BoxToken = null;
                        continue;
                    }
                }

                LOG.DebugFormat("Box response: {0}", response);

                // Check if the token is wrong
                if ("wrong auth token".Equals(response))
                {
                    Config.BoxToken = null;
                    IniConfig.Save();
                    continue;
                }
                var upload = JsonSerializer.Deserialize <Upload>(response);
                if (upload == null || upload.Entries == null || upload.Entries.Count == 0)
                {
                    return(null);
                }

                if (Config.UseSharedLink)
                {
                    string filesResponse = HttpPut(string.Format(FilesUri, upload.Entries[0].Id), "{\"shared_link\": {\"access\": \"open\"}}");
                    var    file          = JsonSerializer.Deserialize <FileEntry>(filesResponse);
                    return(file.SharedLink.Url);
                }
                return(string.Format("http://www.box.com/files/0/f/0/1/f_{0}", upload.Entries[0].Id));
            }
        }
Esempio n. 5
0
        public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surfaceToUpload, ICaptureDetails captureDetails)
        {
            ExportInformation     exportInformation = new ExportInformation(Designation, Description);
            string                filename          = Path.GetFileName(FilenameHelper.GetFilename(Config.UploadFormat, captureDetails));
            SurfaceOutputSettings outputSettings    = new SurfaceOutputSettings(Config.UploadFormat, Config.UploadJpegQuality, Config.UploadReduceColors);

            if (_jiraIssue != null)
            {
                try {
                    // Run upload in the background
                    new PleaseWaitForm().ShowAndWait(Description, Language.GetString("jira", LangKey.communication_wait),
                                                     async() =>
                    {
                        var surfaceContainer = new SurfaceContainer(surfaceToUpload, outputSettings, filename);
                        await _jiraPlugin.JiraConnector.AttachAsync(_jiraIssue.Key, surfaceContainer);
                        surfaceToUpload.UploadUrl = _jiraPlugin.JiraConnector.JiraBaseUri.AppendSegments("browse", _jiraIssue.Key).AbsoluteUri;
                    }
                                                     );
                    Log.DebugFormat("Uploaded to Jira {0}", _jiraIssue.Key);
                    exportInformation.ExportMade = true;
                    exportInformation.Uri        = surfaceToUpload.UploadUrl;
                } catch (Exception e) {
                    MessageBox.Show(Language.GetString("jira", LangKey.upload_failure) + " " + e.Message);
                }
            }
            else
            {
                var jiraForm = new JiraForm(_jiraPlugin.JiraConnector);
                jiraForm.SetFilename(filename);
                var dialogResult = jiraForm.ShowDialog();
                if (dialogResult == DialogResult.OK)
                {
                    try {
                        surfaceToUpload.UploadUrl = _jiraPlugin.JiraConnector.JiraBaseUri.AppendSegments("browse", jiraForm.GetJiraIssue().Key).AbsoluteUri;
                        // Run upload in the background
                        new PleaseWaitForm().ShowAndWait(Description, Language.GetString("jira", LangKey.communication_wait),
                                                         async() =>
                        {
                            await jiraForm.UploadAsync(new SurfaceContainer(surfaceToUpload, outputSettings, filename));
                        }
                                                         );
                        Log.DebugFormat("Uploaded to Jira {0}", jiraForm.GetJiraIssue().Key);
                        exportInformation.ExportMade = true;
                        exportInformation.Uri        = surfaceToUpload.UploadUrl;
                    } catch (Exception e) {
                        MessageBox.Show(Language.GetString("jira", LangKey.upload_failure) + " " + e.Message);
                    }
                }
            }
            ProcessExport(exportInformation, surfaceToUpload);
            return(exportInformation);
        }
Esempio n. 6
0
        public static string UploadToDropbox(ISurface surfaceToUpload, SurfaceOutputSettings outputSettings, string filename)
        {
            var oAuth = new OAuthSession(DropBoxCredentials.CONSUMER_KEY, DropBoxCredentials.CONSUMER_SECRET)
            {
                BrowserSize     = new Size(1080, 650),
                CheckVerifier   = false,
                AccessTokenUrl  = "https://api.dropbox.com/1/oauth/access_token",
                AuthorizeUrl    = "https://api.dropbox.com/1/oauth/authorize",
                RequestTokenUrl = "https://api.dropbox.com/1/oauth/request_token",
                LoginTitle      = "Dropbox authorization",
                Token           = DropboxConfig.DropboxToken,
                TokenSecret     = DropboxConfig.DropboxTokenSecret
            };

            try {
                SurfaceContainer imageToUpload  = new SurfaceContainer(surfaceToUpload, outputSettings, filename);
                string           uploadResponse = oAuth.MakeOAuthRequest(HTTPMethod.POST, "https://api-content.dropbox.com/1/files_put/sandbox/" + OAuthSession.UrlEncode3986(filename), null, null, imageToUpload);
                Log.DebugFormat("Upload response: {0}", uploadResponse);
            } catch (Exception ex) {
                Log.Error("Upload error: ", ex);
                throw;
            } finally {
                if (!string.IsNullOrEmpty(oAuth.Token))
                {
                    DropboxConfig.DropboxToken = oAuth.Token;
                }
                if (!string.IsNullOrEmpty(oAuth.TokenSecret))
                {
                    DropboxConfig.DropboxTokenSecret = oAuth.TokenSecret;
                }
            }

            // Try to get a URL to the uploaded image
            try {
                string responseString = oAuth.MakeOAuthRequest(HTTPMethod.GET, "https://api.dropbox.com/1/shares/sandbox/" + OAuthSession.UrlEncode3986(filename), null, null, null);
                if (responseString != null)
                {
                    Log.DebugFormat("Parsing output: {0}", responseString);
                    IDictionary <string, object> returnValues = JSONHelper.JsonDecode(responseString);
                    if (returnValues.ContainsKey("url"))
                    {
                        return(returnValues["url"] as string);
                    }
                }
            } catch (Exception ex) {
                Log.Error("Can't parse response.", ex);
            }
            return(null);
        }
Esempio n. 7
0
        /// <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="imageData">byte[] with image data</param>
        /// <returns>url to uploaded image</returns>
        public static string UploadToBox(SurfaceContainer image, string title, string filename)
        {
            string folderId = "0";

            if (string.IsNullOrEmpty(config.BoxToken))
            {
                if (!Authorize())
                {
                    return(null);
                }
            }

            string strUrl = string.Format("https://upload.box.net/api/1.0/upload/{0}/{1}?file_name={2}&new_copy=1", config.BoxToken, folderId, filename);

            Dictionary <string, object> parameters = new Dictionary <string, object>();

            parameters.Add("share", "1");
            parameters.Add("new_file", image);

            string response = HttpUploadFile(strUrl, parameters);

            // Check if the token is wrong
            if ("wrong auth token".Equals(response))
            {
                config.BoxToken = null;
                IniConfig.Save();
                return(UploadToBox(image, title, filename));
            }
            LOG.DebugFormat("Box response: {0}", response);
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(response);
            XmlNodeList nodes = doc.GetElementsByTagName("status");

            if (nodes.Count > 0)
            {
                if ("upload_ok".Equals(nodes.Item(0).InnerText))
                {
                    nodes = doc.GetElementsByTagName("file");
                    if (nodes.Count > 0)
                    {
                        long id = long.Parse(nodes.Item(0).Attributes["id"].Value);
                        return(string.Format("http://www.box.com/files/0/f/0/1/f_{0}", id));
                    }
                }
            }
            return(null);
        }
Esempio n. 8
0
        public static string UploadToDropbox(ISurface surfaceToUpload, SurfaceOutputSettings outputSettings, string filename)
        {
            OAuthSession oAuth = new OAuthSession(DropBoxCredentials.CONSUMER_KEY, DropBoxCredentials.CONSUMER_SECRET);

            oAuth.BrowserSize     = new Size(1080, 650);
            oAuth.CheckVerifier   = false;
            oAuth.AccessTokenUrl  = "https://api.dropbox.com/1/oauth/access_token";
            oAuth.AuthorizeUrl    = "https://api.dropbox.com/1/oauth/authorize";
            oAuth.RequestTokenUrl = "https://api.dropbox.com/1/oauth/request_token";
            oAuth.LoginTitle      = "Dropbox authorization";
            oAuth.Token           = config.DropboxToken;
            oAuth.TokenSecret     = config.DropboxTokenSecret;

            try {
                SurfaceContainer imageToUpload  = new SurfaceContainer(surfaceToUpload, outputSettings, filename);
                string           uploadResponse = oAuth.MakeOAuthRequest(HTTPMethod.POST, "https://api-content.dropbox.com/1/files_put/sandbox/" + OAuthSession.UrlEncode3986(filename), null, null, imageToUpload);
                LOG.DebugFormat("Upload response: {0}", uploadResponse);
            } catch (Exception ex) {
                LOG.Error("Upload error: ", ex);
                throw;
            } finally {
                if (!string.IsNullOrEmpty(oAuth.Token))
                {
                    config.DropboxToken = oAuth.Token;
                }
                if (!string.IsNullOrEmpty(oAuth.TokenSecret))
                {
                    config.DropboxTokenSecret = oAuth.TokenSecret;
                }
            }

            // Try to get a URL to the uploaded image
            try {
                string responseString = oAuth.MakeOAuthRequest(HTTPMethod.GET, "https://api.dropbox.com/1/shares/sandbox/" + OAuthSession.UrlEncode3986(filename), null, null, null);
                if (responseString != null)
                {
                    LOG.DebugFormat("Parsing output: {0}", responseString);
                    DropboxResponse response = JSONSerializer <DropboxResponse> .Deserialize(responseString);

                    return(response.url);
                }
            } catch (Exception ex) {
                LOG.Error("Can't parse response.", ex);
            }
            return(null);
        }
Esempio n. 9
0
        /// <summary>
        /// Do the actual upload to Picasa
        /// </summary>
        /// <param name="surfaceToUpload">Image to upload</param>
        /// <param name="outputSettings"></param>
        /// <param name="title"></param>
        /// <param name="filename"></param>
        /// <returns>PicasaResponse</returns>
        public static string UploadToPicasa(ISurface surfaceToUpload, SurfaceOutputSettings outputSettings, string title, string filename)
        {
            // Fill the OAuth2Settings
            var settings = new OAuth2Settings
            {
                AuthUrlPattern     = AuthUrl,
                TokenUrl           = TokenUrl,
                CloudServiceName   = "Picasa",
                ClientId           = PicasaCredentials.ClientId,
                ClientSecret       = PicasaCredentials.ClientSecret,
                AuthorizeMode      = OAuth2AuthorizeMode.LocalServer,
                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, string.Format(UploadUrl, Config.UploadUser, Config.UploadAlbum), settings);
                if (Config.AddFilename)
                {
                    webRequest.Headers.Add("Slug", NetworkHelper.EscapeDataString(filename));
                }
                SurfaceContainer container = new SurfaceContainer(surfaceToUpload, outputSettings, filename);
                container.Upload(webRequest);

                string response = NetworkHelper.GetResponseAsString(webRequest);

                return(ParseResponse(response));
            } finally {
                // Copy the settings back to the config, so they are stored.
                Config.RefreshToken       = settings.RefreshToken;
                Config.AccessToken        = settings.AccessToken;
                Config.AccessTokenExpires = settings.AccessTokenExpires;
                Config.IsDirty            = true;
                IniConfig.Save();
            }
        }
Esempio n. 10
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="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));
        }
Esempio n. 11
0
        protected override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails)
        {
            var exportInformation = new ExportInformation(Designation, Description);
            var filename          = Path.GetFileName(FilenameHelper.GetFilename(_jiraConfiguration.UploadFormat, captureDetails));
            var outputSettings    = new SurfaceOutputSettings(_jiraConfiguration.UploadFormat, _jiraConfiguration.UploadJpegQuality, _jiraConfiguration.UploadReduceColors);

            if (_jiraIssue != null)
            {
                try
                {
                    // Run upload in the background
                    new PleaseWaitForm().ShowAndWait(Description, Language.GetString("jira", LangKey.communication_wait),
                                                     async() =>
                    {
                        var surfaceContainer = new SurfaceContainer(surface, outputSettings, filename);
                        await _jiraConnector.AttachAsync(_jiraIssue.Key, surfaceContainer);
                        surface.UploadUrl = _jiraConnector.JiraBaseUri.AppendSegments("browse", _jiraIssue.Key).AbsoluteUri;
                    }
                                                     );
                    Log.Debug().WriteLine("Uploaded to Jira {0}", _jiraIssue.Key);
                    exportInformation.ExportMade = true;
                    exportInformation.Uri        = surface.UploadUrl;
                }
                catch (Exception e)
                {
                    MessageBox.Show(Language.GetString("jira", LangKey.upload_failure) + " " + e.Message);
                }
            }
            else
            {
                // TODO: set filename
                // _jiraViewModel.SetFilename(filename);
                if (_windowManager.ShowDialog(_jiraViewModel) == true)
                {
                    try
                    {
                        surface.UploadUrl = _jiraConnector.JiraBaseUri.AppendSegments("browse", _jiraViewModel.JiraIssue.Key).AbsoluteUri;
                        // Run upload in the background
                        new PleaseWaitForm().ShowAndWait(Description, Language.GetString("jira", LangKey.communication_wait),
                                                         async() =>
                        {
                            var attachment = new SurfaceContainer(surface, outputSettings, _jiraViewModel.Filename);

                            await _jiraConnector.AttachAsync(_jiraViewModel.JiraIssue.Key, attachment);

                            if (!string.IsNullOrEmpty(_jiraViewModel.Comment))
                            {
                                await _jiraConnector.AddCommentAsync(_jiraViewModel.JiraIssue.Key, _jiraViewModel.Comment);
                            }
                        }
                                                         );
                        Log.Debug().WriteLine("Uploaded to Jira {0}", _jiraViewModel.JiraIssue.Key);
                        exportInformation.ExportMade = true;
                        exportInformation.Uri        = surface.UploadUrl;
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(Language.GetString("jira", LangKey.upload_failure) + " " + e.Message);
                    }
                }
            }
            ProcessExport(exportInformation, surface);
            return(exportInformation);
        }