コード例 #1
0
ファイル: Copy.cs プロジェクト: zhangjianxi2008/ShareX
        // https://developers.copy.com/documentation#api-calls/filesystem - Create File or Directory
        // POST https://api.copy.com/rest/files/PATH/TO/FILE?overwrite=true
        public UploadResult UploadFile(Stream stream, string path, string fileName)
        {
            if (!OAuthInfo.CheckOAuth(AuthInfo))
            {
                Errors.Add("Copy login is required.");
                return(null);
            }

            string url = URLHelpers.CombineURL(URLFiles, URLHelpers.URLPathEncode(path));

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

            args.Add("overwrite", "true");

            string query = OAuthManager.GenerateQuery(url, args, HttpMethod.POST, AuthInfo);

            // There's a 1GB and 5 hour(max time for a single upload) limit to all uploads through the API.
            UploadResult result = UploadData(stream, query, fileName, "file", headers: APIHeaders);

            if (result.IsSuccess)
            {
                CopyUploadInfo content = JsonConvert.DeserializeObject <CopyUploadInfo>(result.Response);

                if (content != null && content.objects != null && content.objects.Length > 0)
                {
                    AllowReportProgress = false;
                    result.URL          = CreatePublicURL(content.objects[0].path, URLType);
                }
            }

            return(result);
        }
コード例 #2
0
ファイル: Dropbox.cs プロジェクト: thebaby/ShareX
        // https://www.dropbox.com/developers/core/docs#files_put
        public UploadResult UploadFile(Stream stream, string path, string fileName, bool createShareableURL = false, DropboxURLType urlType = DropboxURLType.Default)
        {
            if (!OAuth2Info.CheckOAuth(AuthInfo))
            {
                Errors.Add("Dropbox login is required.");
                return(null);
            }

            string url = URLHelpers.CombineURL(URLFiles, URLHelpers.URLPathEncode(path));

            // There's a 150MB limit to all uploads through the API.
            UploadResult result = UploadData(stream, url, fileName, headers: GetAuthHeaders());

            if (result.IsSuccess)
            {
                DropboxContentInfo content = JsonConvert.DeserializeObject <DropboxContentInfo>(result.Response);

                if (content != null)
                {
                    if (createShareableURL)
                    {
                        AllowReportProgress = false;
                        result.URL          = CreateShareableLink(content.Path, urlType);
                    }
                    else
                    {
                        result.URL = GetPublicURL(content.Path);
                    }
                }
            }

            return(result);
        }
コード例 #3
0
        public string CreateShareableLinkAPIv1(string path, DropboxURLType urlType)
        {
            if (!string.IsNullOrEmpty(path) && OAuth2Info.CheckOAuth(AuthInfo))
            {
                string url = URLHelpers.CombineURL(URLShares, URLHelpers.URLPathEncode(path));

                Dictionary <string, string> args = new Dictionary <string, string>();
                args.Add("short_url", urlType == DropboxURLType.Shortened ? "true" : "false");

                string response = SendRequest(HttpMethod.POST, url, args, GetAuthHeaders());

                if (!string.IsNullOrEmpty(response))
                {
                    DropboxShares shares = JsonConvert.DeserializeObject <DropboxShares>(response);

                    if (urlType == DropboxURLType.Direct)
                    {
                        return(GetDirectShareableURL(shares.URL));
                    }
                    else
                    {
                        return(shares.URL);
                    }
                }
            }

            return(null);
        }
コード例 #4
0
ファイル: AmazonS3.cs プロジェクト: thebaby/ShareX
        private string GetObjectURL(string objectName)
        {
            objectName = objectName.Trim('/');
            objectName = URLHelpers.URLPathEncode(objectName);

            string url = string.Empty;

            if (S3Settings.UseCustomCNAME)
            {
                if (!string.IsNullOrEmpty(S3Settings.CustomDomain))
                {
                    url = URLHelpers.CombineURL(S3Settings.CustomDomain, objectName);
                }
                else
                {
                    url = URLHelpers.CombineURL(S3Settings.Bucket, objectName);
                }
            }
            else
            {
                url = URLHelpers.CombineURL(GetEndpoint(), objectName);
            }

            url = URLHelpers.FixPrefix(url);

            return(url);
        }
