예제 #1
0
        public static async Task <FileSystemResult <AmazonFileSystem> > Create(string fname, IOAuthProvider provider, Dictionary <string, object> settings, string pluginanme, string userauthorization = null)
        {
            AmazonFileSystem am = new AmazonFileSystem(provider);

            am.FS                  = am;
            am.OAuth.OAuthUrl      = AmazonOAuth;
            am.OAuth.EndPointUrl   = AmazonEndpoint;
            am.OAuth.OAuthLoginUrl = AmazonOAuthLogin;
            am.OAuth.DefaultScopes = AmazonScopes;
            bool userauth = !string.IsNullOrEmpty(userauthorization);

            if (userauth)
            {
                am.DeserializeAuth(userauthorization);
            }
            FileSystemResult r = await am.OAuth.Login(settings, pluginanme, userauth, false);

            if (!r.IsOk)
            {
                return(new FileSystemResult <AmazonFileSystem>(r.Error));
            }
            r = await am.CheckExpirations();

            if (!r.IsOk)
            {
                return(new FileSystemResult <AmazonFileSystem>(r.Error));
            }
            string url = AmazonRoot.FormatRest(am.OAuth.EndPoint.MetadataUrl);
            FileSystemResult <dynamic> fr = await am.List(url);

            if (!fr.IsOk)
            {
                return(new FileSystemResult <AmazonFileSystem>(fr.Error));
            }
            foreach (dynamic v in fr.Result)
            {
                if (v.kind == "FOLDER")
                {
                    am.SetData(JsonConvert.SerializeObject(v));
                    am.FsName = fname;
                    await am.PopulateAsync();

                    return(new FileSystemResult <AmazonFileSystem>(am));
                }
            }
            return(new FileSystemResult <AmazonFileSystem>("Amazon Root directory not found"));
        }
예제 #2
0
        // ReSharper disable once CyclomaticComplexity
        internal async Task <FileSystemResult <IFile> > InternalCreateFile(string name, string type, bool overwrite, AmazonObject parent, Stream readstream, CancellationToken token, IProgress <FileProgress> progress, Dictionary <string, object> properties)
        {
            if (readstream.Length == 0)
            {
                throw new ArgumentException("input stream must have length");
            }
            string url = AmazonUpload.FormatRest(FS.OAuth.EndPoint.ContentUrl, "?suppress=deduplication");

            Json.Metadata j = null;
            if (!overwrite)
            {
                if (properties == null)
                {
                    properties = new Dictionary <string, object>();
                }
                j                             = new Json.Metadata();
                j.version                     = 0;
                j.contentProperties           = new Json.ContentProperties();
                j.contentProperties.size      = readstream.Length;
                j.contentProperties.version   = 0;
                j.contentProperties.extension = Path.GetExtension(name);
                string n = Extensions.ContentFromExtension(j.contentProperties.extension);
                j.contentProperties.contentType = !string.IsNullOrEmpty(n) ? n : "application/octet-stream";
                if (properties.Any(a => a.Key.Equals("ModifiedDate", StringComparison.InvariantCultureIgnoreCase)))
                {
                    j.modifiedDate =
                        (DateTime)
                        properties.First(
                            a => a.Key.Equals("ModifiedDate", StringComparison.InvariantCultureIgnoreCase)).Value;
                }
                if (properties.Any(a => a.Key.Equals("CreatedDate", StringComparison.InvariantCultureIgnoreCase)))
                {
                    j.createdDate =
                        (DateTime)
                        properties.First(
                            a => a.Key.Equals("CreatedDate", StringComparison.InvariantCultureIgnoreCase)).Value;
                }
                if (properties.Any(a => a.Key.Equals("Application", StringComparison.InvariantCultureIgnoreCase)))
                {
                    j.createdBy =
                        (string)
                        properties.First(
                            a => a.Key.Equals("Application", StringComparison.InvariantCultureIgnoreCase)).Value;
                }
                else
                {
                    j.createdBy = "CloudFileSystem";
                }
                if (properties.Any(a => a.Key.Equals("MD5", StringComparison.InvariantCultureIgnoreCase)))
                {
                    j.contentProperties.md5 =
                        (string)
                        properties.First(a => a.Key.Equals("MD5", StringComparison.InvariantCultureIgnoreCase))
                        .Value;
                }
                j.description = j.name = name;
                j.isShared    = false;
                j.kind        = type;
                j.parents     = new List <string>();
                j.parents.Add(parent.Id);
            }
            HttpRequestMessage msg      = new HttpRequestMessage(overwrite ? HttpMethod.Put : HttpMethod.Post, url);
            string             boundary = "--" + Guid.NewGuid().ToString();

            msg.Headers.UserAgent.ParseAdd(FS.OAuth.UserAgent);
            MultipartFormDataContent ct = new MultipartFormDataContent(boundary);

            if (!overwrite)
            {
                string        meta = JsonConvert.SerializeObject(j);
                StringContent sc   = new StringContent(meta, Encoding.UTF8);
                ct.Add(sc, "metadata");
            }
            StreamContent ssc = new StreamContent(readstream);

            ct.Add(ssc, "file", name);
            msg.Content = ct;
            HttpClientHandler      handler         = new HttpClientHandler();
            ProgressMessageHandler progresshandler = new ProgressMessageHandler(handler);

            progresshandler.HttpSendProgress += (a, b) =>
            {
                FileProgress u = new FileProgress();
                u.Percentage   = b.ProgressPercentage;
                u.TotalSize    = b.TotalBytes ?? 0;
                u.TransferSize = b.BytesTransferred;
                progress.Report(u);
            };
            handler.AllowAutoRedirect      = true;
            handler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
            await FS.CheckExpirations();

            HttpClient          cl       = new HttpClient(progresshandler);
            HttpResponseMessage response = null;

            try
            {
                response = await cl.SendAsync(msg, token);

                if (response.StatusCode == HttpStatusCode.Created)
                {
                    string dd = await response.Content.ReadAsStringAsync();

                    string          parentpath = string.Empty;
                    AmazonDirectory dir        = parent as AmazonDirectory;
                    if (dir == null || !dir.IsRoot)
                    {
                        parentpath = FullName;
                    }
                    AmazonFile file = new AmazonFile(parentpath, FS)
                    {
                        Parent = dir
                    };
                    file.SetData(dd);
                    progress.Report(new FileProgress
                    {
                        Percentage   = 100,
                        TotalSize    = file.Size,
                        TransferSize = file.Size
                    });
                    return(new FileSystemResult <IFile>(file));
                }
                return(new FileSystemResult <IFile>("Http Error : " + response.StatusCode));
            }
            catch (Exception e)
            {
                return(new FileSystemResult <IFile>("Exception Error : " + e.Message));
            }
            finally
            {
                response?.Dispose();
                cl?.Dispose();
                handler?.Dispose();
                progresshandler?.Dispose();
                msg?.Dispose();
            }
        }