upyun.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. var util = require("thinkjs-util");
  2. var request = require("requestretry");
  3. var fs = require("fs");
  4. var path = require("path");
  5. module.exports = util.Class(function() {
  6. return {
  7. /**
  8. * 默认接口域名
  9. * @type {String}
  10. */
  11. DEFAULT_DOMAIN: "v0.api.upyun.com",
  12. /**
  13. * 接口的域名
  14. * @type {String}
  15. */
  16. domain: this.DEFAULT_DOMAIN,
  17. /**
  18. * 初始化
  19. * @param {[type]} bucketname [description]
  20. * @param {[type]} username [description]
  21. * @param {[type]} password [description]
  22. * @return {[type]} [description]
  23. */
  24. init: function(bucketname, username, password) {
  25. this.bucketname = bucketname;
  26. this.username = username;
  27. this.password = util.md5(password);
  28. this.domain = this.DEFAULT_DOMAIN;
  29. },
  30. /**
  31. * 设置接口的domain
  32. * @param {[type]} domain [description]
  33. */
  34. setDomain: function(domain) {
  35. this.domain = domain;
  36. return this;
  37. },
  38. /**
  39. * 签名
  40. * @param {[type]} method [description]
  41. * @param {[type]} uri [description]
  42. * @param {[type]} date [description]
  43. * @param {[type]} length [description]
  44. * @return {[type]} [description]
  45. */
  46. sign: function(method, uri, date, length) {
  47. var sign = method + '&' + uri + '&' + date + '&' + length + '&' + this.password;
  48. return 'UpYun ' + this.username + ':' + util.md5(sign);
  49. },
  50. /**
  51. * 获取文件或者文件夹的信息
  52. * @param {[type]} file [description]
  53. * @return {[type]} [description]
  54. */
  55. getInfo: function(file) {
  56. return this.request(file, 'HEAD').then(function(response) {
  57. var headers = response.headers;
  58. return {
  59. type: headers['x-upyun-file-type'],
  60. size: headers['x-upyun-file-size'],
  61. date: headers['x-upyun-file-date']
  62. };
  63. });
  64. },
  65. /**
  66. * 查看空间占用信息
  67. * @return {[type]} [description]
  68. */
  69. getUsage: function(path) {
  70. path = path || "/";
  71. return this.request(path + "?usage").then(function(response) {
  72. return parseInt(response.body, 10);
  73. });
  74. },
  75. /**
  76. * 从返回的headers里获取图片的信息
  77. * @param {[type]} response [description]
  78. * @return {[type]} [description]
  79. */
  80. getPicInfo: function(response) {
  81. var headers = response.headers;
  82. return {
  83. width: headers['x-upyun-width'],
  84. height: headers['x-upyun-height'],
  85. frames: headers['x-upyun-frames'],
  86. type: headers['x-upyun-file-type']
  87. };
  88. },
  89. /**
  90. * 上传文件或者文件夹
  91. * @param {[type]} savePath [description]
  92. * @param {[type]} filePath [description]
  93. * @return {[type]} [description]
  94. */
  95. upload: function(savePath, filePath, headers) {
  96. var defaultHeaders = {
  97. mkdir: true
  98. };
  99. if (util.isObject(headers)) {
  100. defaultHeaders = util.extend(defaultHeaders, headers);
  101. } else if (headers) {
  102. defaultHeaders["Content-Secret"] = headers;
  103. }
  104. var self = this;
  105. //文件上传
  106. if (util.isFile(filePath)) {
  107. var stream = fs.readFileSync(filePath);
  108. var filename;
  109. if (!(/\.\w+$/.test(savePath))) {
  110. filename = filePath.split('/');
  111. filename = filename[filename.length - 1];
  112. savePath += '/' + filename;
  113. }
  114. return this.request(savePath, 'PUT', stream, defaultHeaders).then(function(response) {
  115. return self.getPicInfo(response);
  116. }).then(function(data) {
  117. if (filename) {
  118. data.filename = filename;
  119. }
  120. return data;
  121. });
  122. } else if (util.isDir(filePath)) { //文件夹上传
  123. if (savePath.slice(-1) !== '/') {
  124. savePath += '/';
  125. }
  126. if (filePath.slice(-1) !== '/') {
  127. filePath += '/';
  128. }
  129. var promises = [];
  130. var files = fs.readdirSync(filePath);
  131. files.forEach(function(item) {
  132. var nFilePath = filePath + item;
  133. var state = fs.statSync(nFilePath);
  134. if (state.isFile() || state.isDirectory()) {
  135. var promise = self.upload(savePath + item, nFilePath);
  136. promises.push(promise);
  137. }
  138. });
  139. if (promises.length) {
  140. return util.Promise.all(promises);
  141. } else {
  142. return self.mkDir(savePath);
  143. }
  144. } else { //普通内容上传
  145. return this.request(savePath, 'PUT', filePath, defaultHeaders).then(function(response) {
  146. return self.getPicInfo(response);
  147. });
  148. }
  149. },
  150. /**
  151. * 文件或者文件夹下载
  152. * @param {[type]} path [description]
  153. * @param {[type]} savePath [description]
  154. * @return {[type]} [description]
  155. */
  156. download: function(sourcePath, savePath, typeData) {
  157. sourcePath = sourcePath || "/";
  158. //if (savePath && savePath.slice(-1) !== "/") {
  159. // savePath += "/";
  160. //}
  161. var self = this;
  162. var promise = typeData ? util.getPromise(typeData) : this.getInfo(sourcePath);
  163. return promise.then(function(data) {
  164. if (data.type === 'folder') {
  165. if (sourcePath.slice(-1) !== "/") {
  166. sourcePath += "/";
  167. }
  168. return self.readDir(sourcePath).then(function(data) {
  169. var promises = [];
  170. data.forEach(function(item) {
  171. var nPath = sourcePath + item.name;
  172. var promise;
  173. //文件夹
  174. if (item.type === 'F') {
  175. promise = self.download(nPath + "/", savePath + item.name + "/", {
  176. type: 'folder'
  177. });
  178. } else if (item.type) { //文件
  179. promise = self.download(nPath, savePath, {
  180. type: 'file'
  181. });
  182. }
  183. promises.push(promise);
  184. });
  185. return util.Promise.all(promises);
  186. });
  187. } else {
  188. //单个文件
  189. return self.request(sourcePath, 'GET', '', {}, {
  190. encoding: null
  191. }).then(function(response) {
  192. if (!savePath) {
  193. return response.body;
  194. }
  195. var sourceExt = path.extname(sourcePath);
  196. var saveExt = path.extname(savePath);
  197. var fileSavePath = savePath;
  198. if (sourceExt && sourceExt === saveExt) {
  199. util.mkdir(path.dirname(savePath));
  200. } else {
  201. util.mkdir(savePath);
  202. fileSavePath = savePath + path.basename(sourcePath);
  203. }
  204. fs.writeFileSync(fileSavePath, response.body);
  205. });
  206. }
  207. });
  208. },
  209. /**
  210. * 删除文件或者文件夹
  211. * @param {[type]} path [description]
  212. * @param {[type]} force [description]
  213. * @return {[type]} [description]
  214. */
  215. rm: function(path, force) {
  216. if (!path) {
  217. return util.getPromise(new Error("path can't empty"), true);
  218. }
  219. if (path.slice(-1) !== '/') {
  220. path += '/';
  221. }
  222. var self = this;
  223. return this.getInfo(path).then(function(data) {
  224. if (data.type === 'folder') {
  225. if (!force) {
  226. return self.request(path, 'DELETE').then(function(response) {
  227. return response.body;
  228. });
  229. }
  230. return self.readDir(path).then(function(data) {
  231. var promises = [];
  232. data.forEach(function(item) {
  233. var nPath = path + item.name;
  234. var promise;
  235. //文件夹
  236. if (item.type === 'F') {
  237. promise = self.rm(nPath + "/", true);
  238. } else if (item.type) { //文件
  239. promise = self.rm(nPath);
  240. }
  241. promises.push(promise);
  242. });
  243. if (promises.length) {
  244. return util.Promise.all(promises);
  245. }
  246. }).then(function() {
  247. return self.rm(path, false);
  248. });
  249. } else {
  250. return self.request(path, 'DELETE').then(function(response) {
  251. return response.body;
  252. });
  253. }
  254. });
  255. },
  256. /**
  257. * 递归创建目录
  258. * @param {[type]} path [description]
  259. * @return {[type]} [description]
  260. */
  261. mkDir: function(path) {
  262. return this.request(path, 'PUT', '', {
  263. mkdir: true,
  264. folder: true
  265. }).then(function(response) {
  266. return response.body;
  267. });
  268. },
  269. /**
  270. * 读取目录下的文件和子目录
  271. * @param {[type]} dir [description]
  272. * @return {[type]} [description]
  273. */
  274. readDir: function(path, recursive) {
  275. path = path || "/";
  276. if (path.slice(-1) !== '/') {
  277. path += '/';
  278. }
  279. var self = this;
  280. return this.request(path, "GET").then(function(response) {
  281. var dirs = response.body.split("\n");
  282. var result = [];
  283. var promises = [];
  284. for (var i = 0; i < dirs.length; i++) {
  285. var dir = dirs[i];
  286. var attrs = dir.split("\t");
  287. dir = {
  288. name: attrs[0],
  289. type: attrs[1],
  290. size: attrs[2],
  291. time: attrs[3]
  292. };
  293. if (recursive && dir.type === 'F') {
  294. var promise = self.readDir(path + dir.name, true).then(function(data) {
  295. dir.children = data;
  296. });
  297. promises.push(promise);
  298. }
  299. result.push(dir);
  300. }
  301. if (promises.length) {
  302. return util.Promise.all(promises).then(function() {
  303. return result;
  304. });
  305. } else {
  306. return result;
  307. }
  308. });
  309. },
  310. /**
  311. * 请求数据
  312. * @param {[type]} uri [description]
  313. * @param {[type]} method [description]
  314. * @param {[type]} data [description]
  315. * @param {[type]} headers [description]
  316. * @param {[type]} options [description]
  317. * @return {[type]} [description]
  318. */
  319. request: function(uri, method, data, headers, options) {
  320. uri = "/" + this.bucketname + uri;
  321. method = method || "GET";
  322. headers = headers || {};
  323. var length = 0;
  324. if (data) {
  325. length = !util.isBuffer(data) ? Buffer.byteLength(data) : data.length;
  326. }
  327. var date = (new Date()).toUTCString();
  328. var Authorization = this.sign(method, uri, date, length);
  329. headers = util.extend(headers, {
  330. 'Content-Length': length,
  331. 'Date': date,
  332. 'Authorization': Authorization
  333. });
  334. var deferred = util.getDefer();
  335. var url = '';
  336. if (this.domain == this.DEFAULT_DOMAIN) {
  337. url = "https://" + this.domain + uri;
  338. } else {
  339. url = "http://" + this.domain + uri;
  340. }
  341. var opts = util.extend({
  342. url: url,
  343. method: method,
  344. body: data || "",
  345. timeout: 120000,
  346. headers: headers,
  347. maxAttempts: 5,
  348. retryDelay: 500,
  349. retryStrategy: request.RetryStrategies.HTTPOrNetworkError
  350. }, options);
  351. request(opts, function(error, response, body) {
  352. if (error || response == undefined || response.statusCode !== 200) {
  353. deferred.reject({
  354. code: (response && response.statusCode) ? response.statusCode : -1,
  355. message: error || "statusCode: " + response.statusCode + "; body: " + body
  356. });
  357. } else {
  358. deferred.resolve(response);
  359. }
  360. });
  361. return deferred.promise;
  362. }
  363. };
  364. });