コード例 #5
0
ファイル: Copy.cs プロジェクト: zhangjianxi2008/ShareX
        public string CreatePublicURL(string path, CopyURLType urlType = CopyURLType.Default)
        {
            path = path.Trim('/');

            string url = URLHelpers.CombineURL(URLLinks, URLHelpers.URLPathEncode(path));

            string query = OAuthManager.GenerateQuery(url, null, HttpMethod.POST, AuthInfo);

            CopyLinkRequest publicLink = new CopyLinkRequest();

            publicLink.@public = true;
            publicLink.name    = "ShareX";
            publicLink.paths   = new string[] { path };

            string content = JsonConvert.SerializeObject(publicLink);

            string response = SendRequest(HttpMethod.POST, query, content, headers: APIHeaders);

            if (!string.IsNullOrEmpty(response))
            {
                CopyLinksInfo link = JsonConvert.DeserializeObject <CopyLinksInfo>(response);

                return(GetLinkURL(link, path, urlType));
            }

            return("");
        }
コード例 #6
0
ファイル: Dropbox.cs プロジェクト: thebaby/ShareX
        // https://www.dropbox.com/developers/core/docs#files-GET
        public bool DownloadFile(string path, Stream downloadStream)
        {
            if (!string.IsNullOrEmpty(path) && OAuth2Info.CheckOAuth(AuthInfo))
            {
                string url = URLHelpers.CombineURL(URLFiles, URLHelpers.URLPathEncode(path));
                return(SendRequest(HttpMethod.GET, downloadStream, url, headers: GetAuthHeaders()));
            }

            return(false);
        }
コード例 #7
0
ファイル: Copy.cs プロジェクト: zhangjianxi2008/ShareX
        // https://developers.copy.com/documentation#api-calls/filesystem - Download Raw File Conents
        // GET https://api.copy.com/rest/files/PATH/TO/FILE
        public bool DownloadFile(string path, Stream downloadStream)
        {
            if (!string.IsNullOrEmpty(path) && OAuthInfo.CheckOAuth(AuthInfo))
            {
                string url   = URLHelpers.CombineURL(URLFiles, URLHelpers.URLPathEncode(path));
                string query = OAuthManager.GenerateQuery(url, null, HttpMethod.GET, AuthInfo);
                return(SendRequest(HttpMethod.GET, downloadStream, query));
            }

            return(false);
        }
コード例 #8
0
        public string GetUriPath(string filename)
        {
            if (string.IsNullOrEmpty(LocalhostRoot))
            {
                return(string.Empty);
            }

            if (HttpHomePathNoExtension)
            {
                filename = Path.GetFileNameWithoutExtension(filename);
            }

            filename = URLHelpers.URLEncode(filename);

            string subFolderPath = GetSubFolderPath();

            subFolderPath = URLHelpers.URLPathEncode(subFolderPath);

            string httpHomePath = GetHttpHomePath();

            string path;

            if (string.IsNullOrEmpty(httpHomePath))
            {
                RemoteProtocol = BrowserProtocol.file;
                path           = LocalUri.Replace("file://", "");
            }
            else
            {
                path = URLHelpers.URLPathEncode(httpHomePath);
            }

            if (Port != 80)
            {
                path = string.Format("{0}:{1}", path, Port);
            }

            if (HttpHomePathAutoAddSubFolderPath)
            {
                path = URLHelpers.CombineURL(path, subFolderPath);
            }

            path = URLHelpers.CombineURL(path, filename);

            string remoteProtocol = RemoteProtocol.GetDescription();

            if (!path.StartsWith(remoteProtocol))
            {
                path = remoteProtocol + path;
            }

            return(path);
        }
コード例 #9
0
ファイル: Dropbox.cs プロジェクト: thebaby/ShareX
        public static string GetPublicURL(long userID, string path)
        {
            if (!string.IsNullOrEmpty(path))
            {
                path = path.Trim('/');

                if (path.StartsWith("Public/", StringComparison.InvariantCultureIgnoreCase))
                {
                    path = URLHelpers.URLPathEncode((path.Substring(7)));
                    return(URLHelpers.CombineURL(URLPublicDirect, userID.ToString(), path));
                }
            }

            return("Upload path is private. Use \"Public\" folder to get public URL.");
        }
