Ejemplo n.º 1
0
        public static WorkerTask CreateDownloadTask(string url, bool upload, TaskSettings taskSettings)
        {
            WorkerTask task = new WorkerTask(taskSettings);

            task.Info.Job      = upload ? TaskJob.DownloadUpload : TaskJob.Download;
            task.Info.DataType = TaskHelpers.FindDataType(url, taskSettings);

            string filename = URLHelpers.URLDecode(url, 10);

            filename = URLHelpers.GetFileName(filename);
            filename = Helpers.GetValidFileName(filename);

            if (task.Info.TaskSettings.UploadSettings.FileUploadUseNamePattern)
            {
                string ext = Path.GetExtension(filename);
                filename = TaskHelpers.GetFilename(task.Info.TaskSettings, ext);
            }

            if (string.IsNullOrEmpty(filename))
            {
                return(null);
            }

            task.Info.FileName   = filename;
            task.Info.Result.URL = url;
            return(task);
        }
Ejemplo n.º 2
0
        public void RemoveDirectory(string url)
        {
            string filename = URLHelpers.GetFileName(url);

            if (filename == "." || filename == "..")
            {
                return;
            }

            List <FTPLineResult> files = ListDirectoryDetails(url);
            string path = URLHelpers.GetDirectoryPath(url);

            foreach (FTPLineResult file in files)
            {
                if (file.IsDirectory)
                {
                    RemoveDirectory(URLHelpers.CombineURL(url, file.Name));
                }
                else
                {
                    DeleteFile(URLHelpers.CombineURL(url, file.Name));
                }
            }

            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);

            request.Proxy       = Options.ProxySettings;
            request.Method      = WebRequestMethods.Ftp.RemoveDirectory;
            request.Credentials = new NetworkCredential(Options.Account.Username, Options.Account.Password);
            request.KeepAlive   = false;

            request.GetResponse();

            WriteOutput("RemoveDirectory: " + url);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Given a <see cref="B2UploadUrl"/> returned from the API, attempts to upload a file.
        /// </summary>
        /// <param name="b2UploadUrl">Information returned by the <c>b2_get_upload_url</c> API.</param>
        /// <param name="destinationPath">The remote path to upload to.</param>
        /// <param name="file">The file to upload.</param>
        /// <returns>
        ///     A B2UploadResult(HTTP status, B2Error, B2Upload) that can be decomposed as follows:
        ///
        ///     <ul>
        ///         <li><b>If successful:</b> <c>(200, null, B2Upload)</c></li>
        ///         <li><b>If unsuccessful:</b> <c>(HTTP status, B2Error, null)</c></li>
        ///         <li><b>If the connection failed:</b> <c>(-1, null, null)</c></li>
        ///     </ul>
        /// </returns>
        private B2UploadResult B2ApiUploadFile(B2UploadUrl b2UploadUrl, string destinationPath, Stream file)
        {
            // we want to send 'Content-Disposition: inline; filename="screenshot.png"'
            // this should display the uploaded data inline if possible, but if that fails, present a sensible filename
            // conveniently, this class will handle this for us
            ContentDisposition contentDisposition = new ContentDisposition("inline")
            {
                FileName = URLHelpers.GetFileName(destinationPath)
            };

            DebugHelper.WriteLine($"B2 uploader: Content disposition is '{contentDisposition}'.");

            // compute SHA1 hash without loading the file fully into memory
            string sha1Hash;

            using (SHA1CryptoServiceProvider cryptoProvider = new SHA1CryptoServiceProvider())
            {
                file.Seek(0, SeekOrigin.Begin);
                byte[] bytes = cryptoProvider.ComputeHash(file);
                sha1Hash = BitConverter.ToString(bytes).Replace("-", "").ToLower();
                file.Seek(0, SeekOrigin.Begin);
            }
            DebugHelper.WriteLine($"B2 uploader: SHA1 hash is '{sha1Hash}'.");

            // it's showtime
            // https://www.backblaze.com/b2/docs/b2_upload_file.html
            NameValueCollection headers = new NameValueCollection()
            {
                ["Authorization"]     = b2UploadUrl.authorizationToken,
                ["X-Bz-File-Name"]    = URLHelpers.URLEncode(destinationPath),
                ["Content-Length"]    = file.Length.ToString(),
                ["X-Bz-Content-Sha1"] = sha1Hash,
                ["X-Bz-Info-src_last_modified_millis"] = DateTimeOffset.Now.ToUnixTimeMilliseconds().ToString(),
                ["X-Bz-Info-b2-content-disposition"]   = URLHelpers.URLEncode(contentDisposition.ToString()),
            };

            string contentType = UploadHelpers.GetMimeType(destinationPath);

            using (HttpWebResponse res = GetResponse(HttpMethod.POST, b2UploadUrl.uploadUrl,
                                                     contentType: contentType, headers: headers, data: file, allowNon2xxResponses: true))
            {
                // if connection failed, res will be null, and here we -do- want to check explicitly for this
                // since the server might be down
                if (res == null)
                {
                    return(new B2UploadResult(-1, null, null));
                }

                if (res.StatusCode != HttpStatusCode.OK)
                {
                    return(new B2UploadResult((int)res.StatusCode, ParseB2Error(res), null));
                }

                string body = UploadHelpers.ResponseToString(res);
                DebugHelper.WriteLine($"B2 uploader: B2ApiUploadFile() reports success! '{body}'");

                return(new B2UploadResult((int)res.StatusCode, null, JsonConvert.DeserializeObject <B2Upload>(body)));
            }
        }
