Inheritance: System.Web.UI.Page
Exemple #1
0
        public override UploadResult ShortenURL(string url)
        {
            UploadResult result = new UploadResult { URL = url };

            if (string.IsNullOrEmpty(API_HOST))
            {
                API_HOST = "https://polr.me/publicapi.php";
                API_KEY = null;
            }
            else
            {
                API_HOST = URLHelpers.FixPrefix(API_HOST);
            }

            Dictionary<string, string> args = new Dictionary<string, string>();

            if (!string.IsNullOrEmpty(API_KEY))
            {
                args.Add("apikey", API_KEY);
            }

            args.Add("action", "shorten");
            args.Add("url", url);

            string response = SendRequest(HttpMethod.GET, API_HOST, args);

            if (!string.IsNullOrEmpty(response))
            {
                result.ShortenedURL = response;
            }

            return result;
        }
        public ActionResult UploadSolution(int id, HttpPostedFileBase file)
        {
            ActionResult redirectResult = this.RedirectToAction(
                "Details",
                "Courses",
                new { area = "Public", id = id });

            UploadResult result = new UploadResult();
            if (file == null)
            {
                return redirectResult;
            }

            this.UserManagement.EnsureFolder(this.UserId);
            result = this.UserManagement.SaveSolution(file, this.UserId, id);
            if (!result.HasSucceed)
            {
                this.TempData["Error"] = result.Error;
            }
            else
            {
                this.courseService.SaveSolution(result.Path, this.UserId, id);
            }

            return redirectResult;
        }
Exemple #3
0
        public override UploadResult ShortenURL(string url)
        {
            UploadResult result = new UploadResult { URL = url };

            if (!string.IsNullOrEmpty(url))
            {
                Dictionary<string, string> arguments = new Dictionary<string, string>();
                arguments.Add("url", url);

                result.Response = SendRequest(HttpMethod.GET, "http://turl.ca/api.php", arguments);

                if (!string.IsNullOrEmpty(result.Response))
                {
                    if (result.Response.StartsWith("SUCCESS:"))
                    {
                        result.ShortenedURL = "http://turl.ca/" + result.Response.Substring(8);
                    }

                    if (result.Response.StartsWith("ERROR:"))
                    {
                        Errors.Add(result.Response.Substring(6));
                    }
                }
            }

            return result;
        }
Exemple #4
0
        public override UploadResult UploadText(string text, string fileName)
        {
            UploadResult result = new UploadResult();

            if (!string.IsNullOrEmpty(text))
            {
                Dictionary<string, string> args = new Dictionary<string, string>();
                args.Add("secret", text);

                NameValueCollection headers = null;

                if (!string.IsNullOrEmpty(API_USERNAME) && !string.IsNullOrEmpty(API_KEY))
                {
                    headers = CreateAuthenticationHeader(API_USERNAME, API_KEY);
                }

                result.Response = SendRequest(HttpMethod.POST, API_ENDPOINT, args, headers);

                if (!string.IsNullOrEmpty(result.Response))
                {
                    OneTimeSecretResponse jsonResponse = JsonConvert.DeserializeObject<OneTimeSecretResponse>(result.Response);

                    if (jsonResponse != null)
                    {
                        result.URL = URLHelpers.CombineURL("https://onetimesecret.com/secret/", jsonResponse.secret_key);
                    }
                }
            }

            return result;
        }
Exemple #5
0
        public override UploadResult Upload(Stream stream, string fileName)
        {
            UploadResult result = new UploadResult();

            fileName = Helpers.GetValidURL(fileName);
            string path = Account.GetSubFolderPath(fileName);

            using (ftpClient = new FTP(Account, BufferSize))
            {
                ftpClient.ProgressChanged += OnProgressChanged;

                try
                {
                    IsUploading = true;
                    ftpClient.UploadData(stream, path);
                }
                finally
                {
                    IsUploading = false;
                }
            }

            if (!stopUpload && Errors.Count == 0)
            {
                result.URL = Account.GetUriPath(fileName);
            }

            return result;
        }
Exemple #6
0
        public override UploadResult ShortenURL(string url)
        {
            UploadResult result = new UploadResult { URL = url };

            if (!string.IsNullOrEmpty(url))
            {
                Dictionary<string, string> arguments = new Dictionary<string, string>();

                if (!string.IsNullOrEmpty(Signature))
                {
                    arguments.Add("signature", Signature);
                }
                else if (!string.IsNullOrEmpty(Username) && !string.IsNullOrEmpty(Password))
                {
                    arguments.Add("username", Username);
                    arguments.Add("password", Password);
                }
                else
                {
                    throw new Exception("Signature or Username/Password is missing.");
                }

                arguments.Add("action", "shorturl");
                arguments.Add("url", url);
                //arguments.Add("keyword", "");
                //arguments.Add("title", "");
                arguments.Add("format", "simple");

                result.Response = SendRequest(HttpMethod.POST, APIURL, arguments);
                result.ShortenedURL = result.Response;
            }

            return result;
        }
Exemple #7
0
        public override UploadResult ShortenURL(string url)
        {
            if (customUploader.RequestType == CustomUploaderRequestType.POST && !string.IsNullOrEmpty(customUploader.FileFormName))
                throw new Exception("'File form name' cannot be used with custom URL shortener.");

            if (customUploader.Arguments == null || !customUploader.Arguments.Any(x => x.Value.Contains("$input$") || x.Value.Contains("%input")))
                throw new Exception("Atleast one '$input$' required for argument value.");

            UploadResult result = new UploadResult { URL = url };

            Dictionary<string, string> args = customUploader.GetArguments(url);

            result.Response = SendRequest(customUploader.GetHttpMethod(), customUploader.GetRequestURL(), args, customUploader.GetHeaders(), responseType: customUploader.ResponseType);

            try
            {
                customUploader.ParseResponse(result, true);
            }
            catch (Exception e)
            {
                Errors.Add(Resources.CustomFileUploader_Upload_Response_parse_failed_ + Environment.NewLine + e);
            }

            return result;
        }
Exemple #8
0
        public override UploadResult Upload(Stream stream, string fileName)
        {
            UploadResult result = new UploadResult();

            fileName = Helpers.GetValidURL(fileName);
            string subFolderPath = Account.GetSubFolderPath();
            string path = subFolderPath.CombineURL(fileName);
            bool uploadResult;

            try
            {
                IsUploading = true;
                uploadResult = UploadStream(stream, path);
            }
            finally
            {
                Dispose();
                IsUploading = false;
            }

            if (uploadResult && !StopUploadRequested && !IsError)
            {
                result.URL = Account.GetUriPath(fileName, subFolderPath);
            }

            return result;
        }
Exemple #9
0
        public override UploadResult Upload(Stream stream, string fileName)
        {
            UploadResult result = new UploadResult();

            string subFolderPath = Account.GetSubFolderPath();
            string path = subFolderPath.CombineURL(fileName);
            string url = Account.GetUriPath(fileName, subFolderPath);

            OnEarlyURLCopyRequested(url);

            try
            {
                IsUploading = true;
                bool uploadResult = UploadStream(stream, path);

                if (uploadResult && !StopUploadRequested && !IsError)
                {
                    result.URL = url;
                }
            }
            finally
            {
                Dispose();
                IsUploading = false;
            }

            return result;
        }
Exemple #10
0
        private UploadResult ParseResult(UploadResult result)
        {
            if (result.IsSuccess)
            {
                XDocument xd = XDocument.Parse(result.Response);

                XElement xe = xd.Element("image");

                if (xe != null)
                {
                    string id = xe.GetElementValue("id");
                    result.URL = "http://twitsnaps.com/snap/" + id;
                    result.ThumbnailURL = "http://twitsnaps.com/thumb/" + id;
                }
                else
                {
                    xe = xd.Element("error");

                    if (xe != null)
                    {
                        Errors.Add("Error: " + xe.GetElementValue("description"));
                    }
                }
            }

            return result;
        }
Exemple #11
0
        public override UploadResult ShortenURL(string url)
        {
            if (customUploader.RequestType == CustomUploaderRequestType.POST && !string.IsNullOrEmpty(customUploader.FileFormName))
                throw new Exception("'File form name' cannot be used with custom URL shortener.");

            if (string.IsNullOrEmpty(customUploader.RequestURL)) throw new Exception("'Request URL' must be not empty.");

            if (customUploader.Arguments == null || !customUploader.Arguments.Any(x => x.Value.Contains("%input") || x.Value.Contains("$input$")))
                throw new Exception("Atleast one '%input' or '$input$' required for argument value when using custom URL shortener.");

            UploadResult result = new UploadResult { URL = url };

            Dictionary<string, string> args = customUploader.ParseArguments(url);

            if (customUploader.RequestType == CustomUploaderRequestType.POST)
            {
                result.Response = SendRequest(HttpMethod.POST, customUploader.RequestURL, args, customUploader.ResponseType);
            }
            else if (customUploader.RequestType == CustomUploaderRequestType.GET)
            {
                result.Response = SendRequest(HttpMethod.GET, customUploader.RequestURL, args, customUploader.ResponseType);
            }

            customUploader.ParseResponse(result, true);

            return result;
        }
Exemple #12
0
        public override UploadResult UploadText(string text, string fileName)
        {
            UploadResult ur = new UploadResult();

            if (!string.IsNullOrEmpty(text))
            {
                if (string.IsNullOrEmpty(APIKey))
                {
                    APIKey = "public";
                }

                Dictionary<string, string> arguments = new Dictionary<string, string>();
                arguments.Add("key", APIKey);
                arguments.Add("description", "");
                arguments.Add("paste", text);
                arguments.Add("format", "simple");
                arguments.Add("return", "link");

                ur.Response = SendRequest(HttpMethod.POST, "http://paste.ee/api", arguments);

                if (!string.IsNullOrEmpty(ur.Response) && ur.Response.StartsWith("error"))
                {
                    Errors.Add(ur.Response);
                }
                else
                {
                    ur.URL = ur.Response;
                }
            }

            return ur;
        }
