All files index.js

88.89% Statements 192/216
81.59% Branches 164/201
92.59% Functions 25/27
88.57% Lines 186/210
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 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579    1x     1x   1x   1x   1x   1x   1x   1x   1x   6x                                 5038x 1x       5037x       5037x 5037x   5037x 8x             8x     8x     8x 2x 2x 2x   2x 2x     5029x       5029x 5029x   5029x 27x       6x 6x       17x 17x 14x                   15x 1x       8x 5x 5x   5x 2x       14x 11x                 5062x     14x   14x 1x       13x   13x   13x 5062x 5062x   5062x 5055x               5062x   13x 13x                       17x 17x   17x 17x 28x 12x   5x     5x   5x 5x 4x       1x                                                                     20x                       20x 1x     19x 2x 2x     2x     17x 17x   17x 11x 10x   10x 7x 7x       10x 5046x   5046x     17x       5029x         10x 10x 20x   20x 3x             16x 13x     16x 16x             3x 3x 3x     3x       3x 3x                         13x 13x 10x       13x 13x           3x 3x 3x     3x 3x                             10x                                 3x             3x 3x 3x 3x     7x 7x 7x   7x 7x 7x     7x                                   3x 2x       1x 1x 1x   1x 7x   7x         7x         1x 1x                 1x 1x   1x 1x 1x                                 31x 1x     30x       30x   22x 9x       25x 9289x     5x     13x   13x 12x 12x 12x     13x                   12x 1x     11x   11x 1x     10x   10x 5025x   3x 3x                   7x   7x 9x 9x 9x 9x   9x             9x         7x 7x 7x               4x 1x     3x           3x         1x 1x
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
 
var _lodash = require("lodash");
 
var _async = _interopRequireDefault(require("async"));
 
var _aliOss = _interopRequireDefault(require("ali-oss"));
 
var _fsExtraPromise = _interopRequireDefault(require("fs-extra-promise"));
 
var _isThere = _interopRequireDefault(require("is-there"));
 
var _moment = _interopRequireDefault(require("moment"));
 
var _walk = _interopRequireDefault(require("walk"));
 
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
 
class OSSExtra extends _aliOss.default {
  async putList(fileList, {
    thread = 10,
    defaultHeader = {},
    headersMap = new Map(),
    bigFile = 1024 * 500,
    partSize = 1024 * 500,
    timeout = 120 * 1000,
    ulimit = 1024,
    verbose = false
  } = {}, {
    putResultsMap = new Map(),
    checkPointMap = new Map(),
    uploadFilesMap = new Map()
  } = {}) {
    if (fileList.some(f => typeof f !== 'object' || !f.src || !f.dst || typeof f.src !== 'string' || typeof f.dst !== 'string' || typeof f.size !== 'number')) {
      throw new Error('putList: Incorrect input!');
    }
 
    async function putFile(file) {
      Iif (putResultsMap.has(file.dst)) {
        return;
      }
 
      try {
        const headers = Object.assign({}, defaultHeader, headersMap.get(file.dst));
 
        if (file.size >= bigFile) {
          const multiOptions = {
            headers,
            progress: function* (_, checkPoint) {
              checkPointMap.set(file.dst, checkPoint);
            }
          };
 
          Iif (checkPointMap.has(file.dst)) {
            multiOptions.checkpoint = (0, _lodash.cloneDeep)(checkPointMap.get(file.dst));
          } else {
            multiOptions.partSize = Math.max(Math.ceil(file.size / ulimit), partSize);
          }
 
          const result = await this.multipartUpload(file.dst, file.src, multiOptions);
          checkPointMap.delete(file.dst);
          uploadFilesMap.delete(file.dst);
          putResultsMap.set(file.dst, result);
 
          Eif (verbose) {
            console.log(`Uploaded: ${file.dst}, Remaining: ${uploadFilesMap.size}`);
          }
        } else {
          const result = await this.put(file.dst, file.src, {
            headers,
            timeout
          });
          uploadFilesMap.delete(file.dst);
          putResultsMap.set(file.dst, result);
 
          if (verbose) {
            console.log(`Uploaded: ${file.dst}, Remaining: ${uploadFilesMap.size}`);
          }
        }
      } catch (err) {
        err.checkPointMap = checkPointMap;
        throw err;
      }
    }
 
    fileList = (0, _lodash.sortBy)(fileList, 'size');
    await _async.default.mapLimit(fileList, thread, putFile.bind(this));
    return [...putResultsMap.values()];
  }
 
