А теперь удачная попытка. Суть в том, что мы сначала отправляем файлы на VPS, далее, уже на Keep2Share через PHP скрипт.
Сам скрипт отправки файла с одного сервера на другой достаточно прост
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php include "Keep2ShareAPI.php"; $api = new Keep2ShareAPI(); $api->username='panteleevstas@gmail.com'; $api->password='SLwA63'; $filepath=$_REQUEST['filepath']; var_dump($api->uploadFile($filepath)); /* object(stdClass)#2 (3) { ["user_file_id"]=> string(13) "5238354a724c3" ["status"]=> string(7) "success" ["status_code"]=> int(200) } */ ?> |
Он выдает некоторую информацию, из которой нам с вами нужно вытащить ссылку на закачанный файл. Вот какой получится результат
Вообще конечную информацию я храню в TStringList в формате
ИмяФайлаНаКлиенте=Ссылка на Сервере
Вытаскивание ссылки из такой строки происходит стандартным образом через TStringList.Values
1 2 3 4 5 6 7 8 9 10 11 |
procedure TfTestHTTPClient.bGetExampleClick(Sender: TObject); begin if PS_HTTPClient1.VisualFrame.FilesSL.Count>0 then ShowMessage( PS_HTTPClient1.VisualFrame.LinksOnKeep2Share.Values[PS_HTTPClient1.VisualFrame.FilesSL[0]] ); end; |
В принципе, что я сделал, взял уже готовую свою наработку по загрузке файлов по HTTP протоколу чанками и добавил дополнительный запрос уже с сервера idHTTPServer на K2S сервер через IIS сервер с помощью PHP скрипта. В общем, немного замудрено, но работает.
Причем, изначально у меня был построен визуальный компонент на основе TPanel. Я его в данном случае использую не визуально, обращаясь к одному из его методов.
Исходники
Как пользоваться?
В проектной группе 3 проекта – сервер, клиент, оформленный в виде компонента и тестовая программа
Нужно инсталлировать компонент TPS_HTTPClient, Delphi будет ругаться на пути к юнитам, это нормально, добавьте всё через Project>Options>SearchPath
У меня для тестовой программы прописаны следующие пути
Что делать с сервером?
Сервер нужно поместить в ту же директорию, в которой находится наш сайт на IIS, в моем случае это выглядело так…
Обращение к скрипту на сервере настроено в юните
uHTTPServerCommandGet.pas
и выглядит оно так… поменяйте его по своему усмотрению
1 |
IdHTTPLocal.Post( 'http://panteleevstas.ru/Keep2Share_Upload.php',PostParams); |
здесь важно то, чтобы сервер находился в директории сайта, потому что скрипту на PHP нужно подать относительный путь до файла.
Также понадобятся 2 файла – создайте и разместите их в директории сайта, например в корневой
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php include "Keep2ShareAPI.php"; $api = new Keep2ShareAPI(); $api->username='panteleevstas@gmail.com'; $api->password='SLwA63'; $filepath=$_REQUEST['filepath']; var_dump($api->uploadFile($filepath)); /* object(stdClass)#2 (3) { ["user_file_id"]=> string(13) "5238354a724c3" ["status"]=> string(7) "success" ["status_code"]=> int(200) } */ ?> |
Keep2Share_Upload.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php include "Keep2ShareAPI.php"; $api = new Keep2ShareAPI(); $api->username='panteleevstas@gmail.com'; $api->password='SLwA63'; $filepath=$_REQUEST['filepath']; var_dump($api->uploadFile($filepath)); /* object(stdClass)#2 (3) { ["user_file_id"]=> string(13) "5238354a724c3" ["status"]=> string(7) "success" ["status_code"]=> int(200) } */ ?> |
И второй файл Keep2ShareAPI.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 |
<?php class Keep2ShareAPI { const ERROR_INCORRECT_PARAMS = 2; const ERROR_INCORRECT_PARAM_VALUE = 3; const ERROR_INVALID_REQUEST = 4; const ERROR_YOU_ARE_NEED_AUTHORIZED = 10; const ERROR_AUTHORIZATION_EXPIRED = 11; const ERROR_FILE_NOT_FOUND = 20; const ERROR_FILE_IS_NOT_AVAILABLE = 21; const ERROR_FILE_IS_BLOCKED = 22; const ERROR_DOWNLOAD_FOLDER_NOT_SUPPORTED = 23; const ERROR_CAPTCHA_REQUIRED = 30; const ERROR_CAPTCHA_INVALID = 31; const ERROR_WRONG_FREE_DOWNLOAD_KEY = 40; const ERROR_NEED_WAIT_TO_FREE_DOWNLOAD = 41; const ERROR_DOWNLOAD_NOT_AVAILABLE = 42; const ERROR_DOWNLOAD_PREMIUM_ONLY = 43; const ERROR_NO_AVAILABLE_RESELLER_CODES = 50; const ERROR_BUY_RESELLER_CODES = 51; const ERROR_CREATE_FOLDER = 60; const ERROR_UPDATE_FILE = 61; const ERROR_COPY_FILE = 62; const ERROR_NO_AVAILABLE_NODES = 63; const ERROR_DISK_SPACE_EXCEED = 64; const ERROR_INCORRECT_USERNAME_OR_PASSWORD = 70; const ERROR_LOGIN_ATTEMPTS_EXCEEDED = 71; const ERROR_ACCOUNT_BANNED = 72; const ERROR_NO_ALLOW_ACCESS_FROM_NETWORK = 73; const ERROR_UNKNOWN_LOGIN_ERROR = 74; const ERROR_ILLEGAL_SESSION_IP = 75; const ERROR_ACCOUNT_STOLEN = 76; const ERROR_NETWORK_BANNED = 77; protected $_ch; protected $_auth_token; protected $_allowAuth = true; public $baseUrl = 'http://keep2share.cc/api/v2/'; public $username; public $password; public $verbose = false; public function __construct() { $this->_ch = curl_init(); curl_setopt($this->_ch, CURLOPT_POST, true); curl_setopt($this->_ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($this->_ch, CURLOPT_FOLLOWLOCATION, 2); $this->_auth_token = $this->getAuthToken(); } /** * @param null $captcha_challenge * @param null $captcha_response * @return bool|int True if success login or error code */ public function login($captcha_challenge = null, $captcha_response = null) { curl_setopt($this->_ch, CURLOPT_URL, $this->baseUrl.'login'); $params = [ 'username'=>$this->username, 'password'=>$this->password, ]; if($captcha_challenge) $params['captcha_challenge'] = $captcha_challenge; if($captcha_response) $params['captcha_response'] = $captcha_response; curl_setopt($this->_ch, CURLOPT_POSTFIELDS, json_encode($params)); $response = curl_exec($this->_ch); if($this->verbose) { echo '>> ' . json_encode($params), "\n"; echo '<< ' . $response, "\n"; echo "-------------------------\n"; } $data = json_decode($response, true); if(!$data || !isset($data['status'])) { self::log('Authentication failed', 'warning'); return false; } if($data['status'] == 'success') { $this->setAuthToken($data['auth_token']); $this->_auth_token = $data['auth_token']; echo $this->_auth_token; return true; } else { self::log('Authentication failed: ' . $data['message'], 'warning'); return $data['errorCode']; } } public function request($action, $params = array()) { if($this->_auth_token) { $params['auth_token'] = $this->_auth_token; } curl_setopt($this->_ch, CURLOPT_URL, $this->baseUrl.$action); curl_setopt($this->_ch, CURLOPT_POSTFIELDS, json_encode($params)); $response = curl_exec($this->_ch); if($this->verbose) { echo '>> ' . json_encode($params), "\n"; echo '<< ' . $response, "\n"; echo "-------------------------\n"; } $data = json_decode($response, true); if($data['status'] == 'error' && isset($data['code']) && $data['code'] == 403) { if($this->_allowAuth) { $this->login(); $this->_allowAuth = false; return $this->request($action, $params); } else { return false; } } return $data; } public function getCode($days, $autoBuy = true, $useExist = true) { $data = $this->request('resellerGetCode', array( 'days'=>$days, 'autoBuy'=>$autoBuy, 'useExist'=>$useExist, )); if(!isset($data['status']) || $data['status'] != 'success') { $err = 'Error get code'; if(isset($data['message'])) { $err .= ' :' . $data['message']; } self::log($err, 'warning'); return false; } else { return $data; } } public function getFilesList($parent = '/', $limit = 100, $offset = 0, array $sort = [], $type = 'any', $only_available = false, $extended_info = false) { return $this->request('getFilesList', array( 'parent'=>$parent, 'limit'=>$limit, 'offset'=>$offset, 'sort'=>$sort, 'type'=>$type, 'only_available' => $only_available, 'extended_info' => $extended_info, )); } const FILE_ACCESS_PUBLIC = 'public'; const FILE_ACCESS_PRIVATE = 'private'; const FILE_ACCESS_PREMIUM = 'premium'; public function createFolder($name, $parent = '/', $access = Keep2ShareAPI::FILE_ACCESS_PUBLIC, $is_public = false) { return $this->request('createFolder', array( 'name'=>$name, 'parent'=>$parent, 'access'=>$access, 'is_public'=>$is_public, )); } public function updateFiles($ids = [], $new_name = null, $new_parent = null, $new_access = null, $new_is_public = null) { return $this->request('updateFiles', array( 'ids'=>$ids, 'new_name'=>$new_name, 'new_parent'=>$new_parent, 'new_access'=>$new_access, 'new_is_public'=>$new_is_public, )); } public function updateFile($id, $new_name = null, $new_parent = null, $new_access = null, $new_is_public = null) { return $this->request('updateFile', array( 'id'=>$id, 'new_name'=>$new_name, 'new_parent'=>$new_parent, 'new_access'=>$new_access, 'new_is_public'=>$new_is_public, )); } public function getBalance() { return $this->request('getBalance'); } public function getFilesInfo(array $ids, $extended_info = false) { return $this->request('getFilesInfo', array( 'ids'=>$ids, 'extended_info' => $extended_info, )); } public function remoteUploadAdd(array $urls) { return $this->request('remoteUploadAdd', array( 'urls'=>$urls, )); } public function deleteFiles(array $ids) { return $this->request('deleteFiles', array( 'ids' => $ids, )); } const REMOTE_UPLOAD_STATUS_NEW = 1; const REMOTE_UPLOAD_STATUS_PROCESSING = 2; const REMOTE_UPLOAD_STATUS_COMPLETED = 3; const REMOTE_UPLOAD_STATUS_ERROR = 4; const REMOTE_UPLOAD_STATUS_ACCEPTED = 5; public function remoteUploadStatus(array $ids) { return $this->request('remoteUploadStatus', array( 'ids'=>$ids, )); } public function findFile($md5) { return $this->request('findFile', array( 'md5'=>$md5, )); } public function createFileByHash($md5, $name, $parent = '/', $access = Keep2ShareAPI::FILE_ACCESS_PUBLIC) { return $this->request('createFileByHash', array( 'hash'=>$md5, 'name'=>$name, 'parent'=>$parent, 'access'=>$access, )); } public function getUploadFormData($parent_id = null, $preferred_node = null) { return $this->request('getUploadFormData', ['parent_id' => $parent_id, 'preferred_node' => $preferred_node]); } public function test() { $response = $this->request('test'); return $response; // echo $this->_auth_token; } /** * @param $file * @param null $parent_id ID of existing folder * @return bool|mixed * @throws Exception * * You can use parent_id OR parent_name for specify file folder */ public function uploadFile($file, $parent_id = null) { if(!is_file($file)) throw new Exception("File '{$file}' is not found"); $data = $this->getUploadFormData($parent_id); if($data['status'] == 'success') { $curl = curl_init(); $postFields = $data['form_data']; $postFields[$data['file_field']] = new CURLFile($file); curl_setopt_array($curl, array( CURLOPT_FOLLOWLOCATION => false, CURLOPT_RETURNTRANSFER => true, CURLOPT_URL => $data['form_action'], CURLOPT_POST => true, CURLOPT_POSTFIELDS =>$postFields, )); $response = curl_exec($curl); if($this->verbose) echo '<<', $response, "\n"; return json_decode($response); } else { self::log('Error uploading file : ' . print_r($data, true), 'error'); return false; } } public function getAccountInfo() { return $this->request('accountInfo'); } public function requestCaptcha() { return $this->request('requestCaptcha'); } public function getUrl($file_id, $free_download_key = null, $captcha_challenge = null, $captcha_response = null) { return $this->request('getUrl', [ 'file_id'=>$file_id, 'free_download_key'=>$free_download_key, 'captcha_challenge'=>$captcha_challenge, 'captcha_response'=>$captcha_response, ]); } public function search($keywords, $operator = 'or', $sort = 'score', $limit = 20, $offset = 0, $ip_client = null) { return $this->request('search', [ 'keywords' => $keywords, 'operator' => $operator, 'sort' => $sort, 'limit' => $limit, 'offset' => $offset, 'ip_client' => $ip_client, ]); } public static function log($msg, $level) { echo $msg."\n"; } public function setAuthToken($key) { // $cache = new Memcache(); // $cache->addserver('127.0.0.1'); // $cache->set('Keep2ShareApiAuthToken', $key, 0, 1800); $temp_file = sys_get_temp_dir() . DIRECTORY_SEPARATOR . md5($this->username) . '_k2s.api.key'; file_put_contents($temp_file, $key); } public function getAuthToken() { // $cache = new Memcache(); // $cache->addserver('127.0.0.1'); // return $cache->get('Keep2ShareApiAuthToken'); $temp_file = sys_get_temp_dir() . DIRECTORY_SEPARATOR . md5($this->username) . '_k2s.api.key'; return is_file($temp_file)? file_get_contents($temp_file) : false; } } |
Что делать с клиентом?
В принципе ничего такого делать не нужно. Всё уже собрано. Можно просто компилировать и запустить третий тестовый проект из проектной группы и все заработатает.
Вот так объявляется экземпляр класса компонента – здесь мы показываем где и на каком порту будет работать наш сервер
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
procedure TfTestHTTPClient.FormCreate(Sender: TObject); begin ReportMemoryLeaksOnShutdown:=true; // small memory leaks in code PS_HTTPClient1:=TPS_HTTPClient.Create(Self); //PS_HTTPClient1.VisualFrame.SendFileInChunks.OnUploadInChunksEnd:=UploadInChunksEnd; PS_HTTPClient1.VisualFrame.OnKeep2ShareStartUpload:= OnKeep2ShareStartUpload; PS_HTTPClient1.VisualFrame.OnKeep2ShareEndUpload:= OnKeep2ShareEndUpload; // defining HTTP_ConnectionParams and Server To Request with PS_HTTPClient1.visualFrame do begin with HTTP_ConnectionParams do begin Protocol:='http'; Host:='localhost';//'40.85.142.196';//'192.168.1.102';//'localhost'; Port:='40000'; IdUser:='123'; User:='SomeUser'; end; DefineServerToRequest; end; end; |
Обязательно удаляем из памяти в ручную
1 2 3 4 |
procedure TfTestHTTPClient.FormDestroy(Sender: TObject); begin PS_HTTPClient1.Free; // << must be to avoid memory leaks end; |
Вот так отправляем на сервер K2S
1 2 3 4 5 6 7 |
procedure TfTestHTTPClient.bUpload2Keep2ShareClick(Sender: TObject); begin // PS_HTTPClient1.VisualFrame.bUploadOnKeep2ShareClick(Self); end; |
Вот так обрабатываем события
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
procedure TfTestHTTPClient.OnKeep2ShareEndUpload(Sender: TObject); begin memo.Lines.Add('Upload attempt finished '); if PS_HTTPClient1.VisualFrame.LinksOnKeep2Share.Count>0 then memo.Lines.Add(PS_HTTPClient1.VisualFrame. LinksOnKeep2Share[PS_HTTPClient1.VisualFrame.LinksOnKeep2Share.Count-1]); end; procedure TfTestHTTPClient.OnKeep2ShareStartUpload(Sender: TObject); begin memo.Lines.Add(' '); memo.Lines.Add('Upload attempt started'); end; |
Вот так вытаскиваем ссылку
1 2 3 4 5 6 7 8 9 10 11 |
procedure TfTestHTTPClient.bGetExampleClick(Sender: TObject); begin if PS_HTTPClient1.VisualFrame.FilesSL.Count>0 then ShowMessage( PS_HTTPClient1.VisualFrame.LinksOnKeep2Share.Values[PS_HTTPClient1.VisualFrame.FilesSL[0]] ); end; |
Вот такой получается результат