Exemple #13
0
        public override UploadResult Upload(Stream stream, string fileName)
        {
            if (string.IsNullOrEmpty(Host))
            {
                throw new Exception("ownCloud Host is empty.");
            }

            if (string.IsNullOrEmpty(Username) || string.IsNullOrEmpty(Password))
            {
                throw new Exception("ownCloud Username or Password is empty.");
            }

            if (string.IsNullOrEmpty(Path))
            {
                Path = "/";
            }

            string path = URLHelpers.CombineURL(Path, fileName);
            string url = URLHelpers.CombineURL(Host, "remote.php/webdav", path);
            url = URLHelpers.FixPrefix(url);
            NameValueCollection headers = CreateAuthenticationHeader(Username, Password);

            SSLBypassHelper sslBypassHelper = null;

            try
            {
                if (IgnoreInvalidCert)
                {
                    sslBypassHelper = new SSLBypassHelper();
                }

                string response = SendRequestStream(url, stream, Helpers.GetMimeType(fileName), headers, method: HttpMethod.PUT);

                UploadResult result = new UploadResult(response);

                if (!IsError)
                {
                    if (CreateShare)
                    {
                        AllowReportProgress = false;
                        result.URL = ShareFile(path);
                    }
                    else
                    {
                        result.IsURLExpected = false;
                    }
                }

                return result;
            }
            finally
            {
                if (sslBypassHelper != null)
                {
                    sslBypassHelper.Dispose();
                }
            }
        }
        protected override void OnLoad(EventArgs e)
        {
            UploadResult result = new UploadResult();
            string typeId = (Request.Form["typeid"] ?? string.Empty).Trim();
            result.CurrentTypeId = typeId;
            string formPath = "music/";
            int maxFileSize = SettingConfigUtility.UploadFileMaxSize * 1000;
            if (Request.Files.Count > 0)
            {
                HttpPostedFile file = Request.Files[0];
                if (file == null)
                {
                    result.IsSuccess = false;
                    result.Message = "没有检测到<br>系统上传的音频文件";
                    this.RenderUploadResult(result);
                }
                else
                {
                    string fileName = file.FileName;
                    fileName = Path.GetFileName(fileName);
                    int fileSize = file.ContentLength;
                    if (fileSize > 0)
                    {
                        if (fileSize > maxFileSize)
                        {
                            result.IsSuccess = false;
                            result.FileName = fileName;
                            result.Message = string.Format("因音频大于{0}KB", SettingConfigUtility.UploadFileMaxSize);
                            this.RenderUploadResult(result);
                        }
                        try
                        {
                            file.SaveAs(Server.MapPath(formPath + fileName));
                        }
                        catch (Exception)
                        {
                            result.IsSuccess = false;
                            result.FileName = fileName;
                            result.Message = "因上传出现未知错误";
                            this.RenderUploadResult(result);
                        }

                        result.IsSuccess = true;
                        result.FileName = fileName;
                        this.RenderUploadResult(result);
                    }
                    else
                    {
                        result.IsSuccess = false;
                        result.FileName = fileName;
                        result.Message = "因音频太小";
                        this.RenderUploadResult(result);
                    }
                }
            }

            base.OnLoad(e);
        }
        public void ProcessRequest(HttpContext context) {
            context.Response.ContentType = "text/plain";

            var uploads = new List<UploadFileInfo>();

            var basePath = HttpContext.Current.Request.Form["path"];

            if (!basePath.StartsWith(SiteSettings.Instance.FilePath)) {
                var exception = new AccessViolationException(string.Format("Wrong path for uploads! {0}", basePath));
                Logger.Write(exception, Logger.Severity.Major);
                throw exception;
            }

            basePath = HttpContext.Current.Server.MapPath(basePath);

            foreach (string file in context.Request.Files) {
                var postedFile = context.Request.Files[file];
                string fileName;

                if (postedFile.ContentLength == 0) {
                    continue;
                }

                if (postedFile.FileName.Contains("\\")) {
                    string[] parts = postedFile.FileName.Split(new[] {'\\'});
                    fileName = parts[parts.Length - 1];
                }
                else {
                    fileName = postedFile.FileName;
                }

                if (IsFileExtensionBlocked(fileName)) {
                    Logger.Write(string.Format("Upload of {0} blocked since file type is not allowed.", fileName), Logger.Severity.Major);
                    uploads.Add(new UploadFileInfo {
                        name = Path.GetFileName(fileName),
                        size = postedFile.ContentLength,
                        type = postedFile.ContentType,
                        error = "Filetype not allowed!"
                    }); 
                    continue;
                }
                
                var savedFileName = GetUniqueFileName(basePath, fileName);
                postedFile.SaveAs(savedFileName);

                uploads.Add(new UploadFileInfo {
                    name = Path.GetFileName(savedFileName),
                    size = postedFile.ContentLength,
                    type = postedFile.ContentType
                });
            }

            var uploadResult = new UploadResult(uploads);
            var serializedUploadInfo = Serialization.JsonSerialization.SerializeJson(uploadResult);
            context.Response.Write(serializedUploadInfo);
        }
Exemple #16
0
        public TaskInfo(TaskSettings taskSettings)
        {
            if (taskSettings == null)
            {
                taskSettings = TaskSettings.GetDefaultTaskSettings();
            }

            TaskSettings = taskSettings;
            Result = new UploadResult();
        }
Exemple #17
0
        private void TranscodeFile(UploadResult result)
        {
            StreamableTranscodeResponse transcodeResponse = JsonConvert.DeserializeObject<StreamableTranscodeResponse>(result.Response);

            if (!string.IsNullOrEmpty(transcodeResponse.Shortcode))
            {
                ProgressManager progress = new ProgressManager(100);

                if (AllowReportProgress)
                {
                    OnProgressChanged(progress);
                }

                while (!StopUploadRequested)
                {
                    string statusJson = SendRequest(HttpMethod.GET, URLHelpers.CombineURL(Host, "videos", transcodeResponse.Shortcode));
                    StreamableStatusResponse response = JsonConvert.DeserializeObject<StreamableStatusResponse>(statusJson);

                    if (response.Status > 2)
                    {
                        result.Errors.Add(response.Message);
                        result.IsSuccess = false;
                        break;
                    }
                    else if (response.Status == 2)
                    {
                        if (AllowReportProgress)
                        {
                            long delta = 100 - progress.Position;
                            progress.UpdateProgress(delta);
                            OnProgressChanged(progress);
                        }

                        result.IsSuccess = true;
                        result.URL = URLHelpers.CombineURL("https://streamable.com", transcodeResponse.Shortcode);
                        break;
                    }

                    if (AllowReportProgress)
                    {
                        long delta = response.Percent - progress.Position;
                        progress.UpdateProgress(delta);
                        OnProgressChanged(progress);
                    }

                    Thread.Sleep(100);
                }
            }
            else
            {
                result.Errors.Add("Could not create video");
                result.IsSuccess = false;
            }
        }
Exemple #18
0
        public override UploadResult UploadText(string text, string fileName)
        {
            UploadResult ur = new UploadResult();

            if (!string.IsNullOrEmpty(text))
            {
                string domain;

                if (!string.IsNullOrEmpty(CustomDomain))
                {
                    domain = CustomDomain;
                }
                else
                {
                    domain = "http://hastebin.com";
                }

                ur.Response = SendRequest(HttpMethod.POST, URLHelpers.CombineURL(domain, "documents"), text);

                if (!string.IsNullOrEmpty(ur.Response))
                {
                    HastebinResponse response = JsonConvert.DeserializeObject<HastebinResponse>(ur.Response);

                    if (response != null && !string.IsNullOrEmpty(response.Key))
                    {
                        string url = URLHelpers.CombineURL(domain, response.Key);

                        string syntaxHighlighting = SyntaxHighlighting;

                        if (UseFileExtension)
                        {
                            string ext = Helpers.GetFilenameExtension(fileName);

                            if (!string.IsNullOrEmpty(ext) && !ext.Equals("txt", StringComparison.InvariantCultureIgnoreCase))
                            {
                                syntaxHighlighting = ext.ToLowerInvariant();
                            }
                        }

                        if (!string.IsNullOrEmpty(syntaxHighlighting))
                        {
                            url += "." + syntaxHighlighting;
                        }

                        ur.URL = url;
                    }
                }
            }

            return ur;
        }
Exemple #19
0
        private void TranscodeFile(string key, UploadResult result)
        {
            Dictionary<string, string> args = new Dictionary<string, string>();
            if (NoResize) args.Add("noResize", "true");
            if (IgnoreExisting) args.Add("noMd5", "true");

            string url = CreateQuery("https://upload.gfycat.com/transcodeRelease/" + key, args);
            string transcodeJson = SendRequest(HttpMethod.GET, url);
            GfycatTranscodeResponse transcodeResponse = JsonConvert.DeserializeObject<GfycatTranscodeResponse>(transcodeJson);

            if (transcodeResponse.IsOk)
            {
                ProgressManager progress = new ProgressManager(10000);

                if (AllowReportProgress)
                {
                    OnProgressChanged(progress);
                }

                while (!StopUploadRequested)
                {
                    string statusJson = SendRequest(HttpMethod.GET, "https://upload.gfycat.com/status/" + key);
                    GfycatStatusResponse response = JsonConvert.DeserializeObject<GfycatStatusResponse>(statusJson);

                    if (response.Error != null)
                    {
                        Errors.Add(response.Error);
                        result.IsSuccess = false;
                        break;
                    }
                    else if (response.GfyName != null)
                    {
                        result.IsSuccess = true;
                        result.URL = "https://gfycat.com/" + response.GfyName;
                        break;
                    }

                    if (AllowReportProgress && progress.UpdateProgress((progress.Length - progress.Position) / response.Time))
                    {
                        OnProgressChanged(progress);
                    }

                    Thread.Sleep(100);
                }
            }
            else
            {
                Errors.Add(transcodeResponse.Error);
                result.IsSuccess = false;
            }
        }
Exemple #20
0
        public override UploadResult ShortenURL(string url)
        {
            UploadResult result = new UploadResult { URL = url };

            if (!string.IsNullOrEmpty(url))
            {
                Dictionary<string, string> arguments = new Dictionary<string, string>();
                arguments.Add("url", url);

                result.Response = result.ShortenedURL = SendRequest(HttpMethod.GET, "http://nl.cm/api/", arguments);
            }

            return result;
        }
Exemple #21
0
        public override UploadResult ShortenURL(string url)
        {
            UploadResult result = new UploadResult { URL = url };

            Dictionary<string, string> args = new Dictionary<string, string>();
            args.Add("url", url);

            string response = SendRequest(HttpMethod.GET, API_ENDPOINT, args);

            if (!string.IsNullOrEmpty(response) && response != "Invalid URL")
            {
                result.ShortenedURL = response;
            }

            return result;
        }