Ejemplo n.º 4
0
        public static void DownloadAndUploadFile(string url, TaskSettings taskSettings = null)
        {
            if (!string.IsNullOrEmpty(url))
            {
                if (taskSettings == null)
                {
                    taskSettings = TaskSettings.GetDefaultTaskSettings();
                }

                string downloadPath = null;
                bool   isDownloaded = false;

                TaskEx.Run(() =>
                {
                    url             = url.Trim();
                    string filename = URLHelpers.GetFileName(url, true, true);

                    if (!string.IsNullOrEmpty(filename))
                    {
                        downloadPath = TaskHelpers.CheckFilePath(taskSettings.CaptureFolder, filename, taskSettings);

                        if (!string.IsNullOrEmpty(downloadPath))
                        {
                            Helpers.CreateDirectoryIfNotExist(downloadPath);

                            try
                            {
                                using (WebClient wc = new WebClient())
                                {
                                    wc.Proxy = HelpersOptions.CurrentProxy.GetWebProxy();
                                    wc.DownloadFile(url, downloadPath);
                                }

                                isDownloaded = true;
                            }
                            catch (Exception e)
                            {
                                DebugHelper.WriteException(e);
                                MessageBox.Show(string.Format(Resources.UploadManager_DownloadAndUploadFile_Download_failed, e), "ShareX", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                },
                           () =>
                {
                    if (isDownloaded)
                    {
                        UploadFile(downloadPath, taskSettings);
                    }
                });
            }
        }
Ejemplo n.º 5
0
        public void DeleteDirectory(string remotePath)
        {
            if (Connect())
            {
                string filename = URLHelpers.GetFileName(remotePath);
                if (filename == "." || filename == "..")
                {
                    return;
                }

                FtpListItem[] files = GetListing(remotePath);

                DeleteFiles(files);

                client.DeleteDirectory(remotePath);
            }
        }
Ejemplo n.º 6
0
Archivo: Copy.cs Proyecto: ywscr/ShareX
        public string GetLinkURL(CopyLinksInfo link, string path, CopyURLType urlType = CopyURLType.Default)
        {
            string filename = URLHelpers.URLEncode(URLHelpers.GetFileName(path));

            switch (urlType)
            {
            default:
            case CopyURLType.Default:
                return(string.Format("https://www.copy.com/s/{0}/{1}", link.id, filename));

            case CopyURLType.Shortened:
                return(string.Format("https://copy.com/{0}", link.id));

            case CopyURLType.Direct:
                return(string.Format("https://copy.com/{0}/{1}", link.id, filename));
            }
        }
Ejemplo n.º 7
0
        public override UploadResult UploadText(string text, string fileName)
        {
            UploadResult ur = new UploadResult();

            if (!string.IsNullOrEmpty(text) && Settings != null)
            {
                Dictionary <string, string> args = new Dictionary <string, string>();

                args.Add("api_dev_key", APIKey);  // which is your unique API Developers Key
                args.Add("api_option", "paste");  // set as 'paste', this will indicate you want to create a new paste
                args.Add("api_paste_code", text); // this is the text that will be written inside your paste

                // Optional args
                args.Add("api_paste_name", Settings.Title);                            // this will be the name / title of your paste
                args.Add("api_paste_format", Settings.TextFormat);                     // this will be the syntax highlighting value
                args.Add("api_paste_private", GetPrivacy(Settings.Exposure));          // this makes a paste public or private, public = 0, private = 1
                args.Add("api_paste_expire_date", GetExpiration(Settings.Expiration)); // this sets the expiration date of your paste

                if (!string.IsNullOrEmpty(Settings.UserKey))
                {
                    args.Add("api_user_key", Settings.UserKey); // this paramater is part of the login system
                }

                ur.Response = SendRequest(HttpMethod.POST, "http://pastebin.com/api/api_post.php", args);

                if (!string.IsNullOrEmpty(ur.Response) && !ur.Response.StartsWith("Bad API request") && ur.Response.IsValidUrl())
                {
                    if (Settings.RawURL)
                    {
                        string paste_key = URLHelpers.GetFileName(ur.Response);
                        ur.URL = "http://pastebin.com/raw/" + paste_key;
                    }
                    else
                    {
                        ur.URL = ur.Response;
                    }
                }
                else
                {
                    Errors.Add(ur.Response);
                }
            }

            return(ur);
        }
Ejemplo n.º 8
0
        public static void UploadURL(TaskSettings taskSettings = null)
        {
            if (taskSettings == null)
            {
                taskSettings = TaskSettings.GetDefaultTaskSettings();
            }

            string url = InputBox.GetInputText("ShareX - URL to download from and upload");

            if (!string.IsNullOrEmpty(url))
            {
                string filename = URLHelpers.GetFileName(url, true);

                if (!string.IsNullOrEmpty(filename))
                {
                    DownloadAndUploadFile(url, filename, taskSettings);
                }
            }
        }
Ejemplo n.º 9
0
        public static void UploadURL(TaskSettings taskSettings = null)
        {
            if (taskSettings == null)
            {
                taskSettings = TaskSettings.GetDefaultTaskSettings();
            }

            string url = InputBox.GetInputText("ShareX - " + Resources.UploadManager_UploadURL_URL_to_download_from_and_upload);

            if (!string.IsNullOrEmpty(url))
            {
                string filename = URLHelpers.GetFileName(url, true);

                if (!string.IsNullOrEmpty(filename))
                {
                    DownloadAndUploadFile(url, filename, taskSettings);
                }
            }
        }
Ejemplo n.º 10
0
        public void DeleteFile(string url)
        {
            string filename = URLHelpers.GetFileName(url);

            if (filename == "." || filename == "..")
            {
                return;
            }

            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);

            request.Proxy       = Options.ProxySettings;
            request.Method      = WebRequestMethods.Ftp.DeleteFile;
            request.Credentials = new NetworkCredential(Options.Account.Username, Options.Account.Password);
            request.KeepAlive   = false;

            request.GetResponse();

            WriteOutput("DeleteFile: " + url);
        }
Ejemplo n.º 11
0
        public static void ClipboardUpload(TaskSettings taskSettings = null)
        {
            if (taskSettings == null)
            {
                taskSettings = TaskSettings.GetDefaultTaskSettings();
            }

            if (Clipboard.ContainsImage())
            {
                Image img = Clipboard.GetImage();

                if (img != null)
                {
                    if (!taskSettings.AdvancedSettings.ProcessImagesDuringClipboardUpload)
                    {
                        taskSettings.AfterCaptureJob = AfterCaptureTasks.UploadImageToHost;
                    }

                    RunImageTask(img, taskSettings);
                }
            }
            else if (Clipboard.ContainsFileDropList())
            {
                string[] files = Clipboard.GetFileDropList().Cast <string>().ToArray();
                UploadFile(files, taskSettings);
            }
            else if (Clipboard.ContainsText())
            {
                string text = Clipboard.GetText();

                if (!string.IsNullOrEmpty(text))
                {
                    string url = text.Trim();

                    if (URLHelpers.IsValidURLRegex(url))
                    {
                        if (taskSettings.UploadSettings.ClipboardUploadURLContents)
                        {
                            string filename = URLHelpers.GetFileName(url, true);

                            if (!string.IsNullOrEmpty(filename))
                            {
                                DownloadAndUploadFile(url, filename, taskSettings);
                                return;
                            }
                        }

                        if (taskSettings.UploadSettings.ClipboardUploadShortenURL)
                        {
                            ShortenURL(url, taskSettings);
                            return;
                        }

                        if (taskSettings.UploadSettings.ClipboardUploadShareURL)
                        {
                            ShareURL(url, taskSettings);
                            return;
                        }
                    }

                    if (taskSettings.UploadSettings.ClipboardUploadAutoIndexFolder && text.Length <= 260 && Directory.Exists(text))
                    {
                        IndexFolder(text, taskSettings);
                    }
                    else
                    {
                        UploadText(text, taskSettings);
                    }
                }
            }
        }