  async deleteList(fileList, {
    thread = 20,
    verbose = false
  } = {}, {
    deleteResults = [],
    deleteFilesMap = new Map()
  } = {}) {
    if (fileList.some(f => typeof f !== 'object' || !f.name || typeof f.name !== 'string')) {
      throw new Error('deleteList: Incorrect input!');
    }
 
    async function deleteFile(file) {
      const result = await this.delete(file.name);
      deleteFilesMap.delete(file.name);
      deleteResults.push(result);
 
      if (verbose) {
        console.log(`Deleted: ${file.name}, Remaining: ${deleteFilesMap.size}`);
      }
    }
 
    await _async.default.mapLimit(fileList, thread, deleteFile.bind(this));
    return deleteResults;
  }
  /**
   * Get a map of local files.
   */
 
 
  async _getLocalFilesMap(directory, prefix, ignoreList = []) {
    function isIgnore(src) {
      return ignoreList.some(dir => src.startsWith(`${directory}/${dir}/`) || src === `${directory}/${dir}`);
    }
 
    return new Promise((resolve, reject) => {
      // a. check if directory exists
      if (!(0, _isThere.default)(directory)) {
        return reject(new Error(`Path ${directory} does not exist!`));
      } // b. construct list of local files
 
 
      const localFiles = new Map();
 
      const walker = _walk.default.walk(directory);
 
      walker.on('file', (root, stat, next) => {
        const dst = `${prefix}${root.substr(directory.length)}/${stat.name}`;
        const src = `${root}/${stat.name}`;
 
        if (!isIgnore(src)) {
          localFiles.set(dst, {
            dst,
            src,
            mtime: stat.mtime.toISOString(),
            size: stat.size
          });
        }
 
        next();
      });
      walker.on('end', async () => {
        resolve(localFiles);
      });
    });
  }
  /**
   * Get a map of cloud files.
   */
 
 
  async _getCloudFilesMap(prefix, options = {
    retryLimit: null
  }, meta = {}) {
    const cloudFiles = new Map();
    const trial = (meta.trial || 0) + 1;
 
    try {
      const cloudFileList = await this.listDir(prefix, ['name', 'lastModified']);
      cloudFileList.forEach(f => cloudFiles.set(f.name, f));
      return cloudFiles;
    } catch (err) {
      Eif (err && (err.name === 'ResponseTimeoutError' || err.name === 'ConnectionTimeoutError' || err.name === 'RequestError' || err.name === 'ResponseError')) {
        const {
          retryLimit
        } = options;
 
        Eif (retryLimit && Number.isInteger(retryLimit)) {
          if (trial < retryLimit) {
            return this._getCloudFilesMap(prefix, options, {
              trial
            });
          } else {
            throw new Error('Retry limit exceeded!');
          }
        } else {
          return this._getCloudFilesMap(prefix);
        }
      } else {
        throw err;
      }
    }
  }
  /**
   * As in:
   * s3 sync ${directory} s3://bucket/${prefix} --delete
   */
 
 
  async syncDir(directory, prefix, {
    remove = true,
    ignoreList = [],
    defaultHeader = {},
    headersMap = new Map(),
    retryLimit = null,
    thread = 10,
    timeout = 120 * 1000,
    ulimit = 1024,
    verbose = false
  } = {}, {
    retrying = false,
    putResultsMap = new Map(),
    deleteResults = [],
    checkPointMap = new Map(),
    uploadFilesMap = new Map(),
    deleteFilesMap = new Map(),
    trial = 0
  } = {}) {
    const options = {
      remove,
      ignoreList,
      defaultHeader,
      headersMap,
      retryLimit,
      thread,
      timeout,
      ulimit,
      verbose
    };
 
    if (typeof directory !== 'string' || typeof prefix !== 'string') {
      throw new Error('syncDir: Incorrect input!');
    }
 
    if (retryLimit && Number.isInteger(retryLimit) && trial > retryLimit) {
      Eif (verbose) {
        console.error('syncDir: Retry limit exceeded!');
      }
 
      throw new Error('Retry limit exceeded!');
    }
 
    let localFilesMap = new Map();
    let cloudFilesMap = new Map(); // 1. Get local and cloud files, if not retrying
 
    if (!retrying) {
      localFilesMap = await this._getLocalFilesMap(directory, prefix, ignoreList);
      cloudFilesMap = await this._getCloudFilesMap(prefix, options);
 
      if (verbose) {
        console.log(`Local files: ${localFilesMap.size}`);
        console.log(`Cloud files: ${cloudFilesMap.size}`);
      } // 2. Prepare a list of files to upload
 
 
      for (const f of localFilesMap.values()) {
        const existed = cloudFilesMap.get(f.dst);
 
        if (existed) {
          // sometimes, clocks in oss servers are 2s slower,
          // adding the round off error, so about 5s is needed
          Iif ((0, _moment.default)(f.mtime).isAfter((0, _moment.default)(existed.lastModified).add(5, 's'))) {
            uploadFilesMap.set(f.dst, f);
          }
        } else {
          uploadFilesMap.set(f.dst, f);
        }
      } // 3. Prepare a list of files to remove
 
 
      Eif (remove) {
        for (const f of cloudFilesMap.values()) {
          const existed = localFilesMap.get(f.name);
 
          if (!existed) {
            deleteFilesMap.set(f.name, f);
          }
        }
      }
    } // 3. Put a list of files to OSS
 
 
    if (verbose) {
      console.log(`Files to upload: ${uploadFilesMap.size}`);
    }
 
    try {
      await this.putList([...uploadFilesMap.values()], options, {
        putResultsMap,
        checkPointMap,
        uploadFilesMap
      });
    } catch (err) {
      // catch the request or response or timeout errors, and re-try
      Eif (err && (err.name === 'ResponseTimeoutError' || err.name === 'ConnectionTimeoutError' || err.name === 'RequestError' || err.name === 'ResponseError' || err.name === 'NoSuchUploadError')) {
        Eif (verbose) {
          console.log(`Upload ${err.name}, retrying...`);
        }
 
        Iif (err.name === 'NoSuchUploadError') {
          err.checkPointMap.delete(err.params.object);
        }
 
        trial++;
        return this.syncDir(directory, prefix, options, {
          retrying: true,
          trial,
          putResultsMap,
          checkPointMap: err.checkPointMap,
          uploadFilesMap,
          deleteFilesMap
        });
      } else {
        throw err;
      }
    }
 
    Eif (remove) {
      if (verbose) {
        console.log(`Files to delete: ${deleteFilesMap.size}`);
      } // 5. Delete a list of files from OSS
 
 
      try {
        await this.deleteList([...deleteFilesMap.values()], options, {
          deleteResults,
          deleteFilesMap
        });
      } catch (err) {
        // catch the request or response or timeout errors, and re-try
        Eif (err && (err.name === 'ResponseTimeoutError' || err.name === 'ConnectionTimeoutError' || err.name === 'RequestError' || err.name === 'ResponseError')) {
          Eif (verbose) {
            console.log(`Delete ${err.name}, retrying...`);
          }
 
          trial++;
          return this.syncDir(directory, prefix, options, {
            retrying: true,
            trial,
            putResultsMap,
            deleteResults,
            checkPointMap,
            uploadFilesMap,
            deleteFilesMap
          });
        } else {
          throw err;
        }
      }
    }
 
    return {
      put: (0, _lodash.uniqBy)([...putResultsMap.values()], 'name'),
      delete: (0, _lodash.uniqBy)(deleteResults, 'res.requestUrls[0]')
    };
  }
  /**
   * Recursively download from the prefix and store all files in a local directory.
   */
 
 
  async syncDirDown(prefix, directory, {
    remove = true,
    thread = 10,
    timeout = 120 * 1000,
    ulimit = 1024,
    verbose = false
  } = {}) {
    const options = {
      remove,
      thread,
      timeout,
      ulimit,
      verbose
    };
    let localFilesMap = new Map();
    let cloudFilesMap = new Map();
    const downloadFilesMap = new Map();
    const deleteFilesMap = new Map();
 
    async function getFile(file) {
      const localFilePath = `${directory}${file.name.substr(prefix.length)}`;
      await _fsExtraPromise.default.ensureFileAsync(localFilePath);
      await this.get(file.name, localFilePath);
 
      Eif (verbose) {
        downloadFilesMap.delete(file.name);
        console.log(`Downloaded: ${localFilePath}, Remaining: ${downloadFilesMap.size}`);
      }
 
      return file.name;
    }
 
    async function deleteFile(file, done) {
      try {
        await _fsExtraPromise.default.removeAsync(file.src);
 
        if (verbose) {
          deleteFilesMap.delete(file.dst);
          console.log(`Deleted: ${file.src}, Remaining: ${deleteFilesMap.size}`);
        }
 
        done(null, file.src);
      } catch (err) {
        done(err);
      }
    }
 
    if (typeof directory !== 'string' || typeof prefix !== 'string') {
      throw new Error('syncDirDown: Incorrect input!');
    } // 1. Get local and cloud files
 
 
    cloudFilesMap = await this._getCloudFilesMap(prefix, options);
    await _fsExtraPromise.default.ensureDirAsync(directory);
    localFilesMap = await this._getLocalFilesMap(directory, prefix); // 2. Prepare a list of cloud files to download
 
    for (const f of cloudFilesMap.values()) {
      const existed = localFilesMap.get(f.name);
 
      Iif (existed) {
        if ((0, _moment.default)(f.lastModified).isAfter((0, _moment.default)(existed.mtime).add(1, 's'))) {
          downloadFilesMap.set(f.name, f);
        }
      } else {
        downloadFilesMap.set(f.name, f);
      }
    } // 3. Prepare a list of local files to remove
 
 
    Eif (remove) {
      for (const f of localFilesMap.values()) {
        const existed = cloudFilesMap.get(f.dst);
 
        if (!existed) {
          deleteFilesMap.set(f.dst, f);
        }
      }
    }
 
    const downloadFiles = (0, _lodash.sortBy)([...downloadFilesMap.values()], 'name');
    const getResults = await _async.default.mapLimit(downloadFiles, thread, getFile.bind(this));
 
    Eif (remove) {
      const deleteResults = await _async.default.mapLimit(deleteFilesMap.values(), thread, deleteFile.bind(this));
      return {
        get: getResults,
        delete: deleteResults
      };
    } else {
      return {
        get: getResults
      };
    }
  }
  /**
   * Get all the files of a directory recursively.
   * Return [] if not found.
   */
 
 
  async listDir(prefix, projection = []) {
    if (typeof prefix !== 'string') {
      throw new Error('listDir: Incorrect input!');
    }
 
    const query = {
      prefix,
      'max-keys': 1000
    };
    let result = await this.list(query);
 
    if (!result.objects) {
      return [];
    }
 
    function project(files) {
      if (projection.length) {
        return files.map(f => (0, _lodash.pick)(f, projection));
      }
 
      return files;
    }
 
    let allFiles = [...project(result.objects)];
 
    while (result.nextMarker) {
      query.marker = result.nextMarker;
      result = await this.list(query);
      allFiles = [...allFiles, ...project(result.objects)];
    }
 
    return allFiles;
  }
  /**
   * Delete a directory on OSS recursively.
   */
 
 
  async deleteDir(prefix, {
    retryLimit = null
  } = {}, meta = {}) {
    if (typeof prefix !== 'string') {
      throw new Error('deleteDir: Incorrect input!');
    }
 
    const trial = (meta.trial || 0) + 1;
 
    if (retryLimit && Number.isInteger(retryLimit) && trial > retryLimit) {
      throw new Error('Retry limit exceeded!');
    }
 
    let objects = [];
 
    try {
      objects = (await this.listDir(prefix, ['name'])).map(x => x.name);
    } catch (err) {
      Eif (err && (err.name === 'ResponseTimeoutError' || err.name === 'ConnectionTimeoutError' || err.name === 'RequestError' || err.name === 'ResponseError')) {
        return this.deleteDir(prefix, {
          retryLimit
        }, {
          trial
        });
      } else {
        throw err;
      }
    }
 
    let results = [];
 
    const cargo = _async.default.cargo(async (tasks, done) => {
      try {
        const data = await this.deleteMulti(tasks);
        results = [...results, ...data.deleted];
        done(null, data);
      } catch (err) {
        Iif (err && (err.name === 'ResponseTimeoutError' || err.name === 'ConnectionTimeoutError' || err.name === 'RequestError' || err.name === 'ResponseError')) {
          return this.deleteDir(prefix, {
            retryLimit
          }, {
            trial
          });
        } else {
          throw err;
        }
      }
    }, 1000);
 
    cargo.push(objects);
    await cargo.drain();
    return results;
  }
  /**
   * Set the content-disposition header of a file.
   */
 
 
  async setDownloadName(file, downloadName) {
    if (typeof file !== 'string' || typeof downloadName !== 'string') {
      throw new Error('setDownloadName: Incorrect input!');
    }
 
    const options = {
      headers: {
        'Content-Type': 'binary/octet-stream',
        'Content-Disposition': `attachment; filename="${encodeURIComponent(downloadName)}"`
      }
    };
    return this.copy(file, file, options);
  }
 
}
 
var _default = OSSExtra;
exports.default = _default;