Exemple #22
0
        public override UploadResult UploadText(string text, string fileName)
        {
            UploadResult ur = new UploadResult();

            if (!string.IsNullOrEmpty(text))
            {
                Dictionary<string, string> arguments = new Dictionary<string, string>();
                arguments.Add("code", text);
                arguments.Add("description", settings.Description);
                arguments.Add("lang", settings.TextFormat);
                arguments.Add("parent", "0");

                ur.URL = SendRequest(HttpMethod.POST, APIURL, arguments, responseType: ResponseType.RedirectionURL);
            }

            return ur;
        }
Exemple #23
0
        private UploadResult ParseResult(UploadResult result)
        {
            if (result.IsSuccess)
            {
                XDocument xdoc = XDocument.Parse(result.Response);
                XElement xele = xdoc.Root.Element("upload");

                string error = xele.GetElementValue("errorCode");
                if (!string.IsNullOrEmpty(error))
                {
                    string errorMessage;

                    switch (error)
                    {
                        case "1":
                            errorMessage = "The MD5 sum that you provided did not match the MD5 sum that we calculated for the uploaded image file." +
                                           " There may of been a network interruption during upload. Suggest that you try the upload again.";
                            break;
                        case "2":
                            errorMessage = "The apiKey that you provided does not exist or has been banned. Please contact us for more information.";
                            break;
                        case "3":
                            errorMessage = "The file that you provided was not a png or jpg.";
                            break;
                        case "4":
                            errorMessage = "The file that you provided was too large, currently the limit per file is 50MB.";
                            break;
                        case "99":
                        default:
                            errorMessage = "An unkown error occured, please contact the admin and include a copy of the file that you were trying to upload.";
                            break;
                    }

                    Errors.Add(errorMessage);
                }
                else
                {
                    result.URL = xele.GetElementValue("original");
                    result.ThumbnailURL = xele.GetElementValue("small");
                    result.DeletionURL = xele.GetElementValue("deleteurl");
                }
            }

            return result;
        }
        public override UploadResult ShortenURL(string url)
        {
            if (customUploader.RequestType == CustomUploaderRequestType.POST && !string.IsNullOrEmpty(customUploader.FileFormName))
                throw new Exception("'File form name' cannot be used with custom URL shortener.");

            if (customUploader.Arguments == null || !customUploader.Arguments.Any(x => x.Value.Contains("$input$") || x.Value.Contains("%input")))
                throw new Exception("Atleast one '$input$' required for argument value.");

            UploadResult result = new UploadResult { URL = url };

            Dictionary<string, string> args = customUploader.GetArguments(url);

            result.Response = SendRequest(customUploader.GetHttpMethod(), customUploader.GetRequestURL(), args, headers: customUploader.Headers.ToNameValueCollection(), responseType: customUploader.ResponseType);

            customUploader.ParseResponse(result, true);

            return result;
        }
        public override UploadResult Upload(Stream stream, string fileName)
        {
            UploadResult result = new UploadResult();

            string filePath = account.GetLocalhostPath(fileName);

            Helpers.CreateDirectoryIfNotExist(filePath);

            using (FileStream fs = new FileStream(filePath, FileMode.Create))
            {
                if (TransferData(stream, fs))
                {
                    result.URL = account.GetUriPath(Path.GetFileName(fileName));
                }
            }

            return result;
        }
        public override UploadResult UploadText(string text, string fileName)
        {
            UploadResult result = new UploadResult();

            string requestURL = customUploader.GetRequestURL();

            if ((customUploader.RequestType != CustomUploaderRequestType.POST || string.IsNullOrEmpty(customUploader.FileFormName)) &&
                (customUploader.Arguments == null || !customUploader.Arguments.Any(x => x.Value.Contains("$input$") || x.Value.Contains("%input"))))
                throw new Exception("Atleast one '$input$' required for argument value.");

            Dictionary<string, string> args = customUploader.GetArguments(text);

            if (customUploader.RequestType == CustomUploaderRequestType.POST)
            {
                if (string.IsNullOrEmpty(customUploader.FileFormName))
                {
                    result.Response = SendRequest(HttpMethod.POST, requestURL, args, customUploader.GetHeaders(), responseType: customUploader.ResponseType);
                }
                else
                {
                    byte[] byteArray = Encoding.UTF8.GetBytes(text);
                    using (MemoryStream stream = new MemoryStream(byteArray))
                    {
                        result = UploadData(stream, requestURL, fileName, customUploader.GetFileFormName(), args, customUploader.GetHeaders(), responseType: customUploader.ResponseType);
                    }
                }
            }
            else
            {
                result.Response = SendRequest(customUploader.GetHttpMethod(), requestURL, args, customUploader.GetHeaders(), responseType: customUploader.ResponseType);
            }

            try
            {
                customUploader.ParseResponse(result);
            }
            catch (Exception e)
            {
                Errors.Add(Resources.CustomFileUploader_Upload_Response_parse_failed_ + Environment.NewLine + e);
            }

            return result;
        }
 protected override void OnInit(EventArgs e)
 {
     if (this._isValidateLogin)
     {
         SessionManager.UserExp = "";
         UserEntity entity = SessionManager.User;
         if (entity == null)
         {
             UploadResult result = new UploadResult();
             result.IsSuccess = false;
             result.Message = "对不起<br>您的登陆已经过期请您重新登陆";
             this.RenderUploadResult(result);
         }
         if (this._operationUserLevels != null)
         {
             bool isOperation = false;
             foreach (UserLevelType userLevel in this._operationUserLevels)
             {
                 if (entity.UserLevel == userLevel)
                 {
                     isOperation = true;
                     break;
                 }
             }
             if (!isOperation)
             {
                 Response.ClearContent();
                 Response.Write(@"
                     <html>
                         <head></head>
                         <body bgcolor='#cad7f7'>
                             对不起!您没有此功能的操作权限
                         </body>
                     </html>
                  ");
                 Response.End();
                 return;
             }
         }
     }
     base.OnInit(e);
 }
Exemple #28
0
        public override UploadResult ShortenURL(string url)
        {
            UploadResult result = new UploadResult { URL = url };

            Dictionary<string, string> args = new Dictionary<string, string>();
            args.Add("key", APIKEY);
            args.Add("uid", APIUID);
            args.Add("advert_type", "int");
            args.Add("domain", "adf.ly");
            args.Add("url", url);

            string response = SendRequest(HttpMethod.GET, "http://api.adf.ly/api.php", args);

            if (!string.IsNullOrEmpty(response) && response != "error")
            {
                result.ShortenedURL = response;
            }

            return result;
        }
Exemple #29
0
        public override UploadResult ShortenURL(string url)
        {
            UploadResult result = new UploadResult { URL = url };

            if (!string.IsNullOrEmpty(url))
            {
                Dictionary<string, string> arguments = new Dictionary<string, string>();
                arguments.Add("format", "simple");
                arguments.Add("url", url);

                result.Response = SendRequest(HttpMethod.GET, APIURL, arguments);

                if (!result.Response.StartsWith("Error:", StringComparison.InvariantCultureIgnoreCase))
                {
                    result.ShortenedURL = result.Response;
                }
            }

            return result;
        }
Exemple #30
0
        public override UploadResult UploadText(string text, string fileName)
        {
            UploadResult ur = new UploadResult();

            if (!string.IsNullOrEmpty(text))
            {
                Dictionary<string, string> arguments = new Dictionary<string, string>();
                arguments.Add("paste[body]", text);
                arguments.Add("paste[restricted]", IsPublic ? "0" : "1");
                arguments.Add("paste[authorization]", "burger");

                ur.Response = SendRequestURLEncoded("http://pastie.org/pastes", arguments, responseType: ResponseType.RedirectionURL);

                if (!string.IsNullOrEmpty(ur.Response))
                {
                    ur.URL = ur.Response;
                }
            }

            return ur;
        }
Exemple #31
0
 public ImageOperate(UploadResult result)
 {
     this.Result = result;
 }
Exemple #32
0
 public ImageOperate(UploadResult result, string upYunPath)
 {
     this.Result    = result;
     this.UpYunPath = upYunPath;
 }
Exemple #33
0
        private UploadResult InternalUpload(Stream stream, string fileName, bool refreshTokenOnError)
        {
            Dictionary <string, string> args = new Dictionary <string, string>();
            NameValueCollection         headers;

            if (UploadMethod == AccountType.User)
            {
                if (!CheckAuthorization())
                {
                    return(null);
                }

                if (!string.IsNullOrEmpty(UploadAlbumID))
                {
                    args.Add("album", UploadAlbumID);
                }

                headers = GetAuthHeaders();
            }
            else
            {
                headers = new NameValueCollection();
                headers.Add("Authorization", "Client-ID " + AuthInfo.Client_ID);
            }

            ReturnResponseOnError = true;

            string fileFormName;

            if (Helpers.IsVideoFile(fileName))
            {
                fileFormName = "video";
            }
            else
            {
                fileFormName = "image";
            }

            UploadResult result = SendRequestFile("https://api.imgur.com/3/upload", stream, fileName, fileFormName, args, headers);

            if (!string.IsNullOrEmpty(result.Response))
            {
                ImgurResponse imgurResponse = JsonConvert.DeserializeObject <ImgurResponse>(result.Response);

                if (imgurResponse != null)
                {
                    if (imgurResponse.success && imgurResponse.status == 200)
                    {
                        ImgurImageData imageData = ((JObject)imgurResponse.data).ToObject <ImgurImageData>();

                        if (imageData != null && !string.IsNullOrEmpty(imageData.link))
                        {
                            if (DirectLink)
                            {
                                if (UseGIFV && !string.IsNullOrEmpty(imageData.gifv))
                                {
                                    result.URL = imageData.gifv;
                                }
                                else
                                {
                                    // webm uploads returns link with dot at the end
                                    result.URL = imageData.link.TrimEnd('.');
                                }
                            }
                            else
                            {
                                result.URL = $"https://imgur.com/{imageData.id}";
                            }

                            string thumbnail = "";

                            switch (ThumbnailType)
                            {
                            case ImgurThumbnailType.Small_Square:
                                thumbnail = "s";
                                break;

                            case ImgurThumbnailType.Big_Square:
                                thumbnail = "b";
                                break;

                            case ImgurThumbnailType.Small_Thumbnail:
                                thumbnail = "t";
                                break;

                            case ImgurThumbnailType.Medium_Thumbnail:
                                thumbnail = "m";
                                break;

                            case ImgurThumbnailType.Large_Thumbnail:
                                thumbnail = "l";
                                break;

                            case ImgurThumbnailType.Huge_Thumbnail:
                                thumbnail = "h";
                                break;
                            }

                            result.ThumbnailURL = $"https://i.imgur.com/{imageData.id}{thumbnail}.jpg"; // Imgur thumbnails always jpg
                            result.DeletionURL  = $"https://imgur.com/delete/{imageData.deletehash}";
                        }
                    }
                    else
                    {
                        ImgurErrorData errorData = ParseError(imgurResponse);

                        if (errorData != null)
                        {
                            if (UploadMethod == AccountType.User && refreshTokenOnError &&
                                ((string)errorData.error).Equals("The access token provided is invalid.", StringComparison.InvariantCultureIgnoreCase) &&
                                RefreshAccessToken())
                            {
                                DebugHelper.WriteLine("Imgur access token refreshed, reuploading image.");

                                return(InternalUpload(stream, fileName, false));
                            }

                            string errorMessage = $"Imgur upload failed: ({imgurResponse.status}) {errorData.error}";
                            Errors.Insert(0, errorMessage);
                        }
                    }
                }
            }

            return(result);
        }
Exemple #34
0
        public override UploadResult UploadText(string text, string fileName)
        {
            UploadResult result = new UploadResult();
            CustomUploaderArgumentInput input = new CustomUploaderArgumentInput(fileName, text);

            CustomUploaderRequestFormat requestFormat = uploader.GetRequestFormat(CustomUploaderDestinationType.TextUploader);

            if (requestFormat == CustomUploaderRequestFormat.MultipartFormData)
            {
                if (string.IsNullOrEmpty(uploader.FileFormName))
                {
                    result.Response = SendRequestMultiPart(uploader.GetRequestURL(), uploader.GetArguments(input),
                                                           uploader.GetHeaders(input), null, uploader.ResponseType, uploader.RequestType);
                }
                else
                {
                    byte[] bytes = Encoding.UTF8.GetBytes(text);
                    using (MemoryStream stream = new MemoryStream(bytes))
                    {
                        result = SendRequestFile(uploader.GetRequestURL(), stream, fileName, uploader.GetFileFormName(),
                                                 uploader.GetArguments(input), uploader.GetHeaders(input), null, uploader.ResponseType, uploader.RequestType);
                    }
                }
            }
            else if (requestFormat == CustomUploaderRequestFormat.URLQueryString)
            {
                result.Response = SendRequest(uploader.RequestType, uploader.GetRequestURL(), uploader.GetArguments(input),
                                              uploader.GetHeaders(input), null, uploader.ResponseType);
            }
            else if (requestFormat == CustomUploaderRequestFormat.JSON)
            {
                result.Response = SendRequest(uploader.RequestType, uploader.GetRequestURL(), uploader.GetData(input), UploadHelpers.ContentTypeJSON,
                                              uploader.GetArguments(input), uploader.GetHeaders(input), null, uploader.ResponseType);
            }
            else if (requestFormat == CustomUploaderRequestFormat.Binary)
            {
                byte[] bytes = Encoding.UTF8.GetBytes(text);
                using (MemoryStream stream = new MemoryStream(bytes))
                {
                    result.Response = SendRequest(uploader.RequestType, uploader.GetRequestURL(), stream, UploadHelpers.GetMimeType(fileName),
                                                  uploader.GetArguments(input), uploader.GetHeaders(input), null, uploader.ResponseType);
                }
            }
            else if (requestFormat == CustomUploaderRequestFormat.FormURLEncoded)
            {
                result.Response = SendRequestURLEncoded(uploader.RequestType, uploader.GetRequestURL(), uploader.GetArguments(input),
                                                        uploader.GetHeaders(input), null, uploader.ResponseType);
            }
            else
            {
                throw new Exception("Unsupported request format.");
            }

            try
            {
                uploader.ParseResponse(result);
            }
            catch (Exception e)
            {
                Errors.Add(Resources.CustomFileUploader_Upload_Response_parse_failed_ + Environment.NewLine + e);
            }

            return(result);
        }
Exemple #35
0
        public override UploadResult Upload(Stream stream, string fileName)
        {
            if (!CheckAuthorization())
            {
                return(null);
            }

            string title                   = Path.GetFileNameWithoutExtension(fileName);
            string description             = "";
            YouTubeVideoPrivacy visibility = PrivacyType;

            if (ShowDialog)
            {
                using (YouTubeVideoOptionsForm form = new YouTubeVideoOptionsForm(title, description, visibility))
                {
                    if (form.ShowDialog() == DialogResult.OK)
                    {
                        title       = form.Title;
                        description = form.Description;
                        visibility  = form.Visibility;
                    }
                    else
                    {
                        return(null);
                    }
                }
            }

            YouTubeVideoUpload uploadVideo = new YouTubeVideoUpload()
            {
                snippet = new YouTubeVideoSnippet()
                {
                    title       = title,
                    description = description
                },
                status = new YouTubeVideoStatusUpload()
                {
                    privacyStatus = visibility
                }
            };

            string metadata = JsonConvert.SerializeObject(uploadVideo);

            UploadResult result = SendRequestFile("https://www.googleapis.com/upload/youtube/v3/videos?part=id,snippet,status", stream, fileName, "file",
                                                  headers: googleAuth.GetAuthHeaders(), relatedData: metadata);

            if (!string.IsNullOrEmpty(result.Response))
            {
                YouTubeVideoResponse responseVideo = JsonConvert.DeserializeObject <YouTubeVideoResponse>(result.Response);

                if (responseVideo != null)
                {
                    if (UseShortenedLink)
                    {
                        result.URL = $"https://youtu.be/{responseVideo.id}";
                    }
                    else
                    {
                        result.URL = $"https://www.youtube.com/watch?v={responseVideo.id}";
                    }

                    switch (responseVideo.status.uploadStatus)
                    {
                    case YouTubeVideoStatus.UploadFailed:
                        Errors.Add("Upload failed: " + responseVideo.status.failureReason);
                        break;

                    case YouTubeVideoStatus.UploadRejected:
                        Errors.Add("Upload rejected: " + responseVideo.status.rejectionReason);
                        break;
                    }
                }
            }

            return(result);
        }
Exemple #36
0
        public override UploadResult Upload(Stream stream, string fileName)
        {
            if (string.IsNullOrEmpty(APIURL))
            {
                throw new Exception("Seafile API URL is empty.");
            }

            if (string.IsNullOrEmpty(AuthToken))
            {
                throw new Exception("Seafile Authentication Token is empty.");
            }

            if (string.IsNullOrEmpty(Path))
            {
                Path = "/";
            }
            else
            {
                char pathLast = Path[Path.Length - 1];
                if (pathLast != '/')
                {
                    Path += "/";
                }
            }

            string url = URLHelpers.FixPrefix(APIURL);

            url = URLHelpers.CombineURL(APIURL, "repos/" + RepoID + "/upload-link/?format=json");

            NameValueCollection headers = new NameValueCollection();

            headers.Add("Authorization", "Token " + AuthToken);

            SSLBypassHelper sslBypassHelper = null;

            try
            {
                if (IgnoreInvalidCert)
                {
                    sslBypassHelper = new SSLBypassHelper();
                }

                string response = SendRequest(HttpMethod.GET, url, null, headers);

                string responseURL = response.Trim('"');

                Dictionary <string, string> args = new Dictionary <string, string>();
                args.Add("filename", fileName);
                args.Add("parent_dir", Path);

                UploadResult result = SendRequestFile(responseURL, stream, fileName, "file", args, headers);

                if (!IsError)
                {
                    if (CreateShareableURL && !IsLibraryEncrypted)
                    {
                        AllowReportProgress = false;
                        result.URL          = ShareFile(Path + fileName);
                    }
                    else
                    {
                        result.IsURLExpected = false;
                    }
                }

                return(result);
            }
            finally
            {
                if (sslBypassHelper != null)
                {
                    sslBypassHelper.Dispose();
                }
            }
        }
Exemple #37
0
        public override UploadResult Upload(Stream stream, string fileName)
        {
            string url = "https://up.flickr.com/services/upload/";

            Dictionary <string, string> args = new Dictionary <string, string>();

            if (!string.IsNullOrEmpty(Settings.Title))
            {
                args.Add("title", Settings.Title);
            }
            if (!string.IsNullOrEmpty(Settings.Description))
            {
                args.Add("description", Settings.Description);
            }
            if (!string.IsNullOrEmpty(Settings.Tags))
            {
                args.Add("tags", Settings.Tags);
            }
            if (!string.IsNullOrEmpty(Settings.IsPublic))
            {
                args.Add("is_public", Settings.IsPublic);
            }
            if (!string.IsNullOrEmpty(Settings.IsFriend))
            {
                args.Add("is_friend", Settings.IsFriend);
            }
            if (!string.IsNullOrEmpty(Settings.IsFamily))
            {
                args.Add("is_family", Settings.IsFamily);
            }
            if (!string.IsNullOrEmpty(Settings.SafetyLevel))
            {
                args.Add("safety_level", Settings.SafetyLevel);
            }
            if (!string.IsNullOrEmpty(Settings.ContentType))
            {
                args.Add("content_type", Settings.ContentType);
            }
            if (!string.IsNullOrEmpty(Settings.Hidden))
            {
                args.Add("hidden", Settings.Hidden);
            }

            string query = OAuthManager.GenerateQuery(url, args, HttpMethod.POST, AuthInfo, out Dictionary <string, string> parameters);

            UploadResult result = SendRequestFile(url, stream, fileName, "photo", parameters);

            if (result.IsSuccess)
            {
                XElement xele = ParseResponse(result.Response, "photoid");

                if (xele != null)
                {
                    string photoid = xele.Value;
                    FlickrPhotosGetSizesResponse photos = PhotosGetSizes(photoid);
                    FlickrPhotosGetSizesSize     photo  = photos?.sizes?.size?[photos.sizes.size.Length - 1];
                    if (photo != null)
                    {
                        if (Settings.DirectLink)
                        {
                            result.URL = photo.source;
                        }
                        else
                        {
                            result.URL = photo.url;
                        }
                    }
                }
            }

            return(result);
        }
        public static AnalyticsResult SendUploadCompletedEvent(string projectID, TimeSpan duration, UploadResult result)
        {
            if (!EditorAnalytics.enabled || !RegisterEvent(EventUploadCompleted))
            {
                return(AnalyticsResult.AnalyticsDisabled);
            }

            var data = new UploadCompletedEventData
            {
                ts       = DateTime.UtcNow.Millisecond,
                id       = projectID,
                duration = duration.Milliseconds,
                result   = (int)result
            };

            return(SendEvent(EventUploadCompleted, data));
        }
        internal static void UploadCompleted(UploadResult result)
        {
            TimeSpan lastUploadDuration = DateTime.UtcNow - Instance.lastUploadStartTime;

            SendUploadCompletedEvent(ProjectID, lastUploadDuration, result);
        }
Exemple #40
0
        public override UploadResult Upload(Stream stream, string fileName)
        {
            Dictionary <string, string> args = new Dictionary <string, string>();

            args.Add("api_key", API_Key);
            args.Add("auth_token", Auth.Token);

            if (!string.IsNullOrEmpty(Settings.Title))
            {
                args.Add("title", Settings.Title);
            }
            if (!string.IsNullOrEmpty(Settings.Description))
            {
                args.Add("description", Settings.Description);
            }
            if (!string.IsNullOrEmpty(Settings.Tags))
            {
                args.Add("tags", Settings.Tags);
            }
            if (!string.IsNullOrEmpty(Settings.IsPublic))
            {
                args.Add("is_public", Settings.IsPublic);
            }
            if (!string.IsNullOrEmpty(Settings.IsFriend))
            {
                args.Add("is_friend", Settings.IsFriend);
            }
            if (!string.IsNullOrEmpty(Settings.IsFamily))
            {
                args.Add("is_family", Settings.IsFamily);
            }
            if (!string.IsNullOrEmpty(Settings.SafetyLevel))
            {
                args.Add("safety_level", Settings.SafetyLevel);
            }
            if (!string.IsNullOrEmpty(Settings.ContentType))
            {
                args.Add("content_type", Settings.ContentType);
            }
            if (!string.IsNullOrEmpty(Settings.Hidden))
            {
                args.Add("hidden", Settings.Hidden);
            }

            args.Add("api_sig", GetAPISig(args));

            UploadResult result = UploadData(stream, "https://up.flickr.com/services/upload/", fileName, "photo", args);

            if (result.IsSuccess)
            {
                XElement xele = ParseResponse(result.Response, "photoid");

                if (null != xele)
                {
                    string photoid = xele.Value;
                    string url     = URLHelpers.CombineURL(GetPhotosLink(), photoid);
                    result.URL = URLHelpers.CombineURL(url, "sizes/o");
                }
            }

            return(result);
        }
Exemple #41
0
        public UploadResult PushFile(Stream stream, string fileName)
        {
            NameValueCollection headers = UploadHelpers.CreateAuthenticationHeader(Config.UserAPIKey, "");

            Dictionary <string, string> pushArgs, upArgs = new Dictionary <string, string>();

            upArgs.Add("file_name", fileName);

            string uploadRequest = SendRequestMultiPart(apiRequestFileUploadURL, upArgs, headers);

            if (uploadRequest == null)
            {
                return(null);
            }

            PushbulletResponseFileUpload fileInfo = JsonConvert.DeserializeObject <PushbulletResponseFileUpload>(uploadRequest);

            if (fileInfo == null)
            {
                return(null);
            }

            pushArgs = upArgs;

            upArgs = new Dictionary <string, string>();

            upArgs.Add("awsaccesskeyid", fileInfo.data.awsaccesskeyid);
            upArgs.Add("acl", fileInfo.data.acl);
            upArgs.Add("key", fileInfo.data.key);
            upArgs.Add("signature", fileInfo.data.signature);
            upArgs.Add("policy", fileInfo.data.policy);
            upArgs.Add("content-type", fileInfo.data.content_type);

            UploadResult uploadResult = SendRequestFile(fileInfo.upload_url, stream, fileName, "file", upArgs);

            if (uploadResult == null)
            {
                return(null);
            }

            pushArgs.Add("device_iden", Config.CurrentDevice.Key);
            pushArgs.Add("type", "file");
            pushArgs.Add("file_url", fileInfo.file_url);
            pushArgs.Add("body", "Sent via ShareX");

            string pushResult = SendRequestMultiPart(apiSendPushURL, pushArgs, headers);

            if (pushResult == null)
            {
                return(null);
            }

            PushbulletResponsePush push = JsonConvert.DeserializeObject <PushbulletResponsePush>(pushResult);

            if (push != null)
            {
                uploadResult.URL = wwwPushesURL + "?push_iden=" + push.iden;
            }

            return(uploadResult);
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            bool tipShow = false;

            if (this.fuDataFile1.HasFile)
            {
                if (this.fuDataFile1.PostedFile.ContentLength > 0)
                {
                    string fileName = this.SaveDataFile(this.fuDataFile1);

                    if (fileName.IsNotNullOrEmpty())
                    {
                        UploadResult result = this.ImportDataFile(fileName, this.cbIgnoreAlreadyUpload1.Checked);

                        this.SetUploadResult(result, this.tdDataUploadResult1);

                        tipShow = true;
                    }
                }

                else
                {
                    this.tdDataUploadResult1.InnerHtml = "请选择有效的数据文件";
                }
            }

            else
            {
                this.tdDataUploadResult1.InnerHtml = String.Empty;
            }

            /**/

            if (this.fuDataFile2.HasFile)
            {
                if (this.fuDataFile2.PostedFile.ContentLength > 0)
                {
                    string fileName = this.SaveDataFile(this.fuDataFile2);

                    if (fileName.IsNotNullOrEmpty())
                    {
                        UploadResult result = this.ImportDataFile(fileName, this.cbIgnoreAlreadyUpload2.Checked);

                        this.SetUploadResult(result, this.tdDataUploadResult2);

                        tipShow = true;
                    }
                }

                else
                {
                    this.tdDataUploadResult2.InnerText = "请选择有效的数据文件";
                }
            }

            else
            {
                this.tdDataUploadResult2.InnerHtml = String.Empty;
            }

            /**/

            if (this.fuDataFile3.HasFile)
            {
                if (this.fuDataFile3.PostedFile.ContentLength > 0)
                {
                    string fileName = this.SaveDataFile(this.fuDataFile3);

                    if (fileName.IsNotNullOrEmpty())
                    {
                        UploadResult result = this.ImportDataFile(fileName, this.cbIgnoreAlreadyUpload3.Checked);

                        this.SetUploadResult(result, this.tdDataUploadResult3);

                        tipShow = true;
                    }
                }

                else
                {
                    this.tdDataUploadResult3.InnerText = "请选择有效的数据文件";
                }
            }

            else
            {
                this.tdDataUploadResult3.InnerHtml = String.Empty;
            }

            /**/

            if (this.fuDataFile4.HasFile)
            {
                if (this.fuDataFile4.PostedFile.ContentLength > 0)
                {
                    string fileName = this.SaveDataFile(this.fuDataFile4);

                    if (fileName.IsNotNullOrEmpty())
                    {
                        UploadResult result = this.ImportDataFile(fileName, this.cbIgnoreAlreadyUpload4.Checked);

                        this.SetUploadResult(result, this.tdDataUploadResult4);

                        tipShow = true;
                    }
                }

                else
                {
                    this.tdDataUploadResult4.InnerText = "请选择有效的数据文件";
                }
            }

            else
            {
                this.tdDataUploadResult4.InnerHtml = String.Empty;
            }

            /**/

            if (this.fuDataFile5.HasFile)
            {
                if (this.fuDataFile5.PostedFile.ContentLength > 0)
                {
                    string fileName = this.SaveDataFile(this.fuDataFile5);

                    if (fileName.IsNotNullOrEmpty())
                    {
                        UploadResult result = this.ImportDataFile(fileName, this.cbIgnoreAlreadyUpload5.Checked);

                        this.SetUploadResult(result, this.tdDataUploadResult5);

                        tipShow = true;
                    }
                }

                else
                {
                    this.tdDataUploadResult5.InnerText = "请选择有效的数据文件";
                }
            }

            else
            {
                this.tdDataUploadResult5.InnerHtml = String.Empty;
            }

            if (tipShow)
            {
                this.JscriptMsg("数据上传成功", null, "Success");
            }

            else
            {
                this.JscriptMsg("至少上传一个文件", null, "Error");
            }
        }
Exemple #43
0
        private void TranscodeFile(UploadResult result)
        {
            StreamableTranscodeResponse transcodeResponse = JsonConvert.DeserializeObject <StreamableTranscodeResponse>(result.Response);

            if (!string.IsNullOrEmpty(transcodeResponse.Shortcode))
            {
                ProgressManager progress = new ProgressManager(100);

                if (AllowReportProgress)
                {
                    OnProgressChanged(progress);
                }

                while (!StopUploadRequested)
                {
                    string statusJson = SendRequest(HttpMethod.GET, URLHelpers.CombineURL(Host, "videos", transcodeResponse.Shortcode));
                    StreamableStatusResponse response = JsonConvert.DeserializeObject <StreamableStatusResponse>(statusJson);

                    if (response.status > 2)
                    {
                        Errors.Add(response.message);
                        result.IsSuccess = false;
                        break;
                    }
                    else if (response.status == 2)
                    {
                        if (AllowReportProgress)
                        {
                            long delta = 100 - progress.Position;
                            progress.UpdateProgress(delta);
                            OnProgressChanged(progress);
                        }

                        result.IsSuccess = true;

                        if (UseDirectURL && response.files != null && response.files.mp4 != null && !string.IsNullOrEmpty(response.files.mp4.url))
                        {
                            result.URL = URLHelpers.ForcePrefix(response.files.mp4.url);
                        }
                        else
                        {
                            result.URL = URLHelpers.ForcePrefix(response.url);
                        }

                        break;
                    }

                    if (AllowReportProgress)
                    {
                        long delta = response.percent - progress.Position;
                        progress.UpdateProgress(delta);
                        OnProgressChanged(progress);
                    }

                    Thread.Sleep(100);
                }
            }
            else
            {
                Errors.Add("Could not create video");
                result.IsSuccess = false;
            }
        }
Exemple #44
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            var uploads = new List <UploadFileInfo>();

            var basePath = HttpContext.Current.Request.Form["path"];

            if (!basePath.StartsWith(SiteSettings.Instance.FilePath))
            {
                var exception = new AccessViolationException(string.Format("Wrong path for uploads! {0}", basePath));
                Logger.Write(exception, Logger.Severity.Major);
                throw exception;
            }

            basePath = HttpContext.Current.Server.MapPath(basePath);

            foreach (string file in context.Request.Files)
            {
                var    postedFile = context.Request.Files[file];
                string fileName;

                if (postedFile.ContentLength == 0)
                {
                    continue;
                }

                if (postedFile.FileName.Contains("\\"))
                {
                    string[] parts = postedFile.FileName.Split(new[] { '\\' });
                    fileName = parts[parts.Length - 1];
                }
                else
                {
                    fileName = postedFile.FileName;
                }

                if (IsFileExtensionBlocked(fileName))
                {
                    Logger.Write(string.Format("Upload of {0} blocked since file type is not allowed.", fileName), Logger.Severity.Major);
                    uploads.Add(new UploadFileInfo {
                        name  = Path.GetFileName(fileName),
                        size  = postedFile.ContentLength,
                        type  = postedFile.ContentType,
                        error = "Filetype not allowed!"
                    });
                    continue;
                }

                var savedFileName = GetUniqueFileName(basePath, fileName);
                postedFile.SaveAs(savedFileName);

                uploads.Add(new UploadFileInfo {
                    name = Path.GetFileName(savedFileName),
                    size = postedFile.ContentLength,
                    type = postedFile.ContentType
                });
            }

            var uploadResult         = new UploadResult(uploads);
            var serializedUploadInfo = Serialization.JsonSerialization.SerializeJson(uploadResult);

            context.Response.Write(serializedUploadInfo);
        }
