示例#1
0
        public async Task<DFileInfo> CreateFolderAsync(DFileInfo destinationFolder, string name)
        {
            var dest = (SkydriveFileInfo)destinationFolder;
            var url = string.Format(SkydriveConfig.FileInfoUrlTemplate, dest.Id);
            var data = "{ \"name\" : \"" + name + "\" }";
            string response = await dataToServer(data, url, "POST").ConfigureAwait(false);

            var newFolder = new SkydriveFileInfo() { Parent = destinationFolder };
            setupFileWithMetadata(newFolder, JToken.Parse(response));
            return newFolder;
        }
示例#2
0
        public async Task<Stream> GetDownloadStreamAsync(DFileInfo file)
        {
            if (file.IsDirectory)
                throw new NotSupportedException("Downloading a folder is not supported.");

            var dFile = (DropboxFileInfo)file;
            var url = new StringBuilder(DropboxConfig.DownloadUrl);
            url.Append(DropboxConfig.AccessType);
            url.Append(dFile.Path);
            ParamUrl queryUrl = new ParamUrl(url.ToString());

            try
            {
                var signedUrl = await signAsync(queryUrl).ConfigureAwait(false);
                var request = (HttpWebRequest)WebRequest.Create(signedUrl);
                request.Method = WebRequestMethods.Http.Get;
                var response = await request.GetResponseAsync().ConfigureAwait(false);
                return response.GetResponseStream();
            }
            catch (WebException e)
            {
                throw parseException(e);
            }
        }
示例#3
0
 public async Task NavigatedToAsync(DFileInfo file)
 {
     if (!file.IsDirectory) return;
     var contents = await getFolderContentsMetadata((SkydriveFileInfo)file).ConfigureAwait(false);
     file.Contents.Clear();
     foreach (JToken entry in contents)
     {
         var newFile = new SkydriveFileInfo() { Parent = file };
         setupFileWithMetadata(newFile, entry);
         file.Contents.Add(newFile.Id, newFile);
     }
 }
示例#4
0
 /// <summary>
 /// Copies this file or a folder to the different location.
 /// </summary>
 /// <param name="destinationFolder">The new location of the file.</param>
 /// <returns>File info of the copied file.</returns>
 public Task<DFileInfo> CopyAsync(DFileInfo destinationFolder)
 {
     return localFileOperationAsync(destinationFolder, false);
 }
示例#5
0
        public async Task DeleteAsync(DFileInfo file)
        {
            var dFile = (DropboxFileInfo)file;
            var url = new ParamUrl(DropboxConfig.DeleteUrl);
            url.Add("root", DropboxConfig.AccessType);
            url.Add("path", percentEncoding(dFile.Path));

            await queryServer(url).ConfigureAwait(false);

            file.Parent.Contents.Remove(file.Name.ToLowerInvariant());
            file = null;
        }
示例#6
0
        public async Task<DFileInfo> RenameAsync(DFileInfo file, string newName)
        {
            var sFile = (SkydriveFileInfo)file;

            var url = string.Format(SkydriveConfig.FileInfoUrlTemplate, sFile.Id);
            var data = "{ \"name\": \"" + newName + "\" }";

            var response = await dataToServer(data, url, "PUT").ConfigureAwait(false);
            var metadata = JToken.Parse(response);

            setupFileWithMetadata(sFile, metadata);
            return sFile;
        }
示例#7
0
 public Task<DFileInfo> CopyAsync(DFileInfo file, DFileInfo destinationFolder)
 {
     return fileOperation((SkydriveFileInfo)file, (SkydriveFileInfo)destinationFolder, "COPY");
 }
示例#8
0
        public async Task<DFileInfo> CreateFolderAsync(DFileInfo destinationFolder, string name)
        {
            string nameKey = name.ToLowerInvariant();
            if (destinationFolder.Contents.ContainsKey(nameKey))
                throw new FileConflictException("Entry with name specified is already present.");

            var dParent = (DropboxFileInfo)destinationFolder;
            string path = concatenatePath(dParent.Path, name);

            var url = new ParamUrl(DropboxConfig.CreateFolderUrl);
            url.Add("root", DropboxConfig.AccessType);
            url.Add("path", path);

            var response = await queryServer(url).ConfigureAwait(false);
            var metadata = JObject.Parse(response);

            var newFolder = new DropboxFileInfo() { Parent = dParent };
            setupFileWithMetadata(newFolder, metadata);

            dParent.Contents.Add(nameKey, newFolder);
            return newFolder;
        }
