PageRenderTime 46ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/apps/files_external/lib/storage/dropbox.php

https://gitlab.com/wuhang2003/core
PHP | 352 lines | 277 code | 29 blank | 46 comment | 54 complexity | e216c25082d5aecd2bcc63a34cc809df MD5 | raw file
  1. <?php
  2. /**
  3. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  4. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  5. * @author Morris Jobke <hey@morrisjobke.de>
  6. * @author Philipp Kapfer <philipp.kapfer@gmx.at>
  7. * @author Robin Appelman <icewind@owncloud.com>
  8. * @author Robin McCorkell <robin@mccorkell.me.uk>
  9. * @author Sascha Schmidt <realriot@realriot.de>
  10. * @author Thomas Müller <thomas.mueller@tmit.eu>
  11. * @author Vincent Petry <pvince81@owncloud.com>
  12. *
  13. * @copyright Copyright (c) 2016, ownCloud, Inc.
  14. * @license AGPL-3.0
  15. *
  16. * This code is free software: you can redistribute it and/or modify
  17. * it under the terms of the GNU Affero General Public License, version 3,
  18. * as published by the Free Software Foundation.
  19. *
  20. * This program is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. * GNU Affero General Public License for more details.
  24. *
  25. * You should have received a copy of the GNU Affero General Public License, version 3,
  26. * along with this program. If not, see <http://www.gnu.org/licenses/>
  27. *
  28. */
  29. namespace OCA\Files_External\Lib\Storage;
  30. use GuzzleHttp\Exception\RequestException;
  31. use Icewind\Streams\IteratorDirectory;
  32. use Icewind\Streams\RetryWrapper;
  33. require_once __DIR__ . '/../../3rdparty/Dropbox/autoload.php';
  34. class Dropbox extends \OC\Files\Storage\Common {
  35. private $dropbox;
  36. private $root;
  37. private $id;
  38. private $metaData = array();
  39. private $oauth;
  40. private static $tempFiles = array();
  41. public function __construct($params) {
  42. if (isset($params['configured']) && $params['configured'] == 'true'
  43. && isset($params['app_key'])
  44. && isset($params['app_secret'])
  45. && isset($params['token'])
  46. && isset($params['token_secret'])
  47. ) {
  48. $this->root = isset($params['root']) ? $params['root'] : '';
  49. $this->id = 'dropbox::'.$params['app_key'] . $params['token']. '/' . $this->root;
  50. $this->oauth = new \Dropbox_OAuth_Curl($params['app_key'], $params['app_secret']);
  51. $this->oauth->setToken($params['token'], $params['token_secret']);
  52. // note: Dropbox_API connection is lazy
  53. $this->dropbox = new \Dropbox_API($this->oauth, 'auto');
  54. } else {
  55. throw new \Exception('Creating Dropbox storage failed');
  56. }
  57. }
  58. /**
  59. * @param string $path
  60. */
  61. private function deleteMetaData($path) {
  62. $path = ltrim($this->root.$path, '/');
  63. if (isset($this->metaData[$path])) {
  64. unset($this->metaData[$path]);
  65. return true;
  66. }
  67. return false;
  68. }
  69. private function setMetaData($path, $metaData) {
  70. $this->metaData[ltrim($path, '/')] = $metaData;
  71. }
  72. /**
  73. * Returns the path's metadata
  74. * @param string $path path for which to return the metadata
  75. * @param bool $list if true, also return the directory's contents
  76. * @return mixed directory contents if $list is true, file metadata if $list is
  77. * false, null if the file doesn't exist or "false" if the operation failed
  78. */
  79. private function getDropBoxMetaData($path, $list = false) {
  80. $path = ltrim($this->root.$path, '/');
  81. if ( ! $list && isset($this->metaData[$path])) {
  82. return $this->metaData[$path];
  83. } else {
  84. if ($list) {
  85. try {
  86. $response = $this->dropbox->getMetaData($path);
  87. } catch (\Exception $exception) {
  88. \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
  89. return false;
  90. }
  91. $contents = array();
  92. if ($response && isset($response['contents'])) {
  93. // Cache folder's contents
  94. foreach ($response['contents'] as $file) {
  95. if (!isset($file['is_deleted']) || !$file['is_deleted']) {
  96. $this->setMetaData($path.'/'.basename($file['path']), $file);
  97. $contents[] = $file;
  98. }
  99. }
  100. unset($response['contents']);
  101. }
  102. if (!isset($response['is_deleted']) || !$response['is_deleted']) {
  103. $this->setMetaData($path, $response);
  104. }
  105. // Return contents of folder only
  106. return $contents;
  107. } else {
  108. try {
  109. $requestPath = $path;
  110. if ($path === '.') {
  111. $requestPath = '';
  112. }
  113. $response = $this->dropbox->getMetaData($requestPath, 'false');
  114. if (!isset($response['is_deleted']) || !$response['is_deleted']) {
  115. $this->setMetaData($path, $response);
  116. return $response;
  117. }
  118. return null;
  119. } catch (\Exception $exception) {
  120. if ($exception instanceof \Dropbox_Exception_NotFound) {
  121. // don't log, might be a file_exist check
  122. return false;
  123. }
  124. \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
  125. return false;
  126. }
  127. }
  128. }
  129. }
  130. public function getId(){
  131. return $this->id;
  132. }
  133. public function mkdir($path) {
  134. $path = $this->root.$path;
  135. try {
  136. $this->dropbox->createFolder($path);
  137. return true;
  138. } catch (\Exception $exception) {
  139. \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
  140. return false;
  141. }
  142. }
  143. public function rmdir($path) {
  144. return $this->unlink($path);
  145. }
  146. public function opendir($path) {
  147. $contents = $this->getDropBoxMetaData($path, true);
  148. if ($contents !== false) {
  149. $files = array();
  150. foreach ($contents as $file) {
  151. $files[] = basename($file['path']);
  152. }
  153. return IteratorDirectory::wrap($files);
  154. }
  155. return false;
  156. }
  157. public function stat($path) {
  158. $metaData = $this->getDropBoxMetaData($path);
  159. if ($metaData) {
  160. $stat['size'] = $metaData['bytes'];
  161. $stat['atime'] = time();
  162. $stat['mtime'] = (isset($metaData['modified'])) ? strtotime($metaData['modified']) : time();
  163. return $stat;
  164. }
  165. return false;
  166. }
  167. public function filetype($path) {
  168. if ($path == '' || $path == '/') {
  169. return 'dir';
  170. } else {
  171. $metaData = $this->getDropBoxMetaData($path);
  172. if ($metaData) {
  173. if ($metaData['is_dir'] == 'true') {
  174. return 'dir';
  175. } else {
  176. return 'file';
  177. }
  178. }
  179. }
  180. return false;
  181. }
  182. public function file_exists($path) {
  183. if ($path == '' || $path == '/') {
  184. return true;
  185. }
  186. if ($this->getDropBoxMetaData($path)) {
  187. return true;
  188. }
  189. return false;
  190. }
  191. public function unlink($path) {
  192. try {
  193. $this->dropbox->delete($this->root.$path);
  194. $this->deleteMetaData($path);
  195. return true;
  196. } catch (\Exception $exception) {
  197. \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
  198. return false;
  199. }
  200. }
  201. public function rename($path1, $path2) {
  202. try {
  203. // overwrite if target file exists and is not a directory
  204. $destMetaData = $this->getDropBoxMetaData($path2);
  205. if (isset($destMetaData) && $destMetaData !== false && !$destMetaData['is_dir']) {
  206. $this->unlink($path2);
  207. }
  208. $this->dropbox->move($this->root.$path1, $this->root.$path2);
  209. $this->deleteMetaData($path1);
  210. return true;
  211. } catch (\Exception $exception) {
  212. \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
  213. return false;
  214. }
  215. }
  216. public function copy($path1, $path2) {
  217. $path1 = $this->root.$path1;
  218. $path2 = $this->root.$path2;
  219. try {
  220. $this->dropbox->copy($path1, $path2);
  221. return true;
  222. } catch (\Exception $exception) {
  223. \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
  224. return false;
  225. }
  226. }
  227. public function fopen($path, $mode) {
  228. $path = $this->root.$path;
  229. switch ($mode) {
  230. case 'r':
  231. case 'rb':
  232. try {
  233. // slashes need to stay
  234. $encodedPath = str_replace('%2F', '/', rawurlencode(trim($path, '/')));
  235. $downloadUrl = 'https://api-content.dropbox.com/1/files/auto/' . $encodedPath;
  236. $headers = $this->oauth->getOAuthHeader($downloadUrl, [], 'GET');
  237. $client = \OC::$server->getHTTPClientService()->newClient();
  238. try {
  239. $response = $client->get($downloadUrl, [
  240. 'headers' => $headers,
  241. 'stream' => true,
  242. ]);
  243. } catch (RequestException $e) {
  244. if (!is_null($e->getResponse())) {
  245. if ($e->getResponse()->getStatusCode() === 404) {
  246. return false;
  247. } else {
  248. throw $e;
  249. }
  250. } else {
  251. throw $e;
  252. }
  253. }
  254. $handle = $response->getBody();
  255. return RetryWrapper::wrap($handle);
  256. } catch (\Exception $exception) {
  257. \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
  258. return false;
  259. }
  260. case 'w':
  261. case 'wb':
  262. case 'a':
  263. case 'ab':
  264. case 'r+':
  265. case 'w+':
  266. case 'wb+':
  267. case 'a+':
  268. case 'x':
  269. case 'x+':
  270. case 'c':
  271. case 'c+':
  272. if (strrpos($path, '.') !== false) {
  273. $ext = substr($path, strrpos($path, '.'));
  274. } else {
  275. $ext = '';
  276. }
  277. $tmpFile = \OCP\Files::tmpFile($ext);
  278. \OC\Files\Stream\Close::registerCallback($tmpFile, array($this, 'writeBack'));
  279. if ($this->file_exists($path)) {
  280. $source = $this->fopen($path, 'r');
  281. file_put_contents($tmpFile, $source);
  282. }
  283. self::$tempFiles[$tmpFile] = $path;
  284. return fopen('close://'.$tmpFile, $mode);
  285. }
  286. return false;
  287. }
  288. public function writeBack($tmpFile) {
  289. if (isset(self::$tempFiles[$tmpFile])) {
  290. $handle = fopen($tmpFile, 'r');
  291. try {
  292. $this->dropbox->putFile(self::$tempFiles[$tmpFile], $handle);
  293. unlink($tmpFile);
  294. $this->deleteMetaData(self::$tempFiles[$tmpFile]);
  295. } catch (\Exception $exception) {
  296. \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
  297. }
  298. }
  299. }
  300. public function free_space($path) {
  301. try {
  302. $info = $this->dropbox->getAccountInfo();
  303. return $info['quota_info']['quota'] - $info['quota_info']['normal'];
  304. } catch (\Exception $exception) {
  305. \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
  306. return false;
  307. }
  308. }
  309. public function touch($path, $mtime = null) {
  310. if ($this->file_exists($path)) {
  311. return false;
  312. } else {
  313. $this->file_put_contents($path, '');
  314. }
  315. return true;
  316. }
  317. /**
  318. * check if curl is installed
  319. */
  320. public static function checkDependencies() {
  321. return true;
  322. }
  323. }