Exemple #45
0
        public async Task <BaseResult> Upload(FileModel model)
        {
            var result = new UploadResult();

            try
            {
                if (model.File.Length > 0)
                {
                    //extension validation
                    var extension = Path.GetExtension(model.File.FileName).ToLowerInvariant();
                    if (string.IsNullOrEmpty(extension) || !permittedExtensions.Contains(extension))
                    {
                        result.Result  = Result.Failed;
                        result.Message = $"Định dạng file không hợp lệ, hãy sử dụng file có định dạng: {{{string.Join(", ", permittedExtensions)}}}";
                    }
                    else
                    {
                        //set new name if exists
                        model.Name = string.IsNullOrEmpty(model.Name) ? (model.File.FileName) : (model.Name + extension);

                        //get hashed name
                        var hashName = model.File.FileName.GetHashCode().ToString() + extension;

                        //create path directory if not exists
                        var path = string.IsNullOrEmpty(model.Path) ? Path.Combine(WebHostEnvironment.WebRootPath, "upload") : Path.Combine(WebHostEnvironment.WebRootPath, "upload", model.Path);
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }

                        //upload file to directory
                        using (var fileStream = System.IO.File.Create(Path.Combine(path, hashName)))
                        {
                            //upload
                            await model.File.CopyToAsync(fileStream);

                            await fileStream.FlushAsync();

                            //create data in sql
                            var file = new Domains.Files.File()
                            {
                                Name     = model.Name,
                                HashName = hashName,
                                Path     = model.Path,
                                Domain   = Domain
                            };
                            file.UpdateCommonInt();
                            await FileRepository.InsertAsync(file);

                            result.Id = file.Id;
                        }
                    }
                }
                else
                {
                    result.Result  = Result.Failed;
                    result.Message = "Không tìm thấy file";
                }
            }
            catch (Exception e)
            {
                result.Result  = Result.SystemError;
                result.Message = e.ToString();
            }
            return(result);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="StubAttachmentUploader" /> class.
 /// </summary>
 /// <param name="downloadUrl"></param>
 public StubAttachmentUploader(string downloadUrl)
 {
     _configuredResult = UploadResult.SuccessWithUrl(downloadUrl: downloadUrl);
 }
