oss.js 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352
  1. /*!
  2. * oss - node.js sdk
  3. * oss core
  4. * Copyright(c) 2012 fantaysni <fantasyni@163.com>
  5. * MIT Licensed
  6. */
  7. var Emitter = require('events').EventEmitter;
  8. var request = require('request');
  9. var mimetypes = require('mime');
  10. var fs = require('fs');
  11. var path = require('path');
  12. var async = require('async');
  13. var xml2js = require('xml2js');
  14. var data2xml = require('data2xml');
  15. var util = require('util');
  16. var oppressor = require('oppressor')
  17. var crypto = require('crypto');
  18. var _ = require('../util');
  19. var ProgressBar = require('progress');
  20. var con = require('../config.js');
  21. var ndir = require('ndir');
  22. var bucket_filter = require('./filter').bucket_filter;
  23. var object_filter = require('./filter').object_filter;
  24. var emitter = new Emitter;
  25. var written = 0;
  26. var debug_mode = 0;
  27. emitter.on("progress",function(result){
  28. //console.log(result);
  29. process.stdout.write('\r\033[2K' + JSON.stringify(result));
  30. })
  31. var oss = function(options){
  32. this._accessId = options.accessId;
  33. this._accessKey = options.accessKey;
  34. this._host = options.host || "oss.aliyuncs.com";
  35. //"storage.aliyun.com";
  36. this._port = options.port || "8080";
  37. this._timeout = 50000;
  38. if(this._accessId == "" || this._accessKey == ""){
  39. throw new Error("OSS accessId and accessKey are both required");
  40. }
  41. }
  42. module.exports = oss;
  43. var pro = oss.prototype;
  44. /**
  45. * oss authRequest
  46. * @param object $options (Optional)
  47. * @return {cb}
  48. * @api private
  49. */
  50. pro.authRequest = function(options,cb){
  51. var self = this;
  52. // check Bucket name,list_bucket do not have to
  53. if(!((('/' == options[con.OSS_OBJECT])||('' == options[con.OSS_BUCKET]))&&('GET' == options[con.OSS_METHOD])) && !_.validate_bucket(options[con.OSS_BUCKET])){
  54. throw new Error("oss_bucket : " + options[con.OSS_BUCKET] + " invalid");
  55. }
  56. //Object charset should be UTF-8
  57. // gb2312->utf8
  58. // current version do not support gb2312 or gbk object name
  59. if(_.is_gb2312(options[con.OSS_OBJECT])){
  60. throw new Error('current version do not support gb2312 or gbk object name !!!');
  61. }
  62. //check Object name
  63. if(options[con.OSS_OBJECT] !== "" && typeof options[con.OSS_OBJECT] === "string" && !_.validate_object(options[con.OSS_OBJECT])){
  64. throw new Error("oss_object : " + options[con.OSS_OBJECT] + " invalid");
  65. }
  66. //check ACL
  67. if(typeof options[con.OSS_HEADERS]!== "undefined" && typeof options[con.OSS_HEADERS][con.OSS_ACL] === "string" && options[con.OSS_HEADERS][con.OSS_ACL] != "" ){
  68. for(var _acl in options[con.OSS_HEADERS][con.OSS_ACL]){
  69. var _temp = _acl.toLowerCase();
  70. var _flag = 0;
  71. for(var _i in options[con.OSS_HEADERS][con.OSS_ACL]){
  72. if(_temp == _i) {
  73. _flag = 1;
  74. break;
  75. }
  76. }
  77. if(_flag == 0){
  78. throw new Error("oss_acl : " + options[con.OSS_HEADERS][con.OSS_ACL] + "invalid");
  79. }
  80. }
  81. }
  82. //make url
  83. var url = this.make_url(options);
  84. options['url'] = url;
  85. var request_md5 = "";
  86. var response_md5 = ""; //etag
  87. async.waterfall([
  88. function getHeader(callback){
  89. self.get_headers(options,function(headers){
  90. //if(options['action'] === 'GET_SIGN_URL'){
  91. // var sign_url = url + '?' + this._accessId + '&Expires=' + options['expires'] + '&Signature=' + headers
  92. //}
  93. callback(null,headers);
  94. });
  95. },
  96. function doRequest(headers,callback){
  97. options['headers'] = headers;
  98. options['timeout'] = options['timeout'] || self._timeout;
  99. var bar = new ProgressBar(' downloading [:bar] :percent :etas', {
  100. complete: '='
  101. , incomplete: ' '
  102. , width: 20
  103. , total: parseInt(options['filesize']) || 0
  104. });
  105. var req = request(options,function(err,response,body){
  106. if(err && cb) cb(err);
  107. if(response && response.statusCode != 200 && response.statusCode != 204){
  108. var e = new Error(body);
  109. e.code = response.statusCode;
  110. if (cb) cb(e);
  111. }else{
  112. if (body && !options.dstFile) {
  113. var parser = new xml2js.Parser();
  114. parser.parseString(body, function(error, result) {
  115. if(error) throw error;
  116. cb(error, result);
  117. });
  118. } else {
  119. if(response && response.headers){
  120. cb(err,{bucket: options['bucket'],
  121. method: options['method'],
  122. request_header:options['headers'],
  123. response_header:response.headers,
  124. statusCode:response.statusCode,
  125. status:"operations finished"
  126. });
  127. }
  128. }
  129. }
  130. });
  131. // put a file to oss
  132. if (typeof options['action']!="undefined" && options.srcFile) {
  133. var rstream ;
  134. if(options['action'] == "UPLOAD_PART"){
  135. rstream = fs.createReadStream(options.srcFile,{start:options['seekTo'],end:(options['upload_length']+options['seekTo']-1)});
  136. }else{
  137. rstream = fs.createReadStream(options.srcFile);
  138. }
  139. if(options['gzip']){
  140. rstream.pipe(oppressor(req));
  141. }else{
  142. rstream.pipe(req);
  143. }
  144. var bar = new ProgressBar(' downloading [:bar] :percent :etas', {
  145. complete: '='
  146. , incomplete: ' '
  147. , width: 20
  148. , total: options['filesize']
  149. });
  150. rstream.on('data', function(chunk){
  151. written+=chunk.length;
  152. //bar.tick(chunk.length);
  153. emitter.emit('progress',{
  154. percent: written/options['filesize'] * 100 | 0
  155. , written: written
  156. , total: options['filesize']
  157. });
  158. });
  159. req.on('progress', emitter.emit.bind(emitter, 'progress'));
  160. }
  161. // get a object from oss and save as a file
  162. if (typeof options['action']!="undefined" && options.dstFile) {
  163. var wstream = fs.createWriteStream(options.dstFile);
  164. req.pipe(wstream);
  165. }
  166. callback(null,req);
  167. }
  168. ],function(err,result){
  169. if(err) cb(err,result);
  170. });
  171. }
  172. /**
  173. * make request URL
  174. * @param object $options (Optional)
  175. * @return string
  176. * @api private
  177. */
  178. pro.make_url = function(options){
  179. var url = "";
  180. var params = [];
  181. url += con.use_ssl ? 'https://' : 'http://';
  182. url += (this._host+":"+this._port);
  183. if(typeof options[con.OSS_BUCKET] === "string"){
  184. url += ('/' + options[con.OSS_BUCKET]);
  185. }
  186. if(typeof options[con.OSS_OBJECT] === "string"){
  187. url = url + '/' + options[con.OSS_OBJECT];
  188. }
  189. if(typeof options[con.OSS_PREFIX] === "string"){
  190. params.push('prefix=' + options[con.OSS_PREFIX]);
  191. }
  192. if(typeof options[con.OSS_MARKER] === "string"){
  193. params.push('marker=' + options[con.OSS_MARKER]);
  194. }
  195. if(typeof options[con.OSS_MAX_KEYS] !== "undefined"){
  196. params.push('max-keys=' + options[con.OSS_MAX_KEYS]);
  197. }
  198. if(typeof options[con.OSS_DELIMITER] === "string"){
  199. params.push('delimiter=' + options[con.OSS_DELIMITER]);
  200. }
  201. if(params.length > 0){
  202. url = url + '?' + params.join('&');
  203. }
  204. //Acl
  205. if(typeof options[con.OSS_ACL] !== "undefined" ){
  206. url += '?acl';
  207. }
  208. //Group
  209. if(typeof options[con.OSS_OBJECT_GROUP] !== "undefined"){
  210. url += '?group';
  211. }
  212. //Multi part
  213. if(typeof options[con.OSS_MULTI_PART] !== "undefined"){
  214. url += '?uploads';
  215. }
  216. //Multi Delete
  217. if(typeof options[con.OSS_MULTI_DELETE] !== "undefined"){
  218. url += '?delete';
  219. }
  220. //partNumber
  221. if(typeof options["partNumber"] !== "undefined"){
  222. url += ('?partNumber='+options["partNumber"]);
  223. }
  224. //uploadId
  225. if(typeof options["uploadId"] !== "undefined"){
  226. url += ('?uploadId='+options["uploadId"]);
  227. }
  228. url = url.replace(/\?/g,"&").replace(/\&/,"?");
  229. return url;
  230. }
  231. /**
  232. * get canonicalizeResource for the auth
  233. * @param object $options (Optional)
  234. * @return string
  235. * @api private
  236. */
  237. pro.canonicalizeResource = function(options){
  238. var resource = '';
  239. if(typeof options[con.OSS_BUCKET] === 'string'){
  240. resource = '/' + options[con.OSS_BUCKET];
  241. }
  242. if(typeof options[con.OSS_OBJECT] === 'string'){
  243. resource = resource + '/' + options[con.OSS_OBJECT];
  244. }
  245. //Acl
  246. if(typeof options[con.OSS_ACL] !== "undefined" ){
  247. resource += '?acl';
  248. }
  249. //Group
  250. if(typeof options[con.OSS_OBJECT_GROUP] !== "undefined"){
  251. resource += '?group';
  252. }
  253. //partNumber
  254. if(typeof options["partNumber"] !== "undefined"){
  255. resource += ('?partNumber='+options["partNumber"]);
  256. }
  257. //Multi part
  258. if(typeof options[con.OSS_MULTI_PART] !== "undefined"){
  259. resource += '?uploads';
  260. }
  261. //uploadId
  262. if(typeof options["uploadId"] !== "undefined"){
  263. resource += ('?uploadId='+options["uploadId"]);
  264. }
  265. //Multi Delete
  266. if(typeof options[con.OSS_MULTI_DELETE] !== "undefined"){
  267. resource += '?delete';
  268. }
  269. resource = resource.replace(/\?/g,"&").replace(/\&/,"?");
  270. return resource;
  271. }
  272. /**
  273. * Perform the following:
  274. *
  275. * - ignore non-oss headers
  276. * - lowercase fields
  277. * - sort lexicographically
  278. * - trim whitespace between ":"
  279. * - join with newline
  280. *
  281. * @param {Object} headers
  282. * @return {String}
  283. * @api private
  284. */
  285. pro.canonicalizeHeaders = function(headers){
  286. var buf = []
  287. , fields = Object.keys(headers);
  288. for (var i = 0, len = fields.length; i < len; ++i) {
  289. var field = fields[i]
  290. , val = headers[field]
  291. , field = field.toLowerCase();
  292. if (0 !== field.indexOf('x-oss')) continue;
  293. buf.push(field + ':' + val);
  294. }
  295. return buf.sort().join('\n');
  296. }
  297. /**
  298. * get http request headers
  299. * @param object options
  300. * @return string
  301. * @api private
  302. */
  303. pro.get_headers = function(options,cb){
  304. var headers = {};
  305. var self = this;
  306. if(options['action'] == "UPLOAD_PART" && options.srcFile){
  307. headers['content-type'] = mimetypes.lookup(path.extname(options.srcFile));
  308. self.fillHeaders(options,headers);
  309. cb(headers);
  310. }else{
  311. if(typeof options['action'] !== "undefined" && options.srcFile){
  312. headers['content-type'] = mimetypes.lookup(path.extname(options.srcFile));
  313. async.waterfall([
  314. function checkFile(callback){
  315. fs.stat(options.srcFile,function(err,stats){
  316. if(err) throw err;
  317. callback(err,stats,options.srcFile);
  318. });
  319. },
  320. function readFile(stats,file,callback){
  321. if(stats.isFile()){
  322. fs.readFile(file,'utf8',function(err,data){
  323. callback(err,stats,data);
  324. });
  325. }else{
  326. throw new Error("file is not exist");
  327. }
  328. },
  329. function fillFileData(stats,data,callback){
  330. headers['Content-MD5'] = _.md5(data);
  331. self.fillHeaders(options,headers);
  332. if(typeof headers['Content-Length'] == "undefined"){
  333. options['filesize'] = stats.size;
  334. headers['Content-Length'] = stats.size; // file length
  335. }
  336. callback(null,headers);
  337. }
  338. ],function(err,result){
  339. cb(headers);
  340. }
  341. );
  342. }else{
  343. self.fillHeaders(options,headers);
  344. cb(headers);
  345. }
  346. }
  347. }
  348. /**
  349. * fill headers
  350. * @param object $options (Required)
  351. * @return
  352. * @api private
  353. */
  354. pro.fillHeaders = function(options,headers){
  355. headers['Date'] = new Date().toGMTString();
  356. if(options[con.OSS_GROUP]){
  357. headers['content-type'] = 'txt/xml';
  358. }
  359. for(var key in options['headers']){
  360. headers[key] = options['headers'][key];
  361. }
  362. headers['Authorization'] = this.authorization(options,headers);
  363. }
  364. /**
  365. * Return an "Authorization" header value with the given `options`
  366. * in the form of "OSS <key>:<signature>"
  367. *
  368. * @param {Object} options
  369. * @return {String}
  370. * @api private
  371. */
  372. pro.authorization = function(options,headers){
  373. var method = options['method'];
  374. var content_md5 = headers['Content-MD5'] || '';
  375. var content_type = headers['content-type'] || '';
  376. var date = headers['Date'];
  377. var canonicalizeHeader = this.canonicalizeHeaders(headers);
  378. var resource = this.canonicalizeResource(options);
  379. var params = [method,content_md5,content_type,date];
  380. // this is a trick
  381. if(canonicalizeHeader != ""){
  382. params.push(canonicalizeHeader);
  383. }
  384. params.push(resource);
  385. var string_to_sign = params.join('\n') ;
  386. //var string_to_sign = method + '\n' + content_md5 + '\n' + content_type + '\n' + date + '\n' + canonicalizeHeader + resource;
  387. return 'OSS ' + this._accessId + ':' + this.hmacSha1(string_to_sign);
  388. };
  389. /**
  390. * Simple HMAC-SHA1 Wrapper
  391. *
  392. * @param signature
  393. * @return {String}
  394. * @api private
  395. */
  396. pro.hmacSha1 = function(signature){
  397. return crypto.createHmac('sha1', this._accessKey).update(signature).digest('base64');
  398. };
  399. /*
  400. * bucket operations
  401. */
  402. /**
  403. * Get_Service
  404. * list all the bucket you own
  405. *
  406. * @param
  407. * @return {cb}
  408. * @api public
  409. */
  410. pro.get_service = pro.list_bucket = function(callback){
  411. var options = {};
  412. options['method'] = "GET";
  413. options['bucket'] = '';
  414. this.authRequest(options,callback);
  415. }
  416. /**
  417. * Create_Bucket
  418. * create a bucket in oss with acl default 'private'
  419. *
  420. * @param {
  421. * bucket {required}: bucketName,
  422. * headers {optional}: {
  423. * "x-oss-acl" : acl
  424. * }
  425. * }
  426. * @return {cb}
  427. * @api public
  428. */
  429. pro.create_bucket = function(options,callback){
  430. bucket_filter(options);
  431. options['method'] = "PUT";
  432. options['x-oss-acl'] = options['x-oss-acl'] || con.OSS_ACL_TYPE_PRIVATE;
  433. this.authRequest(options,callback);
  434. }
  435. /**
  436. * Get_Bucket
  437. * get the list of objects in the bucket
  438. *
  439. * @param {
  440. * bucket {required}: bucketName,
  441. * prefix {optional}: prefix,
  442. * max-keys {optional}: max-keys,
  443. * marker {optional}: marker,
  444. * delimiter {optional}: delimiter
  445. * }
  446. * @return {cb}
  447. * @api public
  448. */
  449. pro.get_bucket = pro.list_object = function(options,callback){
  450. bucket_filter(options);
  451. options['method'] = "GET";
  452. this.authRequest(options,callback);
  453. }
  454. /**
  455. * Delete_Bucket
  456. * delete bucket in oss
  457. *
  458. * @param {
  459. * bucket {required}: bucketName
  460. * }
  461. * @return {cb}
  462. * @api public
  463. */
  464. pro.delete_bucket = function(options,callback){
  465. bucket_filter(options);
  466. options['method'] = "DELETE";
  467. this.authRequest(options,callback);
  468. }
  469. /**
  470. * Get_Bucket_Acl
  471. * get the acl of the bucket
  472. *
  473. * @param {
  474. * bucket {required}: bucketName
  475. * }
  476. * @return {cb}
  477. * @api public
  478. */
  479. pro.get_bucket_acl = function(options,callback){
  480. bucket_filter(options);
  481. options['method'] = "GET";
  482. options['oss-acl'] = "acl";
  483. this.authRequest(options,callback);
  484. }
  485. /**
  486. * Set_Bucket_Acl
  487. * set the bucket acl
  488. *
  489. * @param {
  490. * bucket {required}: bucketName,
  491. * headers {required} : {
  492. * "x-oss-acl" : acl
  493. * }
  494. * }
  495. * @return {cb}
  496. * @api public
  497. */
  498. pro.set_bucket_acl = function(options,callback){
  499. bucket_filter(options);
  500. options['method'] = "PUT";
  501. options['headers']['x-oss-acl'] = options['headers']['x-oss-acl'] || con.OSS_ACL_TYPE_PRIVATE;
  502. this.authRequest(options,callback);
  503. }
  504. /*
  505. ******************************************object operations**********************************
  506. */
  507. /**
  508. * Put_Object
  509. * put a object to a bucket in oss
  510. *
  511. * @param {
  512. * bucket {required}: bucketName,
  513. * object {required}: ossObjectName, { you can use / to create a directory in oss}
  514. * srcFile {required}: localObjectPath
  515. * }
  516. * @return {cb}
  517. * @api public
  518. */
  519. pro.put_object = function(options,callback){
  520. if(typeof options != "undefined"){
  521. if(typeof options['srcFile'] == "undefined"){
  522. throw new Error("put_object path is required");
  523. }
  524. bucket_filter(options);
  525. object_filter(options);
  526. }
  527. options['method'] = "PUT";
  528. options['action'] = "UPLOAD_OBJECT";
  529. written = 0;
  530. this.authRequest(options,callback);
  531. }
  532. /**
  533. * Get_Object
  534. * get the object
  535. *
  536. * @param {
  537. * bucket {required}: bucketName,
  538. * object {required}: ossObjectName,
  539. * dstFile {required}: downLoadObjectPath
  540. * }
  541. * @return {cb}
  542. * @api public
  543. */
  544. pro.get_object = function(options,callback){
  545. if(typeof options != "undefined"){
  546. if(typeof options['dstFile'] == "undefined"){
  547. throw new Error("get_object path is required");
  548. }
  549. bucket_filter(options);
  550. object_filter(options);
  551. }
  552. var self = this;
  553. self.head_object({
  554. bucket:options['bucket'],
  555. object:options['object']
  556. },function(err,result){
  557. options['filesize'] = result['response_header']['content-length'];
  558. options['method'] = "GET";
  559. self.authRequest(options,callback);
  560. })
  561. }
  562. /**
  563. * Copy_Object
  564. * copy object which can be in different bucket in oss
  565. *
  566. * @param {
  567. * bucket {required}: bucketName,
  568. * object {required}: ossObjectName,
  569. * copyBucket {required}: copyBucket,
  570. * copyObject {required}: copyObjectName
  571. * }
  572. * @return {cb}
  573. * @api public
  574. */
  575. pro.copy_object = function(options,callback){
  576. bucket_filter(options);
  577. object_filter(options);
  578. options['method'] = "PUT";
  579. if(typeof options["copyBucket"] == "undefined" || typeof options["copyObject"] == "undefined"){
  580. throw new Error("dstBucket and dstObject are both required");
  581. }
  582. options.headers = {};
  583. options['headers'][con.OSS_OBJECT_COPY_SOURCE] = "/" + options["copyBucket"] + "/" + options["copyObject"];
  584. this.authRequest(options,callback);
  585. }
  586. /**
  587. * Head_Object
  588. * get the meta infomation for the object like acl
  589. *
  590. * @param {
  591. * bucket {required}: bucketName,
  592. * object {required}: ossObjectName
  593. * }
  594. * @return {cb}
  595. * @api public
  596. */
  597. pro.head_object = function(options,callback){
  598. bucket_filter(options);
  599. object_filter(options);
  600. options['method'] = "HEAD";
  601. this.authRequest(options,callback);
  602. }
  603. /**
  604. * Delete_Object
  605. * delete an object in the bucket
  606. *
  607. * @param {
  608. * bucket {required}: bucketName,
  609. * object {required}: ossObjectName
  610. * }
  611. * @return {cb}
  612. * @api public
  613. */
  614. pro.delete_object = function(options,callback){
  615. bucket_filter(options);
  616. object_filter(options);
  617. options['method'] = "DELETE";
  618. this.authRequest(options,callback);
  619. }
  620. /**
  621. * Delete_Objects
  622. * delete many objects in the bucket
  623. *
  624. * @param {
  625. * bucket {required}: bucketName,
  626. * objects {required}: [ossObjectName1,ossObjectName2,...]
  627. * }
  628. * @return {cb}
  629. * @api public
  630. */
  631. pro.delete_objects = function(options,callback){
  632. bucket_filter(options);
  633. options['method'] = "POST";
  634. options[con.OSS_MULTI_DELETE] = "delete";
  635. options['quiet'] = options['quiet'] || "false";
  636. var objects = options['objects'];
  637. if(objects.length != 0){
  638. var xml_obj = {
  639. Quiet : options['quiet'],
  640. Object : []
  641. }
  642. for(var key in objects){
  643. xml_obj.Object.push({Key:objects[key]});
  644. }
  645. var xml_content = data2xml("Delete",xml_obj);
  646. options['body'] = xml_content;
  647. options['Content-type'] = 'application/xml';
  648. options['headers'] = {}
  649. options['headers']['Content-Length'] = xml_content.length;
  650. options['headers']['Content-MD5'] = crypto.createHash('md5').update(xml_content).digest('base64');
  651. this.authRequest(options,callback);
  652. }else{
  653. callback(null,"no objects in this bucket");
  654. }
  655. }
  656. /**
  657. * Create_Dir
  658. * create a dir in oss
  659. *
  660. * @param {
  661. * bucket {required}: bucketName,
  662. * dir {required}: dirName { with / in the end to represent a dir}
  663. * }
  664. * @return {cb}
  665. * @api public
  666. */
  667. pro.create_dir = function(options,callback){
  668. if(typeof options != "undefined"){
  669. bucket_filter(options);
  670. }
  671. options['method'] = "PUT";
  672. options['object'] = options['dir'] || '/';
  673. this.authRequest(options,callback);
  674. }
  675. /*
  676. ***************************************multipart operations******************************************
  677. */
  678. /**
  679. * Get_Multipart_Counts
  680. * divide a big file and get the parts array
  681. *
  682. * @param {
  683. * upload_filesize {required}: fileSize,
  684. * part_size {optional}: dividePartSize
  685. * }
  686. * @return {array}
  687. * @api private
  688. */
  689. pro.get_multipart_counts = function(upload_filesize,part_size){
  690. part_size = part_size || 5242880; // default 5M
  691. part_size = _.getPartSize(part_size);
  692. var sizeCount = upload_filesize;
  693. var values = [];
  694. var i = 0;
  695. while(sizeCount>0){
  696. sizeCount -= part_size;
  697. values.push({ seekTo : part_size*i,
  698. length : (sizeCount > 0) ? part_size : (sizeCount+part_size)
  699. });
  700. i++;
  701. }
  702. return values;
  703. }
  704. /**
  705. * Initiate_Mulipart_Upload
  706. * do initiation and get the upload_id
  707. *
  708. * @param {
  709. * bucket {required}: bucketName,
  710. * object {required}: ossObjectName
  711. * }
  712. * @return {cb}
  713. * @api private
  714. */
  715. pro.initiate_multipart_upload = function(options,callback){
  716. bucket_filter(options);
  717. object_filter(options);
  718. options['method'] = "POST";
  719. options[con.OSS_MULTI_PART] = "uploads";
  720. this.authRequest(options,callback);
  721. }
  722. /**
  723. * Initiate_Mulipart_Upload
  724. * do initiation and get the upload_id
  725. *
  726. * @param {
  727. * bucket {required}: bucketName,
  728. * object {required}: ossObjectName
  729. * }
  730. * @return {cb}
  731. * @api private
  732. */
  733. pro.upload_part = function(options,callback){
  734. bucket_filter(options);
  735. object_filter(options);
  736. if(typeof options['partNumber'] == "undefined" || typeof options['uploadId'] == "undefined"){
  737. throw new Error("partNumber and uploadId are both required");
  738. }
  739. options['method'] = "PUT";
  740. options['action'] = "UPLOAD_PART";
  741. this.authRequest(options,callback);
  742. }
  743. /**
  744. * Complete_Mulipart_Upload
  745. * mulipart_upload complete operation
  746. *
  747. * @param
  748. * @return {cb}
  749. * @api private
  750. */
  751. pro.complete_multipart_upload = function(options,callback){
  752. bucket_filter(options);
  753. object_filter(options);
  754. if(typeof options['uploadId'] == "undefined"){
  755. throw new Error("uploadId is required");
  756. }
  757. options['method'] = "POST";
  758. this.authRequest(options,callback);
  759. }
  760. /**
  761. * Mulipart_Upload_Object
  762. * mulipart_upload operation
  763. *
  764. * @param {
  765. * bucket {required}: bucketName,
  766. * object {required}: ossObjectName,
  767. * srcFile {required}: localObjectPath
  768. * }
  769. * @return {cb}
  770. * @api public
  771. */
  772. pro.multipart_upload_object = function(options,cb){
  773. bucket_filter(options);
  774. object_filter(options);
  775. if(typeof options['srcFile'] == "undefined"){
  776. throw new Error("upload object path is required");
  777. }
  778. written = 0;
  779. var srcFile = options['srcFile'];
  780. options['partSize'] = options['partSize'] || 5242880;
  781. var self = this;
  782. //var upload_filesize = 0;
  783. async.waterfall([
  784. function checkFile(callback){
  785. fs.stat(options.srcFile,function(err,stats){
  786. if(err) throw err;
  787. callback(err,stats,options.srcFile);
  788. });
  789. },
  790. function getFileSize(stats,file,callback){
  791. if(stats.isFile()){
  792. //upload_filesize = stats.size;
  793. options['filesize'] = stats.size;
  794. callback(null,stats.size,file);
  795. }else{
  796. throw new Error("file is not exist");
  797. }
  798. },
  799. function filterFileUpload(filesize,file,callback){
  800. options['partSize'] = _.getPartSize(options['partSize']);
  801. if(filesize <= 52428800*2){ // if it is not a big file ,simple upload it
  802. self.put_object(options,function(err,result){
  803. cb(err,result);
  804. return;
  805. });
  806. }else{ // multipart_upload_file
  807. options['srcFile'] = undefined;
  808. self.initiate_multipart_upload(options,function(err,result){
  809. var pieces = self.get_multipart_counts(filesize,options['partSize']);
  810. options['uploadId'] = result['InitiateMultipartUploadResult']['UploadId'];
  811. options[con.OSS_MULTI_PART] = undefined;
  812. options['srcFile'] = srcFile;
  813. callback(err,result['InitiateMultipartUploadResult']['UploadId'],pieces);
  814. })
  815. }
  816. },
  817. function uploadFilePart(uploadId,pieces,callback){
  818. var i = 0;
  819. var parts = [];
  820. async.whilst(
  821. function(){ return i < pieces.length; },
  822. function(_cb){
  823. options['partNumber'] = i+1;
  824. if(typeof options['headers'] == "undefined"){
  825. options['headers'] = {};
  826. }
  827. options['headers']['Content-Length'] = pieces[i]['length'];
  828. options['seekTo'] = pieces[i]['seekTo'];
  829. options['upload_length'] = pieces[i]['length'];
  830. self.upload_part(options,function(err,result){
  831. if(result){
  832. parts.push({partNumber:i+1,etag:result['response_header']['etag']});
  833. i++;
  834. _cb(err,result);
  835. }
  836. })
  837. },
  838. function(err){
  839. delete pieces;
  840. callback(null,parts);
  841. }
  842. );
  843. },
  844. function completeMultipartUpload(parts,callback){
  845. var xml_obj = {
  846. Part : []
  847. }
  848. for(var key in parts){
  849. xml_obj.Part.push({PartNumber:parts[key]['partNumber'],ETag:parts[key]['etag']});
  850. }
  851. var xml_content = data2xml("CompleteMultipartUpload",xml_obj);
  852. delete xml_obj;
  853. delete parts;
  854. options['partNumber'] = undefined;
  855. options['body'] = xml_content;
  856. options['action'] = undefined;
  857. options['Content-type'] = 'application/xml';
  858. options['headers'] = {}
  859. options['headers']['Content-Length'] = xml_content.length;
  860. options['headers']['Content-MD5'] = crypto.createHash('md5').update(xml_content).digest('base64');
  861. delete xml_content;
  862. self.complete_multipart_upload(options,function(err,result){
  863. callback(err,result);
  864. })
  865. }
  866. ],function(err,result){
  867. cb(err,result);
  868. })
  869. }
  870. /**
  871. * Abort_Multipart_Upload
  872. * when using multipart_upload ,you can abort the process by using this api
  873. *
  874. * @param {
  875. * bucket {required}: bucketName,
  876. * object {required}: ossObjectName,
  877. * uploadId {required}: mulipartUploadId
  878. * }
  879. * @return {cb}
  880. * @api public
  881. */
  882. pro.abort_multipart_upload = function(options,callback){
  883. bucket_filter(options);
  884. object_filter(options);
  885. if(typeof options['uploadId'] == "undefined"){
  886. throw new Error("uploadId is required");
  887. }
  888. options['method'] = "DELETE";
  889. this.authRequest(options,callback);
  890. }
  891. /**
  892. * List_Multipart_Uploads
  893. * you can list the object by using mulipart_upload in the bucket
  894. *
  895. * @param {
  896. * bucket {required}: bucketName
  897. * }
  898. * @return {cb}
  899. * @api public
  900. */
  901. pro.list_multipart_uploads = function(options,callback){
  902. bucket_filter(options);
  903. options['method'] = "GET";
  904. options[con.OSS_MULTI_PART] = "uploads";
  905. this.authRequest(options,callback);
  906. }
  907. /**
  908. * List_Parts
  909. * list mulipart_upload parts
  910. *
  911. * @param {
  912. * bucket {required}: bucketName,
  913. * object {required}: ossObjectName,
  914. * uploadId {required}: multipartUploadId
  915. * }
  916. * @return {cb}
  917. * @api public
  918. */
  919. pro.list_parts = function(options,callback){
  920. bucket_filter(options);
  921. object_filter(options);
  922. if(typeof options['uploadId'] == "undefined"){
  923. throw new Error("uploadId is required");
  924. }
  925. options['method'] = "GET";
  926. this.authRequest(options,callback);
  927. }
  928. /*
  929. *******************************************object group operations*************************************
  930. */
  931. /**
  932. * Create_Object_Group
  933. * softly link some objects to become a big one
  934. *
  935. * @param {
  936. * bucket {required}: bucketName,
  937. * object {required}: ossObjectGroupName,
  938. * objects {required}: [ossObject1,ossObject2,...]
  939. * }
  940. * @return {cb}
  941. * @api public
  942. */
  943. pro.create_object_group = function(options,callback){
  944. bucket_filter(options);
  945. object_filter(options);
  946. if(typeof options['objects'] == "undefined"){
  947. throw new Error("object_group objects are required");
  948. }
  949. options['method'] = "POST";
  950. options[con.OSS_OBJECT_GROUP] = "group";
  951. var self = this;
  952. var objects = options['objects'];
  953. var i = 0;
  954. var xml_obj = {
  955. Part : []
  956. }
  957. var xml_content = "";
  958. async.whilst(
  959. function(){ return i<objects.length; },
  960. function(_cb){
  961. self.head_object({bucket:options["bucket"],object:objects[i]},function(err,result){
  962. xml_obj.Part.push({PartNumber:(i+1),PartName:objects[i],ETag:result['response_header']['etag']});
  963. i++;
  964. _cb(err,result);
  965. })
  966. },
  967. function(err){
  968. xml_content = data2xml("CreateFileGroup",xml_obj);
  969. options['body'] = xml_content;
  970. options['Content-type'] = 'application/xml';
  971. options['headers'] = {}
  972. options['headers']['Content-Length'] = xml_content.length;
  973. options['headers']['Content-MD5'] = crypto.createHash('md5').update(xml_content).digest('base64');
  974. self.authRequest(options,callback);
  975. }
  976. );
  977. }
  978. /**
  979. * Get_Object_Group
  980. * object group is the same as simple oss object
  981. *
  982. * @param {
  983. * bucket {required}: bucketName,
  984. * object {required}: ossObjectName,
  985. * dstFile {required}: downLoadObjectPath
  986. * }
  987. * @return {cb}
  988. * @api public
  989. */
  990. pro.get_object_group = pro.get_object;
  991. /**
  992. * Get_Object_Group_Index
  993. * get the index of object_group
  994. *
  995. * @param {
  996. * bucket {required}: bucketName,
  997. * object {required}: ossObjectName
  998. * }
  999. * @return {cb}
  1000. * @api public
  1001. */
  1002. pro.get_object_group_index = function(options,callback){
  1003. bucket_filter(options);
  1004. object_filter(options);
  1005. options['method'] = "GET";
  1006. options['headers'] = {};
  1007. options['headers']['x-oss-file-group'] = undefined;
  1008. this.authRequest(options,callback);
  1009. }
  1010. /**
  1011. * Head_Object_Group
  1012. * get the meta infomation of the object_group
  1013. *
  1014. * @param {
  1015. * bucket {required}: bucketName,
  1016. * object {required}: ossObjectName
  1017. * }
  1018. * @return {cb}
  1019. * @api public
  1020. */
  1021. pro.head_object_group = pro.head_object;
  1022. /**
  1023. * Delete_Object_Group
  1024. * delete the object_group
  1025. *
  1026. * @param {
  1027. * bucket {required}: bucketName,
  1028. * object {required}: ossObjectName
  1029. * }
  1030. * @return {cb}
  1031. * @api public
  1032. */
  1033. pro.delete_object_group = pro.delete_object;
  1034. /**
  1035. *****************************************************other useful functions*******************************
  1036. */
  1037. /**
  1038. * Upload_Objects_By_Dir
  1039. * you can upload local dir files to oss
  1040. *
  1041. * @param {
  1042. * bucket {required}: bucketName,
  1043. * ossDir {required}: ossDirName,
  1044. * local {required}: localDirPath
  1045. * }
  1046. * @return {cb}
  1047. * @api public
  1048. */
  1049. pro.upload_objects_by_dir = function(options,callback){
  1050. if(typeof options['local'] == "undefined"){
  1051. throw new Error("local dir is required");
  1052. }
  1053. var self = this;
  1054. var _path = options['local'];
  1055. var bucket = options['bucket'];
  1056. var ossDir = options['ossDir'];
  1057. var _files = [];
  1058. fs.stat(_path,function(err,stats){
  1059. if(stats.isDirectory()){
  1060. var walker = ndir.walk(_path);
  1061. walker.on('dir', function(dirpath, files) {
  1062. for (var i = 0, l = files.length; i < l; i++) {
  1063. var info = files[i];
  1064. if (info[1].isFile()) {
  1065. console.log(info[0]);
  1066. _files.push(info[0]);
  1067. }
  1068. }
  1069. });
  1070. walker.on('end',function(){
  1071. var _i = 0;
  1072. async.whilst(
  1073. function(){ return _i<_files.length; },
  1074. function(_cb){
  1075. options = {};
  1076. options['bucket'] = bucket;
  1077. options['srcFile'] = _files[_i];
  1078. if(ossDir){
  1079. if(ossDir[ossDir.length-1] == '/'){
  1080. options['object'] = ossDir + _.getFileName(_files[_i]);
  1081. }else{
  1082. options['object'] = ossDir + '/' + _.getFileName(_files[_i]);
  1083. }
  1084. }else{
  1085. options['object'] = _.getFileName(_files[_i]);
  1086. }
  1087. self.multipart_upload_object(options,function(err,_res){
  1088. _i++;
  1089. _cb(err,_res);
  1090. });
  1091. },
  1092. function(err){
  1093. callback(err,"upload_objects_by_dir good");
  1094. }
  1095. );
  1096. });
  1097. }else{
  1098. throw new Error("local dir is not a directory");
  1099. }
  1100. });
  1101. }
  1102. /**
  1103. * Sync_Local_Dir
  1104. * similar to upload_objects_by_dir the differene is the dir will also be created in oss
  1105. *
  1106. * @param {
  1107. * bucket {required}: bucketName,
  1108. * ossDir {required}: ossDirName,
  1109. * local {required}: localDirPath
  1110. * }
  1111. * @return {cb}
  1112. * @api public
  1113. */
  1114. pro.sync_local_dir = function(options,callback){
  1115. if(typeof options['local'] == "undefined"){
  1116. throw new Error("local dir is required");
  1117. }
  1118. var self = this;
  1119. var _path = options['local'];
  1120. var bucket = options['bucket'];
  1121. var ossDir = options['ossDir'];
  1122. var _files = [];
  1123. var _dirname = path.resolve(_path);
  1124. if(_dirname[_dirname.length-1] != '/'){
  1125. _dirname = _dirname + '/';
  1126. }
  1127. fs.stat(_path,function(err,stats){
  1128. if(stats.isDirectory()){
  1129. var walker = ndir.walk(_path);
  1130. walker.on('dir', function(dirpath, files) {
  1131. for (var i = 0, l = files.length; i < l; i++) {
  1132. var info = files[i];
  1133. if (info[1].isFile()) {
  1134. _files.push(info[0]);
  1135. }
  1136. }
  1137. });
  1138. walker.on('end',function(){
  1139. var _i = 0;
  1140. async.whilst(
  1141. function(){ return _i<_files.length; },
  1142. function(_cb){
  1143. options = {};
  1144. options['bucket'] = bucket;
  1145. options['srcFile'] = _files[_i];
  1146. if(ossDir){
  1147. if(ossDir[ossDir.length-1] == '/'){
  1148. options['object'] = ossDir + _.getAbsoluteFileName(_dirname,_files[_i]);
  1149. }else{
  1150. options['object'] = ossDir + '/' + _.getAbsoluteFileName(_dirname,_files[_i]);
  1151. }
  1152. }else{
  1153. options['object'] = _.getAbsoluteFileName(_dirname,_files[_i]);
  1154. }
  1155. console.log('');
  1156. console.log(options['object']);
  1157. self.multipart_upload_object(options,function(err,_res){
  1158. _i++;
  1159. _cb(err,_res);
  1160. });
  1161. },
  1162. function(err){
  1163. callback(err,"\nsync_local_dir good");
  1164. }
  1165. );
  1166. });
  1167. }else{
  1168. throw new Error("local dir is not a directory");
  1169. }
  1170. });
  1171. }
  1172. /*
  1173. pro.get_sign_url = function(options,callback){
  1174. if(typeof options != "undefined"){
  1175. if(typeof options['dstFile'] == "undefined"){
  1176. throw new Error("get_object path is required");
  1177. }
  1178. bucket_filter(options);
  1179. object_filter(options);
  1180. }
  1181. options['action'] == 'GET_SIGN_URL';
  1182. this.authRequest(options,callback);
  1183. }
  1184. */