Commits

HexRx  committed 1c379a6

Added support FTP

  • Participants
  • Parent commits 3a6fd90

Comments (0)

Files changed (2)

File KPDataSave/KPDataSaveExt.cs

 /*
     KPDataSave - KeePass plugin which saves database in Dropbox service
-    Copyright (C) 2011-2013 HexRx
+    Copyright (C) 2011-2014 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
         // Событие открытия базы паролей
         private void MainWindowFileOpened(object sender, KeePass.Forms.FileOpenedEventArgs e)
         {
-            // Пописываемся на событие по завершению сохранения данных в файл
+            // Подписываемся на событие по завершению сохранения данных в файл
             _mHost.MainWindow.FileSaved += new EventHandler<KeePass.Forms.FileSavedEventArgs>(MainWindowFileSaved);
         }
 
             _mHost.MainWindow.UIBlockInteraction(true);
             // Путь к файлу базы
             string dbFile = _mHost.Database.IOConnectionInfo.Path;
-            var client = new DropboxClientProxy("hhekhlyshoqxt5s", "h0oh21e8y2seixx", account.Token, account.Secret);
-            // Сохранение файла базы на сервере Dropbox
-            FileInfo file = new FileInfo(dbFile);
+
+            var client = new DropboxClientProxy("hhekhlyshoqxt5s", "h0oh21e8y2seixx", account.Token, account.Secret);            
 
             // Поток для выполнения асинхронной загрузки файла
-            new Thread(() => UploadFileAsync(client, file, account.Path)).Start();
+            new Thread(() => UploadFileAsync(client, dbFile, account.Path)).Start();
         }
 
         // Клик на пункте меню настроек плагина
         }
 
         // Асинхронная загрузка
-        private void UploadFileAsync(DropboxClient client, FileInfo file, string path)
+        private void UploadFileAsync(DropboxClient client, string filePath, string dropboxPath)
         {
-            // Выполняем загрузку файла
-            var status = client.UploadFile(path, file);
+            // Выполняем загрузку файла на сервер Dropbox
+
+            var status = (HttpStatusCode) 0;
+            // Локальный файл
+            if (_mHost.Database.IOConnectionInfo.IsLocalFile())
+            {
+                var file = new FileInfo(filePath);
+                status = client.UploadFile(dropboxPath, file);
+            }
+            // Загрузка с ftp
+            else
+            {
+                var request = WebRequest.Create(filePath);
+                request.Credentials = new NetworkCredential(_mHost.Database.IOConnectionInfo.UserName, _mHost.Database.IOConnectionInfo.Password);
+                request.Method = WebRequestMethods.Ftp.DownloadFile;
+                var stream = request.GetResponse().GetResponseStream();
+
+                var buffer = new byte[1024];
+                byte[] data;
+                using (var ms = new MemoryStream())
+                {
+                    int bytesRead = 0;
+                    do
+                    {
+                        if (stream != null) 
+                            bytesRead = stream.Read(buffer, 0, buffer.Length);
+                        Console.WriteLine(bytesRead);
+                        ms.Write(buffer, 0, bytesRead);
+                    } while (bytesRead != 0);
+                    data = ms.ToArray();
+                }
+
+                status = client.UploadFile(dropboxPath, data, Path.GetFileName(filePath));
+            }
             string message;
             switch (status)
             {

File KPDataSave/Libs/DropboxAPI/DropboxClient.cs

 /*
     KPDataSave - KeePass plugin which saves database in Dropbox service
-    Copyright (C) 2011-2013 HexRx
+    Copyright (C) 2011-2014 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
         }
 
         public DropboxClient(string appKey, string appSecret, string accessToken, string accessTokenSecret)
+            : this(appKey, appSecret)
         {
-            this.appKey = appKey;
-            this.appSecret = appSecret;
             this.AccessToken = new AccessToken();
             this.AccessToken.Token = accessToken;
             this.AccessToken.TokenSecret = accessTokenSecret;
             return response.Data;
         }
 
-        // Отправка файла
-        public HttpStatusCode UploadFile(string path, FileInfo localFile)
+        public HttpStatusCode UploadFile(string dropboxPath, byte[] data, string fileName)
         {
             var client = CreateRestClient(apiContent);
             var request = new RestRequest(Method.POST);
 
             // Обязательно путь должен начинаться на '/'
-            if (!path.StartsWith("/")) path = "/" + path;
-
-            byte[] content = File.ReadAllBytes(localFile.FullName);
+            if (!dropboxPath.StartsWith("/")) dropboxPath = "/" + dropboxPath;
 
             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);
+            request.AddUrlSegment("path", dropboxPath);
+            request.AddParameter("file", fileName);
+            request.AddFile("file", data, fileName);
 
             var response = client.Execute(request);
 
             return response.StatusCode;
         }
 
+        // Отправка файла
+        public HttpStatusCode UploadFile(string dropboxPath, FileInfo localFile)
+        {
+            byte[] content = File.ReadAllBytes(localFile.FullName);
+            return UploadFile(dropboxPath, content, localFile.Name);
+        }
+
         // Получение данных о файлах
         public MetaData GetMetaData(string path)
         {