Exemple #47
0
        public override UploadResult Upload(Stream stream, string fileName)
        {
            ThrowWebExceptions = true;

            string hash = CreateHash(stream);

            UploadResult result = CheckExists(hash);

            if (result != null)
            {
                return(result);
            }

            try
            {
                result = UploadData(stream, URLHelpers.CombineURL(APIURL, "api/upload/file"), fileName);
            }
            catch (WebException e)
            {
                HttpWebResponse response = e.Response as HttpWebResponse;

                if (response == null)
                {
                    throw;
                }

                if (response.StatusCode == HttpStatusCode.Conflict)
                {
                    return(HandleDuplicate(response));
                }

                throw;
            }

            hash = JToken.Parse(result.Response)["hash"].Value <string>();

            while (!StopUploadRequested)
            {
                result.Response = SendRequest(HttpMethod.GET, URLHelpers.CombineURL(APIURL, "api/" + hash + "/status"));
                JToken jsonResponse = JToken.Parse(result.Response);
                string status       = jsonResponse["status"].Value <string>();

                switch (status)
                {
                case "processing":
                case "pending":
                    Thread.Sleep(500);
                    break;

                case "done":
                case "ready":
                    MediaCrushBlob blob = jsonResponse[hash].ToObject <MediaCrushBlob>();
                    return(UpdateResult(result, blob));

                case "unrecognized":
                    // Note: MediaCrush accepts just about _every_ kind of media file,
                    // so the file itself is probably corrupted or just not actually a media file
                    throw new Exception("This file is not an acceptable file type.");

                case "timeout":
                    throw new Exception("This file took too long to process.");

                default:
                    throw new Exception("This file failed to process.");
                }
            }

            return(result);
        }