コード例 #10
0
        public static string GetPublicURL(string userID, string path)
        {
            if (!string.IsNullOrEmpty(path))
            {
                path = path.Trim('/');

                string find = "Public/";

                if (path.StartsWith(find, StringComparison.InvariantCultureIgnoreCase))
                {
                    path = path.Substring(find.Length);
                    path = URLHelpers.URLPathEncode(path);
                    return(URLHelpers.CombineURL(URLPublicDirect, userID, path));
                }
            }

            return("Upload path is private. Use \"Public\" folder or shareable URL option to get URL.");
        }
コード例 #11
0
        public string GenerateURL(string uploadPath)
        {
            if (string.IsNullOrEmpty(Bucket))
            {
                return("");
            }

            if (string.IsNullOrEmpty(Domain))
            {
                Domain = URLHelpers.CombineURL("storage.googleapis.com", Bucket);
            }

            uploadPath = URLHelpers.URLPathEncode(uploadPath);

            string url = URLHelpers.CombineURL(Domain, uploadPath);

            return(URLHelpers.FixPrefix(url, "https://"));
        }
コード例 #12
0
ファイル: Copy.cs プロジェクト: zhangjianxi2008/ShareX
        // https://developers.copy.com/documentation#api-calls/filesystem - Read Root Directory
        // GET https://api.copy.com/rest/meta/copy
        public CopyContentInfo GetMetadata(string path)
        {
            CopyContentInfo contentInfo = null;

            if (OAuthInfo.CheckOAuth(AuthInfo))
            {
                string url = URLHelpers.CombineURL(URLMetaData, URLHelpers.URLPathEncode(path));

                string query = OAuthManager.GenerateQuery(url, null, HttpMethod.GET, AuthInfo);

                string response = SendRequest(HttpMethod.GET, query);

                if (!string.IsNullOrEmpty(response))
                {
                    contentInfo = JsonConvert.DeserializeObject <CopyContentInfo>(response);
                }
            }

            return(contentInfo);
        }
コード例 #13
0
ファイル: Dropbox.cs プロジェクト: thebaby/ShareX
        // https://www.dropbox.com/developers/core/docs#metadata
        public DropboxContentInfo GetMetadata(string path, bool list)
        {
            DropboxContentInfo contentInfo = null;

            if (OAuth2Info.CheckOAuth(AuthInfo))
            {
                string url = URLHelpers.CombineURL(URLMetaData, URLHelpers.URLPathEncode(path));

                Dictionary <string, string> args = new Dictionary <string, string>();
                args.Add("list", list ? "true" : "false");

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

                if (!string.IsNullOrEmpty(response))
                {
                    contentInfo = JsonConvert.DeserializeObject <DropboxContentInfo>(response);
                }
            }

            return(contentInfo);
        }
コード例 #14
0
        public string GenerateURL(string uploadPath)
        {
            if (!string.IsNullOrEmpty(Settings.Endpoint) && !string.IsNullOrEmpty(Settings.Bucket))
            {
                uploadPath = URLHelpers.URLPathEncode(uploadPath);

                string url;

                if (Settings.UseCustomCNAME && !string.IsNullOrEmpty(Settings.CustomDomain))
                {
                    url = URLHelpers.CombineURL(Settings.CustomDomain, uploadPath);
                }
                else
                {
                    url = URLHelpers.CombineURL(Settings.Endpoint, Settings.Bucket, uploadPath);
                }

                return(URLHelpers.FixPrefix(url, "https://"));
            }

            return("");
        }