示例#9
0
        public async Task<DFileInfo> UploadFileAsync(DFileInfo destinationFolder, string name, Stream stream, 
            CancellationToken cancellationToken, IProgress<int> progress, long fileSize)
        {
            var dDestFolder = (DropboxFileInfo)destinationFolder;
            string uploadId = null;

            using (stream)
            {
                if (progress != null) progress.Report(0);
                var buffer = new byte[DropboxConfig.ChunkSize];
                long totalUploaded = 0, offset = 0;

                // Some data is read from the buffer until it is full and we 
                // attempt to push it to the server until it acknowledges all of it.
                while (true)
                {
                    int bytesRead = 0, bytesReadThisTime = 0;
                    while (bytesRead < buffer.Length)
                    {
                        bytesReadThisTime =
                            await stream.ReadAsync(buffer, bytesRead, buffer.Length - bytesRead).ConfigureAwait(false);
                        bytesRead += bytesReadThisTime;
                        if (bytesReadThisTime == 0) break;
                    }

                    if (bytesRead == 0) break;

                    int relativeOffset = 0;
                    // relativeOffset shows how many bytes server already accepted.
                    while (relativeOffset < bytesRead)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        var url = new ParamUrl(DropboxConfig.UploadUrl);
                        url.Add("offset", (offset + relativeOffset).ToString());
                        if (uploadId != null) url.Add("upload_id", uploadId);

                        var signedUrl = await signAsync(url).ConfigureAwait(false);
                        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(signedUrl);
                        request.Method = WebRequestMethods.Http.Put;
                        request.ContentLength = bytesRead - relativeOffset;

                        using (var requestStream = await request.GetRequestStreamAsync().ConfigureAwait(false))
                        {
                            requestStream.Write(buffer, relativeOffset, bytesRead - relativeOffset);
                        }

                        JToken response;
                        try
                        {
                            var webResponse = await request.GetResponseAsync().ConfigureAwait(false);
                            StreamReader reader = new StreamReader(webResponse.GetResponseStream());
                            var jsonResult = reader.ReadToEnd();
                            reader.Close();
                            response = JToken.Parse(jsonResult);
                        }
                        catch (WebException e)
                        {
                            string message = e.ResponseString();
                            if (e.HttpStatusCode() == 400 && !string.IsNullOrEmpty(message))
                            {
                                response = JToken.Parse(message);
                            }
                            else throw parseException(e);
                        }

                        uploadId = (string)response["upload_id"];
                        relativeOffset = (int)((long)response["offset"] - offset);
                        totalUploaded = offset + relativeOffset;
                        if (progress != null) progress.Report((int)(totalUploaded * 100 / fileSize));
                    } 

                    offset += bytesRead;
                }           

            }

            var baseUrl = new StringBuilder(DropboxConfig.UploadFinishUrl);
            baseUrl.Append(DropboxConfig.AccessType);
            baseUrl.Append(concatenatePath(dDestFolder.Path, name));

            var finalUrl = new ParamUrl(baseUrl.ToString());
            finalUrl.Add("upload_id", uploadId);
            var finishResponse = await queryServer(finalUrl, WebRequestMethods.Http.Post).ConfigureAwait(false);

            DropboxFileInfo file = new DropboxFileInfo() { Parent = destinationFolder };
            setupFileWithMetadata(file, JToken.Parse(finishResponse));
            destinationFolder.Contents.Add(name.ToLowerInvariant(), file);
            return file;
        }
示例#10
0
 private async Task<DFileInfo> localFileOperationAsync(DFileInfo destinationFolder, bool move)
 {
     if (destinationFolder == null)
         throw new NullReferenceException(ExceptionMessage.IsNullOrInvalid("destinationFolder"));
     if (destinationFolder.IsReadOnly)
         throw new InvalidOperationException(ExceptionMessage.ReadOnly);
     if (!destinationFolder.IsDirectory)
         throw new InvalidOperationException("Destination is not a folder. Impossible to move/copy to a file.");
     if (this.Provider == destinationFolder.Provider)
     {
         if (move)
         {
             return await Provider.MoveAsync(this, destinationFolder);
         }
         else
         {
             return await Provider.CopyAsync(this, destinationFolder);
         }
     }
     else
     {
         if (this.IsDirectory)
             throw new InvalidOperationException("Copying or moving folders between providers is not supported.");
         Stream thisFile = await this.GetDownloadStreamAsync();
         var file = await destinationFolder.CreateFileAsync(this.Name, thisFile, CancellationToken.None);
         if (move) await this.DeleteAsync();
         return file;
     }
 }
示例#11
0
 public async Task NavigatedToAsync(DFileInfo file)
 {
     // File system updates on hash mismatch.
     var dFile = (DropboxFileInfo)file;
     var metadata = await loadMetadata(dFile.Path, true, dFile.Hash).ConfigureAwait(false);
     if (metadata != null)
     {
         setupFileWithMetadata(dFile, metadata);
         await SynchronizeAsync().ConfigureAwait(false);
     }
 }
