Source

KPDataSave / KPDataSave / Libs / DropboxAPI / DropboxClient.cs

/*
    KPDataSave - KeePass plugin which saves database in Dropbox service
    Copyright (C) 2011-2012 HexRx

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

using System;
using System.Text;
using System.IO;
using System.Net;
using System.Collections.Specialized;

using RestSharp;
using RestSharp.Authenticators;
using RestSharp.Contrib;
using DropboxAPI.Models;
using DropboxAPI.Exceptions;
using Newtonsoft.Json;

namespace DropboxAPI
{
    public class DropboxClient
    {
        // Dropbox API parameters
        private const string version = "1";
        private const string apiBase = "https://api.dropbox.com";
        private const string apiContent = "https://api-content.dropbox.com";
        private const string dbBase = "https://www.dropbox.com";
        // App keys
        private string appKey;
        private string appSecret;
        private string oauth_token;
        private string oauth_token_secret;
        public AccessToken AccessToken { get; set; }

        // Токены приложения
        public DropboxClient(string appKey, string appSecret)
        {
            this.appKey = appKey;
            this.appSecret = appSecret;
        }

        public DropboxClient(string appKey, string appSecret, string accessToken, string accessTokenSecret)
        {
            this.appKey = appKey;
            this.appSecret = appSecret;
            this.AccessToken = new AccessToken();
            this.AccessToken.Token = accessToken;
            this.AccessToken.TokenSecret = accessTokenSecret;
        }

        public string Login_GetUrlLink()
        {
            RestClient client = new RestClient(apiBase);
            RestRequest request = new RestRequest(Method.POST);

            // request_token
            client.Authenticator = OAuth1Authenticator.ForRequestToken(appKey, appSecret);
            request.Resource = "{version}/oauth/request_token";
            request.AddUrlSegment("version", version);

            RestResponse response = client.Execute(request);
            if (response.StatusCode != HttpStatusCode.OK)
                throw new DropboxClientException(JsonConvert.DeserializeObject<APIError>(response.Content).Error, response.StatusCode);

            // Получаем токены
            NameValueCollection qs = HttpUtility.ParseQueryString(response.Content);
            oauth_token = qs["oauth_token"];
            oauth_token_secret = qs["oauth_token_secret"];

            // authorize
            client.BaseUrl = dbBase;
            request = new RestRequest(Method.GET);
            request.Resource = "{version}/oauth/authorize";
            request.AddUrlSegment("version", version);
            request.AddParameter("oauth_token", oauth_token);
            string url = client.BuildUri(request).ToString();

            return url;
        }

        public AccessToken Login_RequestAccessToken()
        {
            RestClient client = new RestClient(apiBase);
            RestRequest request = new RestRequest(Method.POST);

            // access_token
            request.Resource = "{version}/oauth/access_token";
            request.AddUrlSegment("version", version);
            client.Authenticator = OAuth1Authenticator.ForAccessToken(appKey, appSecret, oauth_token, oauth_token_secret);

            RestResponse response = client.Execute(request);
            if (response.StatusCode != HttpStatusCode.OK)
                throw new DropboxClientException(JsonConvert.DeserializeObject<APIError>(response.Content).Error, response.StatusCode);

            NameValueCollection qs = HttpUtility.ParseQueryString(response.Content);
            this.AccessToken = new AccessToken();
            this.AccessToken.Token = qs["oauth_token"];
            this.AccessToken.TokenSecret = qs["oauth_token_secret"];
            this.AccessToken.UID = Convert.ToInt32(qs["uid"]);

            return this.AccessToken;
        }

        // Получение информации об аккаунте
        public AccountInfo GetAccountInfo()
        {
            RestClient client = new RestClient(apiBase);
            RestRequest request = new RestRequest(Method.GET);

            client.Authenticator = OAuth1Authenticator.ForProtectedResource(appKey, appSecret, AccessToken.Token, AccessToken.TokenSecret);
            request.Resource = "{version}/account/info";
            request.AddUrlSegment("version", version);

            RestResponse<AccountInfo> response = client.Execute<AccountInfo>(request);
            if (response.StatusCode != HttpStatusCode.OK)
                throw new DropboxClientException(JsonConvert.DeserializeObject<APIError>(response.Content).Error, response.StatusCode);

            return response.Data;
        }

        // Отправка файла
        public bool UploadFile(string path, FileInfo localFile)
        {
            RestClient client = new RestClient(apiContent);
            RestRequest request = new RestRequest(Method.POST);

            // Обязательно путь должен начинаться на '/'
            if (!path.StartsWith("/")) path = "/" + path;

            byte[] content = File.ReadAllBytes(localFile.FullName);

            client.Authenticator = OAuth1Authenticator.ForProtectedResource(appKey, appSecret, AccessToken.Token, AccessToken.TokenSecret);

            request.Resource = "{version}/files/dropbox{path}";
            request.AddUrlSegment("version", version);
            request.AddUrlSegment("path", path);
            request.AddParameter("file", localFile.Name);
            request.AddFile("file", content, localFile.Name);

            RestResponse response = client.Execute(request);

            return response.StatusCode == HttpStatusCode.OK;
        }

        // Получение данных о файлах
        public MetaData GetMetaData(string path)
        {
            RestClient client = new RestClient(apiBase);
            RestRequest request = new RestRequest(Method.GET);

            client.Authenticator = OAuth1Authenticator.ForProtectedResource(appKey, appSecret, AccessToken.Token, AccessToken.TokenSecret);

            // Путь должен начинаться на '/'
            if (!path.StartsWith("/")) path = "/" + path;

            request.Resource = "{version}/metadata/dropbox{path}";
            request.AddUrlSegment("version", version);
            request.AddUrlSegment("path", path);

            RestResponse<MetaData> response = client.Execute<MetaData>(request);
            // Если в ответе пришла ошибка, генерируем исключение DropboxClientException
            if (response.StatusCode != HttpStatusCode.OK)
                throw new DropboxClientException(JsonConvert.DeserializeObject<APIError>(response.Content).Error, response.StatusCode);

            return response.Data;
        }
    }
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.