コード例 #15
0
ファイル: Dropbox.cs プロジェクト: thebaby/ShareX
        // https://www.dropbox.com/developers/core/docs#shares
        public string CreateShareableLink(string path, DropboxURLType urlType)
        {
            if (!string.IsNullOrEmpty(path) && OAuth2Info.CheckOAuth(AuthInfo))
            {
                string url = URLHelpers.CombineURL(URLShares, URLHelpers.URLPathEncode(path));

                Dictionary <string, string> args = new Dictionary <string, string>();
                args.Add("short_url", urlType == DropboxURLType.Shortened ? "true" : "false");

                string response = SendRequest(HttpMethod.POST, url, args, GetAuthHeaders());

                if (!string.IsNullOrEmpty(response))
                {
                    DropboxShares shares = JsonConvert.DeserializeObject <DropboxShares>(response);

                    if (urlType == DropboxURLType.Direct)
                    {
                        Match match = Regex.Match(shares.URL, @"https?://(?:www\.)?dropbox.com/s/(?<path>\w+/.+)");
                        if (match.Success)
                        {
                            string urlPath = match.Groups["path"].Value;
                            if (!string.IsNullOrEmpty(urlPath))
                            {
                                return(URLHelpers.CombineURL(URLShareDirect, urlPath));
                            }
                        }
                    }
                    else
                    {
                        return(shares.URL);
                    }
                }
            }

            return(null);
        }
コード例 #16
0
        public override UploadResult Upload(Stream stream, string fileName)
        {
            bool forcePathStyle = Settings.UsePathStyle;

            if (!forcePathStyle && Settings.Bucket.Contains("."))
            {
                forcePathStyle = true;
            }

            string endpoint            = URLHelpers.RemovePrefixes(Settings.Endpoint);
            string host                = forcePathStyle ? endpoint : $"{Settings.Bucket}.{endpoint}";
            string algorithm           = "AWS4-HMAC-SHA256";
            string credentialDate      = DateTime.UtcNow.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
            string region              = GetRegion();
            string scope               = URLHelpers.CombineURL(credentialDate, region, "s3", "aws4_request");
            string credential          = URLHelpers.CombineURL(Settings.AccessKeyID, scope);
            string longDate            = DateTime.UtcNow.ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture);
            string expiresTotalSeconds = ((long)TimeSpan.FromHours(1).TotalSeconds).ToString();
            string contentType         = Helpers.GetMimeType(fileName);

            NameValueCollection headers = new NameValueCollection();

            headers["content-type"] = contentType;
            headers["host"]         = host;
            if (Settings.SetPublicACL)
            {
                headers["x-amz-acl"] = "public-read";
            }
            headers["x-amz-storage-class"] = Settings.StorageClass.ToString();

            string signedHeaders = GetSignedHeaders(headers);

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

            args.Add("X-Amz-Algorithm", algorithm);
            args.Add("X-Amz-Credential", credential);
            args.Add("X-Amz-Date", longDate);
            args.Add("X-Amz-Expires", expiresTotalSeconds);
            args.Add("X-Amz-SignedHeaders", signedHeaders);

            string uploadPath = GetUploadPath(fileName);

            string canonicalURI = uploadPath;

            if (forcePathStyle)
            {
                canonicalURI = URLHelpers.CombineURL(Settings.Bucket, canonicalURI);
            }
            canonicalURI = URLHelpers.AddSlash(canonicalURI, SlashType.Prefix);
            canonicalURI = URLHelpers.URLPathEncode(canonicalURI);

            string canonicalQueryString = URLHelpers.CreateQuery(args, true);
            string canonicalHeaders     = CreateCanonicalHeaders(headers);

            string canonicalRequest = "PUT" + "\n" +
                                      canonicalURI + "\n" +
                                      canonicalQueryString + "\n" +
                                      canonicalHeaders + "\n" +
                                      signedHeaders + "\n" +
                                      "UNSIGNED-PAYLOAD";

            string stringToSign = algorithm + "\n" +
                                  longDate + "\n" +
                                  scope + "\n" +
                                  Helpers.BytesToHex(Helpers.ComputeSHA256(canonicalRequest));

            byte[] dateKey              = Helpers.ComputeHMACSHA256(credentialDate, "AWS4" + Settings.SecretAccessKey);
            byte[] dateRegionKey        = Helpers.ComputeHMACSHA256(region, dateKey);
            byte[] dateRegionServiceKey = Helpers.ComputeHMACSHA256("s3", dateRegionKey);
            byte[] signingKey           = Helpers.ComputeHMACSHA256("aws4_request", dateRegionServiceKey);
            string signature            = Helpers.BytesToHex(Helpers.ComputeHMACSHA256(stringToSign, signingKey));

            args.Add("X-Amz-Signature", signature);

            headers.Remove("content-type");
            headers.Remove("host");

            string url = URLHelpers.CombineURL(host, canonicalURI);

            url = URLHelpers.CreateQuery(url, args, true);
            url = URLHelpers.ForcePrefix(url, "https://");

            NameValueCollection responseHeaders = SendRequestGetHeaders(HttpMethod.PUT, url, stream, contentType, null, headers);

            if (responseHeaders == null || responseHeaders.Count == 0)
            {
                Errors.Add("Upload to Amazon S3 failed. Check your access credentials.");
                return(null);
            }

            if (responseHeaders["ETag"] == null)
            {
                Errors.Add("Upload to Amazon S3 failed.");
                return(null);
            }

            return(new UploadResult
            {
                IsSuccess = true,
                URL = GenerateURL(uploadPath)
            });
        }