示例#12
0
 private static DFileInfo traverseFileSystem(DFileInfo currentFile, IEnumerator<string> nameEnumerator)
 {
     if (currentFile == null) return null;
     currentFile.Navigated();
     string name = nameEnumerator.Current;
     var nextFile = currentFile.Find(name);
     if (nameEnumerator.MoveNext())
         return traverseFileSystem(nextFile, nameEnumerator);
     else return nextFile;
 }
示例#13
0
 /// <summary>
 /// Copies this file or a folder to the different location.
 /// </summary>
 /// <param name="destinationFolder">The new location of the file.</param>
 /// <returns>File info of the copied file.</returns>
 public DFileInfo Copy(DFileInfo destinationFolder)
 {
     return this.CopyAsync(destinationFolder).Result;
 }
示例#14
0
 /// <summary>
 /// Moves this file or a folder to the different location.
 /// </summary>
 /// <param name="destinationFolder">The new location of the file.</param>
 /// <returns>File info of the moved file.</returns>
 public DFileInfo Move(DFileInfo destinationFolder)
 {
     return this.MoveAsync(destinationFolder).Result;
 }
示例#15
0
        public async Task<DFileInfo> UploadFileAsync(DFileInfo destinationFolder, string name, Stream stream, 
            CancellationToken cancellationToken, IProgress<int> progress, long fileSize)
        {
            var dest = (SkydriveFileInfo)destinationFolder;
            var url = sign(string.Format(SkydriveConfig.FilesUrlTemplate, dest.Id) + '/' + name) + "&overwrite=ChooseNewName";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "PUT";
            if (progress != null)
            {
                request.ContentLength = fileSize;
                request.AllowWriteStreamBuffering = false;
            }

            try
            {
                using (var reqStream = await request.GetRequestStreamAsync())
                {
                    await stream.CopyToAsync(reqStream, SkydriveConfig.ChunkSize, cancellationToken, progress, fileSize);
                }

                var webResponse = await request.GetResponseAsync();
                using (var reader = new StreamReader(webResponse.GetResponseStream()))
                {
                    var response = await reader.ReadToEndAsync().ConfigureAwait(false);
                    var metadata = JToken.Parse(response);
                    var newFile = new SkydriveFileInfo() { Parent = destinationFolder };
                    setupFileWithMetadata(newFile, metadata);
                    dest.Contents.Add(newFile.Id, newFile);
                    return newFile;
                }
            }
            catch (WebException e)
            {
                throw parseException(e);
            }
        }
示例#16
0
 public Task<DFileInfo> RenameAsync(DFileInfo file, string newName)
 {
     return copyOperation((DropboxFileInfo)file, (DropboxFileInfo)file.Parent, true, newName);
 }
示例#17
0
        public async Task<Stream> GetDownloadStreamAsync(DFileInfo file)
        {
            if (file.IsDirectory)
                throw new NotSupportedException("Downloading a folder is not supported");

            string url = string.Format(SkydriveConfig.FileContentUrlTemplate, ((SkydriveFileInfo)file).Id);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sign(url));
            request.Method = WebRequestMethods.Http.Get;

            try
            {
                var response = await request.GetResponseAsync().ConfigureAwait(false);
                return response.GetResponseStream();
            }
            catch (WebException e)
            {
                throw parseException(e);
            }
        }
示例#18
0
 public Task<DFileInfo> MoveAsync(DFileInfo file, DFileInfo destFolder)
 {
     return copyOperation((DropboxFileInfo)file, (DropboxFileInfo)destFolder, true);
 }
示例#19
0
 public Task<DFileInfo> MoveAsync(DFileInfo file, DFileInfo destinationFolder)
 {
     return fileOperation((SkydriveFileInfo)file, (SkydriveFileInfo)destinationFolder, "MOVE");
 }
示例#20
0
 public Task<DFileInfo> CopyAsync(DFileInfo file, DFileInfo destFolder)
 {
     return copyOperation((DropboxFileInfo)file, (DropboxFileInfo)destFolder, false);
 }
示例#21
0
        public async Task DeleteAsync(DFileInfo file)
        {
            var sFile = (SkydriveFileInfo)file;
            var url = string.Format(SkydriveConfig.FileInfoUrlTemplate, sFile.Id);
            // Server returns empty response which is no interest.
            await queryServer(url, "DELETE");

            if (sFile.Parent != null)
            {
                sFile.Parent.Contents.Remove(sFile.Id);
            }
            file = null;
        }
示例#22
0
 /// <summary>
 /// Moves this file or a folder to the different location.
 /// </summary>
 /// <param name="destinationFolder">The new location of the file.</param>
 /// <returns>File info of the moved file.</returns>
 public Task<DFileInfo> MoveAsync(DFileInfo destinationFolder)
 {
     if (IsReadOnly)
         throw new InvalidOperationException(ExceptionMessage.ReadOnly);
     return localFileOperationAsync(destinationFolder, true);          
 }