Exemple #48
0
        public override UploadResult Upload(Stream stream, string fileName)
        {
            if (string.IsNullOrEmpty(s3Settings.AccessKeyID))
            {
                throw new Exception("'Access Key' must not be empty.");
            }
            if (string.IsNullOrEmpty(s3Settings.SecretAccessKey))
            {
                throw new Exception("'Secret Access Key' must not be empty.");
            }
            if (string.IsNullOrEmpty(s3Settings.Bucket))
            {
                throw new Exception("'Bucket' must not be empty.");
            }
            if (GetCurrentRegion(s3Settings) == UnknownEndpoint)
            {
                throw new Exception("Please select an endpoint.");
            }

            var region = GetCurrentRegion(s3Settings);

            var s3ClientConfig = new AmazonS3Config();

            if (region.AmazonRegion == null)
            {
                s3ClientConfig.ServiceURL = "https://" + region.Hostname;
            }
            else
            {
                s3ClientConfig.RegionEndpoint = region.AmazonRegion;
            }

            using (var client = new AmazonS3Client(GetCurrentCredentials(), s3ClientConfig))
            {
                var putRequest = new GetPreSignedUrlRequest
                {
                    BucketName  = s3Settings.Bucket,
                    Key         = GetObjectKey(fileName),
                    Verb        = HttpVerb.PUT,
                    Expires     = DateTime.UtcNow.AddMinutes(5),
                    ContentType = Helpers.GetMimeType(fileName)
                };

                var requestHeaders = new NameValueCollection();
                requestHeaders["x-amz-acl"]           = "public-read";
                requestHeaders["x-amz-storage-class"] = GetObjectStorageClass();

                putRequest.Headers["x-amz-acl"]           = "public-read";
                putRequest.Headers["x-amz-storage-class"] = GetObjectStorageClass();

                var responseHeaders = SendRequestStreamGetHeaders(client.GetPreSignedURL(putRequest), stream, Helpers.GetMimeType(fileName), requestHeaders, method: HttpMethod.PUT);
                var eTag            = responseHeaders["ETag"].Replace("\"", "");

                var uploadResult = new UploadResult();

                if (GetMd5Hash(stream) == eTag)
                {
                    uploadResult.IsSuccess = true;
                    uploadResult.URL       = GetObjectURL(putRequest.Key);
                }
                else
                {
                    uploadResult.Errors = new List <string> {
                        "Uploaded file is different."
                    };
                }

                return(uploadResult);
            }
        }
Exemple #49
0
        /// <summary>
        /// 上传操作
        /// </summary>
        /// <param name="dirPath">目录路径</param>
        /// <param name="fileTypes">文件类型</param>
        /// <param name="maxFileSize">最大文件大小,默认10M</param>
        /// <returns></returns>
        protected Task <UploadResult> Upload(string dirPath, string fileTypes, long maxFileSize = 10000000)
        {
            if (!Request.Content.IsMimeMultipartContent("form-data"))
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            string dirTempPath = SysControl.GetPhysicalPath(dirPath);

            if (!Directory.Exists(dirTempPath))
            {
                Directory.CreateDirectory(dirTempPath);
            }
            // 设置上传目录
            var provider = new MultipartFormDataStreamProvider(dirTempPath);
            var task     = Request.Content.ReadAsMultipartAsync(provider).ContinueWith <UploadResult>(o =>
            {
                FileInfo fileInfo = null;
                try
                {
                    UploadResult result = new UploadResult();
                    // 判断文件数据
                    if (!(provider.FileData.Count > 0))
                    {
                        throw new Exception("上传失败,文件数据不存在!");
                    }
                    if (o.IsFaulted || o.IsCanceled)
                    {
                        throw new Exception("上传失败!");
                    }

                    var file           = provider.FileData[0];
                    string oldFileName = file.Headers.ContentDisposition.FileName.TrimStart('"').TrimEnd('"');
                    fileInfo           = new FileInfo(file.LocalFileName);
                    result.Length      = fileInfo.Length;

                    if (fileInfo.Length <= 0)
                    {
                        throw new Exception("请选择上传文件!");
                    }
                    if (fileInfo.Length > maxFileSize)
                    {
                        throw new Exception("上传文件大小超过限制!");
                    }

                    var fileExt = oldFileName.Substring(oldFileName.LastIndexOf('.'));
                    if (fileExt == null ||
                        Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1)
                    {
                        throw new Exception("不支持上传文件类型!");
                    }

                    string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo);
                    string filePath    = Path.Combine(dirPath, newFileName + fileExt);

                    fileInfo.CopyTo(Path.Combine(dirTempPath, newFileName + fileExt), true);

                    result.FileName = newFileName;
                    result.FilePath = filePath;
                    result.FileId   = newFileName;
                    result.Type     = FileControl.GetContentType(fileExt);
                    return(result);
                }
                catch (Exception ex)
                {
                    throw new Exception("上传失败!");
                }
                finally
                {
                    if (fileInfo != null)
                    {
                        fileInfo.Delete();
                    }
                }
            });

            return(task);
        }
Exemple #50
0
        public void AddAttachment(ChatMessage message, string fileName, string contentType, long size, UploadResult result)
        {
            var attachment = new Attachment
            {
                Id          = result.Identifier,
                Url         = result.Url,
                FileName    = fileName,
                ContentType = contentType,
                Size        = size,
                Room        = message.Room,
                Owner       = message.User,
                When        = DateTimeOffset.UtcNow
            };

            _repository.Add(attachment);
        }