コード例 #17
0
ファイル: AmazonS3.cs プロジェクト: ralic/ShareX
        public override UploadResult Upload(Stream stream, string fileName)
        {
            bool isPathStyleRequest = Settings.UsePathStyle;

            if (!isPathStyleRequest && Settings.Bucket.Contains("."))
            {
                isPathStyleRequest = true;
            }

            string endpoint       = URLHelpers.RemovePrefixes(Settings.Endpoint);
            string host           = isPathStyleRequest ? endpoint : $"{Settings.Bucket}.{endpoint}";
            string algorithm      = "AWS4-HMAC-SHA256";
            string credentialDate = DateTime.UtcNow.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
            string region         = GetRegion();
            string scope          = URLHelpers.CombineURL(credentialDate, region, "s3", "aws4_request");
            string credential     = URLHelpers.CombineURL(Settings.AccessKeyID, scope);
            string timeStamp      = DateTime.UtcNow.ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture);
            string contentType    = Helpers.GetMimeType(fileName);
            string uploadPath     = GetUploadPath(fileName);
            string hashedPayload  = "UNSIGNED-PAYLOAD";

            NameValueCollection headers = new NameValueCollection();

            headers["host"]                 = host;
            headers["content-type"]         = contentType;
            headers["x-amz-date"]           = timeStamp;
            headers["x-amz-content-sha256"] = hashedPayload;
            headers["x-amz-storage-class"]  = Settings.StorageClass.ToString();
            if (Settings.SetPublicACL)
            {
                headers["x-amz-acl"] = "public-read";
            }

            string canonicalURI = uploadPath;

            if (isPathStyleRequest)
            {
                canonicalURI = URLHelpers.CombineURL(Settings.Bucket, canonicalURI);
            }
            canonicalURI = URLHelpers.AddSlash(canonicalURI, SlashType.Prefix);
            canonicalURI = URLHelpers.URLPathEncode(canonicalURI);
            string canonicalQueryString = "";
            string canonicalHeaders     = CreateCanonicalHeaders(headers);
            string signedHeaders        = GetSignedHeaders(headers);

            string canonicalRequest = "PUT" + "\n" +
                                      canonicalURI + "\n" +
                                      canonicalQueryString + "\n" +
                                      canonicalHeaders + "\n" +
                                      signedHeaders + "\n" +
                                      hashedPayload;

            string stringToSign = algorithm + "\n" +
                                  timeStamp + "\n" +
                                  scope + "\n" +
                                  Helpers.BytesToHex(Helpers.ComputeSHA256(canonicalRequest));

            byte[] dateKey              = Helpers.ComputeHMACSHA256(credentialDate, "AWS4" + Settings.SecretAccessKey);
            byte[] dateRegionKey        = Helpers.ComputeHMACSHA256(region, dateKey);
            byte[] dateRegionServiceKey = Helpers.ComputeHMACSHA256("s3", dateRegionKey);
            byte[] signingKey           = Helpers.ComputeHMACSHA256("aws4_request", dateRegionServiceKey);

            string signature = Helpers.BytesToHex(Helpers.ComputeHMACSHA256(stringToSign, signingKey));

            headers["Authorization"] = algorithm + " " +
                                       "Credential=" + credential + "," +
                                       "SignedHeaders=" + signedHeaders + "," +
                                       "Signature=" + signature;

            headers.Remove("host");
            headers.Remove("content-type");

            string url = URLHelpers.CombineURL(host, canonicalURI);

            url = URLHelpers.ForcePrefix(url, "https://");

            NameValueCollection responseHeaders = SendRequestGetHeaders(HttpMethod.PUT, url, stream, contentType, null, headers);

            if (responseHeaders == null || responseHeaders.Count == 0 || responseHeaders["ETag"] == null)
            {
                Errors.Add("Upload to Amazon S3 failed.");
                return(null);
            }

            return(new UploadResult
            {
                IsSuccess = true,
                URL = GenerateURL(uploadPath)
            });
        }