Exemple #51
0
 public UploadInfo()
 {
     Result = new UploadResult();
 }
 /// <summary>
 /// 将扫码上传的文件保存至缓存
 /// </summary>
 /// <param name="guid"></param>
 /// <param name="uploadFileInfo"></param>
 public virtual void SetUploadInfo(string guid, UploadResult uploadResult)
 {
     CacheManager.GetCache <string, UploadResult>("ExternalUploadCache").Get(guid, () => uploadResult);
 }
Exemple #53
0
        public async Task <UploadResult> UploadFile(bool origin, bool min, bool mid, bool max)
        {
            // Check if the request contains multipart/form-data.
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            string folder = ConfigurationManager.AppSettings["FileIntMarketPath"].ToString()
                            + UploadHelper.GetDateFolder();

            string directory = HttpContext.Current.Server.MapPath("~/" + folder);

            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            var provider = new SQStreamProvider(directory);

            var result = new UploadResult();

            try
            {
                // Read the form data.
                await Request.Content.ReadAsMultipartAsync(provider);

                if (provider.FileData.Count() > 1)
                {
                    result.Error = "上传数量出错";

                    return(result);
                }
                FileInfo fi = new FileInfo(provider.FileData[0].LocalFileName);

                result.ImageName = fi.Name;
                result.Status    = "success";
                result.ImageUrl  = UploadHelper.GetImgSaveUrl(folder, fi.Name.Replace(fi.Extension, ""), fi.Extension);

                if (origin)
                {
                    return(result);
                }

                if (min)
                {
                    UploadHelper.Crop(fi.FullName, 120);
                    result.ImageUrl_120 = UploadHelper.GetImgSaveUrl(folder, fi.Name.Replace(fi.Extension, ""), ".jpg", 120);
                }
                if (mid)
                {
                    UploadHelper.Crop(fi.FullName, 430);
                    result.ImageUrl_430 = UploadHelper.GetImgSaveUrl(folder, fi.Name.Replace(fi.Extension, ""), ".jpg", 430);
                }
                if (max)
                {
                    UploadHelper.Crop(fi.FullName, 800);
                    result.ImageUrl_800 = UploadHelper.GetImgSaveUrl(folder, fi.Name.Replace(fi.Extension, ""), ".jpg", 430);
                }
                return(result);
            }
            catch (System.Exception e)
            {
                result.Error = e.Message;
                return(result);
            }
        }
Exemple #54
0
        public ActionResult UploadFile(string fileType)
        {
            string       callback = Request["callback"];
            UploadResult result   = new UploadResult()
            {
                State = UploadState.Unknown
            };
            UEditorModel uploadConfig = new UEditorModel();

            if (fileType == "uploadimage")
            {
                uploadConfig = new UEditorModel()
                {
                    AllowExtensions = UEditorConfig.GetStringList("imageAllowFiles"),
                    PathFormat      = UEditorConfig.GetString("imagePathFormat"),
                    SizeLimit       = UEditorConfig.GetInt("imageMaxSize"),
                    UploadFieldName = UEditorConfig.GetString("imageFieldName")
                };
            }
            if (fileType == "uploadscrawl")
            {
                uploadConfig = new UEditorModel()
                {
                    AllowExtensions = new string[] { ".png" },
                    PathFormat      = UEditorConfig.GetString("scrawlPathFormat"),
                    SizeLimit       = UEditorConfig.GetInt("scrawlMaxSize"),
                    UploadFieldName = UEditorConfig.GetString("scrawlFieldName"),
                    Base64          = true,
                    Base64Filename  = "scrawl.png"
                };
            }
            if (fileType == "uploadvideo")
            {
                uploadConfig = new UEditorModel()
                {
                    AllowExtensions = UEditorConfig.GetStringList("videoAllowFiles"),
                    PathFormat      = UEditorConfig.GetString("videoPathFormat"),
                    SizeLimit       = UEditorConfig.GetInt("videoMaxSize"),
                    UploadFieldName = UEditorConfig.GetString("videoFieldName")
                };
            }
            if (fileType == "uploadfile")
            {
                uploadConfig = new UEditorModel()
                {
                    AllowExtensions = UEditorConfig.GetStringList("fileAllowFiles"),
                    PathFormat      = UEditorConfig.GetString("filePathFormat"),
                    SizeLimit       = UEditorConfig.GetInt("fileMaxSize"),
                    UploadFieldName = UEditorConfig.GetString("fileFieldName")
                };
            }
            byte[] uploadFileBytes;
            string uploadFileName;

            if (uploadConfig.Base64)
            {
                uploadFileName  = uploadConfig.Base64Filename;
                uploadFileBytes = Convert.FromBase64String(Request[uploadConfig.UploadFieldName]);
            }
            else
            {
                var file = Request.Files[uploadConfig.UploadFieldName];
                uploadFileName = file.FileName;
                var fileExtension = Path.GetExtension(uploadFileName).ToLower();

                if (!uploadConfig.AllowExtensions.Select(x => x.ToLower()).Contains(fileExtension))
                {
                    result.State = UploadState.TypeNotAllow;
                    return(Content(WriteUploadResult(callback, result), string.IsNullOrWhiteSpace(callback) ? "text/plain" : "application/javascript"));
                }
                if (!(file.ContentLength < uploadConfig.SizeLimit))
                {
                    result.State = UploadState.SizeLimitExceed;
                    return(Content(WriteUploadResult(callback, result), string.IsNullOrWhiteSpace(callback) ? "text/plain" : "application/javascript"));
                }
                uploadFileBytes = new byte[file.ContentLength];
                try
                {
                    file.InputStream.Read(uploadFileBytes, 0, file.ContentLength);
                }
                catch (Exception)
                {
                    result.State = UploadState.NetworkError;
                    return(Content(WriteUploadResult(callback, result), string.IsNullOrWhiteSpace(callback) ? "text/plain" : "application/javascript"));
                }
            }
            result.OriginFileName = uploadFileName;

            var savePath  = PathFormatter.Format(uploadFileName, uploadConfig.PathFormat);
            var localPath = Server.MapPath(savePath);

            try
            {
                if (!Directory.Exists(Path.GetDirectoryName(localPath)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(localPath));
                }
                System.IO.File.WriteAllBytes(localPath, uploadFileBytes);
                result.Url   = savePath;
                result.State = UploadState.Success;
            }
            catch (Exception e)
            {
                result.State        = UploadState.FileAccessError;
                result.ErrorMessage = e.Message;
            }
            return(Content(WriteUploadResult(callback, result), string.IsNullOrWhiteSpace(callback) ? "text/plain" : "application/javascript"));
        }
Exemple #55
0
        private void DoAfterUploadJobs()
        {
            try
            {
                if (Info.TaskSettings.AdvancedSettings.ResultForceHTTPS)
                {
                    Info.Result.ForceHTTPS();
                }

                if (Info.Job != TaskJob.ShareURL && (Info.TaskSettings.AfterUploadJob.HasFlag(AfterUploadTasks.UseURLShortener) || Info.Job == TaskJob.ShortenURL ||
                                                     (Info.TaskSettings.AdvancedSettings.AutoShortenURLLength > 0 && Info.Result.URL.Length > Info.TaskSettings.AdvancedSettings.AutoShortenURLLength)))
                {
                    UploadResult result = ShortenURL(Info.Result.URL);

                    if (result != null)
                    {
                        Info.Result.ShortenedURL = result.ShortenedURL;
                        Info.Result.Errors.AddRange(result.Errors);
                    }
                }

                if (Info.Job != TaskJob.ShortenURL && (Info.TaskSettings.AfterUploadJob.HasFlag(AfterUploadTasks.ShareURL) || Info.Job == TaskJob.ShareURL))
                {
                    UploadResult result = ShareURL(Info.Result.ToString());

                    if (result != null)
                    {
                        Info.Result.Errors.AddRange(result.Errors);
                    }

                    if (Info.Job == TaskJob.ShareURL)
                    {
                        Info.Result.IsURLExpected = false;
                    }
                }

                if (Info.TaskSettings.AfterUploadJob.HasFlag(AfterUploadTasks.CopyURLToClipboard))
                {
                    string txt;

                    if (!string.IsNullOrEmpty(Info.TaskSettings.AdvancedSettings.ClipboardContentFormat))
                    {
                        txt = new UploadInfoParser().Parse(Info, Info.TaskSettings.AdvancedSettings.ClipboardContentFormat);
                    }
                    else
                    {
                        txt = Info.Result.ToString();
                    }

                    if (!string.IsNullOrEmpty(txt))
                    {
                        ClipboardHelpers.CopyText(txt);
                    }
                }

                if (Info.TaskSettings.AfterUploadJob.HasFlag(AfterUploadTasks.OpenURL))
                {
                    string result;

                    if (!string.IsNullOrEmpty(Info.TaskSettings.AdvancedSettings.OpenURLFormat))
                    {
                        result = new UploadInfoParser().Parse(Info, Info.TaskSettings.AdvancedSettings.OpenURLFormat);
                    }
                    else
                    {
                        result = Info.Result.ToString();
                    }

                    URLHelpers.OpenURL(result);
                }

                if (Info.TaskSettings.AfterUploadJob.HasFlag(AfterUploadTasks.ShowQRCode))
                {
                    threadWorker.InvokeAsync(() => new QRCodeForm(Info.Result.ToString()).Show());
                }
            }
            catch (Exception e)
            {
                DebugHelper.WriteException(e);
                AddErrorMessage(e.ToString());
            }
        }