コード例 #18
0
ファイル: FTPAccount.cs プロジェクト: SolidX/ShareX
        public string GetUriPath(string filename, string subFolderPath = null)
        {
            if (string.IsNullOrEmpty(Host))
            {
                return(string.Empty);
            }

            if (HttpHomePathNoExtension)
            {
                filename = Path.GetFileNameWithoutExtension(filename);
            }

            filename = URLHelpers.URLEncode(filename);

            if (subFolderPath == null)
            {
                subFolderPath = GetSubFolderPath();
            }

            subFolderPath = URLHelpers.URLPathEncode(subFolderPath);

            UriBuilder httpHomeUri;
            var        httpHomePath = GetHttpHomePath();

            if (string.IsNullOrEmpty(httpHomePath))
            {
                var host = Host;

                if (host.StartsWith("ftp."))
                {
                    host = host.Substring(4);
                }

                httpHomeUri      = new UriBuilder(URLHelpers.CombineURL(host, subFolderPath, filename));
                httpHomeUri.Port = -1; //Since httpHomePath is not set, it's safe to erase UriBuilder's assumed port number
            }
            else
            {
                //Parse HttpHomePath in to host, port, path and query components
                var firstSlash      = httpHomePath.IndexOf('/');
                var httpHome        = firstSlash >= 0 ? httpHomePath.Substring(0, firstSlash) : httpHomePath;
                var portSpecifiedAt = httpHome.LastIndexOf(':');

                var httpHomeHost         = portSpecifiedAt >= 0 ? httpHome.Substring(0, portSpecifiedAt) : httpHome;
                var httpHomePort         = -1;
                var httpHomePathAndQuery = firstSlash >= 0 ? httpHomePath.Substring(firstSlash + 1) : "";
                var querySpecifiedAt     = httpHomePathAndQuery.LastIndexOf('?');
                var httpHomeDir          = querySpecifiedAt >= 0 ? httpHomePathAndQuery.Substring(0, querySpecifiedAt) : httpHomePathAndQuery;
                var httpHomeQuery        = querySpecifiedAt >= 0 ? httpHomePathAndQuery.Substring(querySpecifiedAt + 1) : "";

                if (portSpecifiedAt >= 0)
                {
                    int.TryParse(httpHome.Substring(portSpecifiedAt + 1), out httpHomePort);
                }

                //Build URI
                httpHomeUri = new UriBuilder {
                    Host = httpHomeHost, Path = httpHomeDir, Query = httpHomeQuery
                };
                if (portSpecifiedAt >= 0)
                {
                    httpHomeUri.Port = httpHomePort;
                }

                if (httpHomeUri.Query.EndsWith("="))
                {
                    //Setting URIBuilder.Query automatically prepends a ? so we must trim it first.
                    if (HttpHomePathAutoAddSubFolderPath)
                    {
                        httpHomeUri.Query = URLHelpers.CombineURL(httpHomeUri.Query.Substring(1), subFolderPath, filename);
                    }
                    else
                    {
                        httpHomeUri.Query = httpHomeUri.Query.Substring(1) + filename;
                    }
                }
                else
                {
                    if (HttpHomePathAutoAddSubFolderPath)
                    {
                        httpHomeUri.Path = URLHelpers.CombineURL(httpHomeUri.Path, subFolderPath);
                    }

                    httpHomeUri.Path = URLHelpers.CombineURL(httpHomeUri.Path, filename);
                }
            }

            httpHomeUri.Scheme = BrowserProtocol.GetDescription();
            return(Uri.EscapeUriString(httpHomeUri.Uri.ToString()));
        }
コード例 #19
0
ファイル: AmazonS3.cs プロジェクト: Gigabait/ShareX
        public override UploadResult Upload(Stream stream, string fileName)
        {
            string hostname            = URLHelpers.RemovePrefixes(Settings.RegionHostname);
            string host                = $"{Settings.Bucket}.{hostname}";
            string algorithm           = "AWS4-HMAC-SHA256";
            string credentialDate      = DateTime.UtcNow.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
            string scope               = $"{credentialDate}/{Settings.RegionIdentifier}/s3/aws4_request";
            string credential          = $"{Settings.AccessKeyID}/{scope}";
            string longDate            = DateTime.UtcNow.ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture);
            string expiresTotalSeconds = ((long)TimeSpan.FromHours(1).TotalSeconds).ToString();
            string contentType         = Helpers.GetMimeType(fileName);

            NameValueCollection headers = new NameValueCollection();

            headers["content-type"]        = contentType;
            headers["host"]                = host;
            headers["x-amz-acl"]           = "public-read";
            headers["x-amz-storage-class"] = Settings.UseReducedRedundancyStorage ? "REDUCED_REDUNDANCY" : "STANDARD";

            string signedHeaders = GetSignedHeaders(headers);

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

            args.Add("X-Amz-Algorithm", algorithm);
            args.Add("X-Amz-Credential", credential);
            args.Add("X-Amz-Date", longDate);
            args.Add("X-Amz-Expires", expiresTotalSeconds);
            args.Add("X-Amz-SignedHeaders", signedHeaders);

            string uploadPath   = GetUploadPath(fileName);
            string canonicalURI = URLHelpers.AddSlash(uploadPath, SlashType.Prefix);

            canonicalURI = URLHelpers.URLPathEncode(canonicalURI);

            string canonicalQueryString = CreateQueryString(args);
            string canonicalHeaders     = CreateCanonicalHeaders(headers);

            string canonicalRequest = "PUT" + "\n" +
                                      canonicalURI + "\n" +
                                      canonicalQueryString + "\n" +
                                      canonicalHeaders + "\n" +
                                      signedHeaders + "\n" +
                                      "UNSIGNED-PAYLOAD";

            string stringToSign = algorithm + "\n" +
                                  longDate + "\n" +
                                  scope + "\n" +
                                  BytesToHex(ComputeHash(canonicalRequest));

            byte[] secretKey            = Encoding.UTF8.GetBytes("AWS4" + Settings.SecretAccessKey);
            byte[] dateKey              = ComputeHMAC(Encoding.UTF8.GetBytes(credentialDate), secretKey);
            byte[] dateRegionKey        = ComputeHMAC(Encoding.UTF8.GetBytes(Settings.RegionIdentifier), dateKey);
            byte[] dateRegionServiceKey = ComputeHMAC(Encoding.UTF8.GetBytes("s3"), dateRegionKey);
            byte[] signingKey           = ComputeHMAC(Encoding.UTF8.GetBytes("aws4_request"), dateRegionServiceKey);
            string signature            = BytesToHex(ComputeHMAC(Encoding.UTF8.GetBytes(stringToSign), signingKey));

            args.Add("X-Amz-Signature", signature);

            headers.Remove("content-type");
            headers.Remove("host");

            string url = URLHelpers.CombineURL(host, canonicalURI) + "?" + CreateQueryString(args);

            url = URLHelpers.ForcePrefix(url, "https://");

            NameValueCollection responseHeaders = SendRequestGetHeaders(HttpMethod.PUT, url, stream, contentType, null, headers);

            if (responseHeaders == null || responseHeaders.Count == 0)
            {
                Errors.Add("Upload to Amazon S3 failed. Check your access credentials.");
                return(null);
            }

            if (responseHeaders["ETag"] == null)
            {
                Errors.Add("Upload to Amazon S3 failed.");
                return(null);
            }

            return(new UploadResult
            {
                IsSuccess = true,
                URL = GenerateURL(fileName)
            });
        }
コード例 #20
0
        public string GetUriPath(string filename, string subFolderPath = null)
        {
            if (string.IsNullOrEmpty(Host))
            {
                return(string.Empty);
            }

            if (HttpHomePathNoExtension)
            {
                filename = Path.GetFileNameWithoutExtension(filename);
            }

            filename = URLHelpers.URLEncode(filename);

            if (subFolderPath == null)
            {
                subFolderPath = GetSubFolderPath();
            }

            subFolderPath = URLHelpers.URLPathEncode(subFolderPath);

            string httpHomePath = GetHttpHomePath();

            httpHomePath = URLHelpers.URLPathEncode(httpHomePath);

            string path;

            if (string.IsNullOrEmpty(httpHomePath))
            {
                string host = Host;

                if (host.StartsWith("ftp."))
                {
                    host = host.Substring(4);
                }

                path = URLHelpers.CombineURL(host, subFolderPath, filename);
            }
            else
            {
                if (HttpHomePathAutoAddSubFolderPath)
                {
                    path = URLHelpers.CombineURL(httpHomePath, subFolderPath);
                }
                else
                {
                    path = httpHomePath;
                }

                if (path.EndsWith("="))
                {
                    path += filename;
                }
                else
                {
                    path = URLHelpers.CombineURL(path, filename);
                }
            }

            string browserProtocol = BrowserProtocol.GetDescription();

            if (!path.StartsWith(browserProtocol))
            {
                path = browserProtocol + path;
            }

            return(path);
        }
コード例 #21
0
ファイル: FTPAccount.cs プロジェクト: Quantumplation/ShareX
        public string GetUriPath(string filename, string subFolderPath = null)
        {
            if (string.IsNullOrEmpty(Host))
            {
                return(string.Empty);
            }

            if (HttpHomePathNoExtension)
            {
                filename = Path.GetFileNameWithoutExtension(filename);
            }

            filename = URLHelpers.URLEncode(filename);

            if (subFolderPath == null)
            {
                subFolderPath = GetSubFolderPath();
            }

            subFolderPath = URLHelpers.URLPathEncode(subFolderPath);

            UriBuilder httpHomeUri;
            var        httpHomePath = GetHttpHomePath();

            if (string.IsNullOrEmpty(httpHomePath))
            {
                var host = Host;

                if (host.StartsWith("ftp."))
                {
                    host = host.Substring(4);
                }

                httpHomeUri = new UriBuilder(URLHelpers.CombineURL(host, subFolderPath, filename));
            }
            else
            {
                //Parse HttpHomePath in to host, port and path components
                var firstSlash      = httpHomePath.IndexOf('/');
                var httpHome        = firstSlash >= 0 ? httpHomePath.Substring(0, firstSlash) : httpHomePath;
                var portSpecifiedAt = httpHome.LastIndexOf(':');

                var httpHomeHost = portSpecifiedAt >= 0 ? httpHome.Substring(0, portSpecifiedAt) : httpHome;
                var httpHomePort = -1;
                var httpHomeDir  = httpHomePath.Substring(firstSlash + 1);

                if (portSpecifiedAt >= 0)
                {
                    int.TryParse(httpHome.Substring(portSpecifiedAt + 1), out httpHomePort);
                }

                //Build URI
                httpHomeUri = new UriBuilder {
                    Host = httpHomeHost, Path = httpHomeDir
                };
                if (portSpecifiedAt >= 0)
                {
                    httpHomeUri.Port = httpHomePort;
                }

                if (HttpHomePathAutoAddSubFolderPath)
                {
                    httpHomeUri.Path = URLHelpers.CombineURL(httpHomeUri.Path, subFolderPath);
                }

                if (httpHomeUri.Query.EndsWith("="))
                {
                    httpHomeUri.Query += filename;
                }
                else
                {
                    httpHomeUri.Path = URLHelpers.CombineURL(httpHomeUri.Path, filename);
                }
            }

            httpHomeUri.Scheme = BrowserProtocol.GetDescription();
            return(httpHomeUri.Uri.ToString());
        }