Exemple #56
0
        private UploadResult InternalUpload(Stream stream, string fileName, bool refreshTokenOnError)
        {
            Dictionary <string, string> args = new Dictionary <string, string>();
            NameValueCollection         headers;

            if (UploadMethod == AccountType.User)
            {
                if (!CheckAuthorization())
                {
                    return(null);
                }

                if (!string.IsNullOrEmpty(UploadAlbumID))
                {
                    args.Add("album", UploadAlbumID);
                }

                headers = GetAuthHeaders();
            }
            else
            {
                headers = new NameValueCollection();
                headers.Add("Authorization", "Client-ID " + AuthInfo.Client_ID);
            }

            WebExceptionReturnResponse = true;
            UploadResult result = UploadData(stream, "https://api.imgur.com/3/image", fileName, "image", args, headers);

            if (!string.IsNullOrEmpty(result.Response))
            {
                ImgurResponse imgurResponse = JsonConvert.DeserializeObject <ImgurResponse>(result.Response);

                if (imgurResponse != null)
                {
                    if (imgurResponse.success && imgurResponse.status == 200)
                    {
                        ImgurImageData imageData = ((JObject)imgurResponse.data).ToObject <ImgurImageData>();

                        if (imageData != null && !string.IsNullOrEmpty(imageData.link))
                        {
                            if (Config.DirectLink)
                            {
                                if (UseGIFV && !string.IsNullOrEmpty(imageData.gifv))
                                {
                                    result.URL = imageData.gifv;
                                }
                                else
                                {
                                    result.URL = imageData.link;
                                }
                            }
                            else
                            {
                                result.URL = "http://imgur.com/" + imageData.id;
                            }

                            string thumbnail = string.Empty;

                            switch (ThumbnailType)
                            {
                            case ImgurThumbnailType.Small_Square:
                                thumbnail = "s";
                                break;

                            case ImgurThumbnailType.Big_Square:
                                thumbnail = "b";
                                break;

                            case ImgurThumbnailType.Small_Thumbnail:
                                thumbnail = "t";
                                break;

                            case ImgurThumbnailType.Medium_Thumbnail:
                                thumbnail = "m";
                                break;

                            case ImgurThumbnailType.Large_Thumbnail:
                                thumbnail = "l";
                                break;

                            case ImgurThumbnailType.Huge_Thumbnail:
                                thumbnail = "h";
                                break;
                            }

                            result.ThumbnailURL = string.Format("http://i.imgur.com/{0}{1}.jpg", imageData.id, thumbnail); // Thumbnails always jpg
                            result.DeletionURL  = "http://imgur.com/delete/" + imageData.deletehash;
                        }
                    }
                    else
                    {
                        ImgurErrorData errorData = ((JObject)imgurResponse.data).ToObject <ImgurErrorData>();

                        if (errorData != null)
                        {
                            if (UploadMethod == AccountType.User && refreshTokenOnError &&
                                errorData.error.Equals("The access token provided is invalid.", StringComparison.InvariantCultureIgnoreCase) && RefreshAccessToken())
                            {
                                DebugHelper.WriteLine("Imgur access token refreshed, reuploading image.");

                                return(InternalUpload(stream, fileName, false));
                            }

                            string errorMessage = string.Format("Imgur upload failed: ({0}) {1}", imgurResponse.status, errorData.error);
                            Errors.Clear();
                            Errors.Add(errorMessage);
                        }
                    }
                }
            }

            return(result);
        }
Exemple #57
0
        static void Main(string[] args)
        {
            var config = LoadAppSettings();

            if (config == null)
            {
                Console.WriteLine("Invalid appsettings.json file.");
                return;
            }

            var client = GetAuthenticatedGraphClient(config);

            //Upload small file
            var smallFile = "smallfile.txt";
            var smallPath = Path.Combine(System.IO.Directory.GetCurrentDirectory(), smallFile);

            Console.WriteLine("Uploading file: " + smallFile);

            FileStream fileStream   = new FileStream(smallPath, FileMode.Open);
            var        uploadedFile = client.Me.Drive.Root
                                      .ItemWithPath("smallfile.txt")
                                      .Content
                                      .Request()
                                      .PutAsync <DriveItem>(fileStream)
                                      .Result;

            Console.WriteLine("File uploaded to: " + uploadedFile.WebUrl);

            //Upload large file
            var largeFile = "dogs.zip";
            var largePath = Path.Combine(System.IO.Directory.GetCurrentDirectory(), largeFile);

            Console.WriteLine("Uploading file: " + largeFile);

            using (Stream stream = new FileStream(largePath, FileMode.Open))
            {
                var uploadSession = client.Me.Drive.Root
                                    .ItemWithPath(largeFile)
                                    .CreateUploadSession()
                                    .Request()
                                    .PostAsync()
                                    .Result;

                // create upload task
                var maxChunkSize    = 320 * 1024;
                var largeUploadTask = new LargeFileUploadTask <DriveItem>(uploadSession, stream, maxChunkSize);

                // create progress implementation
                IProgress <long> uploadProgress = new Progress <long>(uploadBytes =>
                {
                    Console.WriteLine($"Uploaded {uploadBytes} bytes of {stream.Length} bytes");
                });

                // upload file
                UploadResult <DriveItem> uploadResult = largeUploadTask.UploadAsync(uploadProgress).Result;
                if (uploadResult.UploadSucceeded)
                {
                    Console.WriteLine("File uploaded to user's OneDrive root folder.");
                }
            }
        }
        public static UploadResult upload_object(Project p0, string p1, string p2, UploadOptions p3)
        {
            UploadResult ret = new UploadResult(storj_uplinkPINVOKE.upload_object(Project.getCPtr(p0), p1, p2, UploadOptions.getCPtr(p3)), true);

            return(ret);
        }
        private UploadResult ImportDataFile(string fileName, bool isIgnoreAlreadyUpload)
        {
            UploadResult result = new UploadResult();

            using (CurrencyFileReader fileReader = new CurrencyFileReader(fileName))
            {
                FileHeader fileHeader = fileReader.FileHeader;
                IEnumerable <CurrencyInfo> dataList = fileReader.Read(isIgnoreAlreadyUpload).ToList();

                /**/

                IDeviceService deviceService = ServiceFactory.GetService <IDeviceService>();

                bool deviceExists = deviceService.CheckExists_Info(new DeviceInfo()
                {
                    DeviceNumber = fileHeader.MachineSN
                });

                result.FileType     = fileHeader.FileType;
                result.DeviceNumber = fileHeader.MachineSN;
                result.DeviceStatus = deviceExists ? "已入库" : "未入库";

                if (!deviceExists)
                {
                    DeviceInfo deviceInfo = new DeviceInfo()
                    {
                        OrgId           = 0,
                        ModelCode       = 0,
                        KindCode        = 0,
                        DeviceNumber    = fileHeader.MachineSN,
                        SoftwareVersion = fileHeader.SoftVersion,
                        OnLineTime      = DateTime.Now,
                        DeviceStatus    = 1,
                    };

                    deviceService.Save_Info(deviceInfo);
                }

                /**/

                result.TotalCount         = fileHeader.SumRecords;
                result.AlreadyUploadCount = fileHeader.UploadRecord;

                if (isIgnoreAlreadyUpload)
                {
                    result.ShouldSaveCount = result.TotalCount - result.AlreadyUploadCount;
                }

                else
                {
                    result.ShouldSaveCount = result.TotalCount;
                }

                /**/

                ICurrencyService currencyService = ServiceFactory.GetService <ICurrencyService>();

                int bufferCount            = 500;
                int maxCount               = dataList.Count();
                List <CurrencyInfo> buffer = null;

                for (int i = 0; i <= maxCount / bufferCount; i++)
                {
                    buffer = dataList.Skip(i * bufferCount).Take(bufferCount).ToList();

                    if (buffer.Count() > 0)
                    {
                        currencyService.BatchSave_Info(buffer);
                    }
                }

                result.SuccessSaveCount = maxCount;
            }

            return(result);
        }
Exemple #60
0
        private async void btnSave_Click(object sender, EventArgs e)
        {
            ClearErrors();

            if (HasErrors())
            {
                return;
            }

            StartNewProgressInfo(StringResources.SigningDocument);
            this.Cursor = Cursors.WaitCursor;
            bool signed = true;

            try
            {
                _digitalSignature.SignDocument();

                StartNewProgressInfo(StringResources.UploadingSignedFiles);

                _ticket = await Session.GetTikectAsync();

                UploadResult result = null;
                switch (_signatureIndex)
                {
                case 0:

                    result = await _dataService.UploadAsync(_ticket, _community.id, String.Empty,
                                                            _folder.id, String.Empty, String.Empty, _digitalSignature.DocumentId, false, String.Empty,
                                                            String.Empty, "DokuSignPrinterLocalCertificate", false, new System.IO.FileInfo(_digitalSignature.DocumentSigned));

                    break;

                case 1:
                    result = await _dataService.UploadAsync(_ticket, _community.id, String.Empty,
                                                            _folder.id, String.Empty, String.Empty, _digitalSignature.DocumentId, false,
                                                            _digitalSignature.BiometricSignature, sigOnline1.CertificatePass, "DokuSignPrinterSystemCertificate",
                                                            false, new System.IO.FileInfo(_digitalSignature.DocumentSigned));

                    break;

                case 2:
                    result = await _dataService.UploadAsync(_ticket, _community.id, String.Empty,
                                                            _folder.id, String.Empty, String.Empty, _digitalSignature.DocumentId, false,
                                                            String.Empty, String.Empty, "DokuSignPrinterBiometric", false,
                                                            new System.IO.FileInfo(_digitalSignature.DocumentSigned));

                    var sigPositions     = _digitalSignature.GetSignaturePositions();
                    var sigPosition      = (SignaturePosition)null;
                    var sigPositionsArgs = new List <DokuFlex.Windows.Common.Services.Data.SignaturePosition>(sigPositions.Count);

                    foreach (int key in sigPositions.Keys)
                    {
                        if (sigPositions.TryGetValue(key, out sigPosition))
                        {
                            sigPositionsArgs.Add(new DokuFlex.Windows.Common.Services.Data.SignaturePosition()
                            {
                                page = key,
                                x    = sigPosition.SigPosX,
                                y    = sigPosition.SigPosY
                            });
                        }
                    }

                    await _dataService.AddImageSignatureAsync(new FileInfo(_digitalSignature.BiometricSignature),
                                                              new FileInfo(_digitalSignature.SignatureImage), _ticket, result.nodeId, sigPositionsArgs.ToArray());

                    break;

                default:
                    break;
                }

                if (SelectedUsers.Count > 0)
                {
                    await _dataService.RequestDocumentSignature(_ticket, result.nodeId, SelectedUsers.Select(u => u.id).ToList());
                }

                try
                {
                    Directory.Delete(_documentDir, true);
                }
                catch (Exception ex)
                {
                    DokuFlex.Windows.Common.Log.LogFactory.CreateLog().LogError(ex);
                    //Silent exception
                }

                ConfigurationManager.Save(); //Save configuration changes.
            }
            catch (Exception ex)
            {
                DokuFlex.Windows.Common.Log.LogFactory.CreateLog().LogError(ex);
                signed = false;
            }
            finally
            {
                HideProgressInfo();
                this.Cursor = Cursors.Default;
            }
            if (signed)
            {
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }