'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.doDelete = exports.put = exports.post = exports.get = exports.closeSession = exports.saveSession = exports.loadSession = exports.replaceSession = exports.getSession = undefined; exports.uploadFile = uploadFile; var _nodeFetch = require('node-fetch'); var _nodeFetch2 = _interopRequireDefault(_nodeFetch); var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs); var _request = require('request'); var _request2 = _interopRequireDefault(_request); var _progress = require('progress'); var _progress2 = _interopRequireDefault(_progress); var _package = require('../package.json'); var _package2 = _interopRequireDefault(_package); var _tcpPing = require('tcp-ping'); var _tcpPing2 = _interopRequireDefault(_tcpPing); var _util = require('util'); var _util2 = _interopRequireDefault(_util); var _path = require('path'); var _path2 = _interopRequireDefault(_path); var _filesizeParser = require('filesize-parser'); var _filesizeParser2 = _interopRequireDefault(_filesizeParser); var _utils = require('./utils'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const defaultEndpoint = 'https://update.reactnative.cn/api'; let host = process.env.PUSHY_REGISTRY || defaultEndpoint; const tcpPing = _util2.default.promisify(_tcpPing2.default.ping); let session = undefined; let savedSession = undefined; const userAgent = `react-native-update-cli/${_package2.default.version}`; const getSession = exports.getSession = function () { return session; }; const replaceSession = exports.replaceSession = function (newSession) { session = newSession; }; const loadSession = exports.loadSession = async function () { if (_fs2.default.existsSync('.update')) { try { replaceSession(JSON.parse(_fs2.default.readFileSync('.update', 'utf8'))); savedSession = session; } catch (e) { console.error('Failed to parse file `.update`. Try to remove it manually.'); throw e; } } }; const saveSession = exports.saveSession = function () { // Only save on change. if (session !== savedSession) { const current = session; const data = JSON.stringify(current, null, 4); _fs2.default.writeFileSync('.update', data, 'utf8'); savedSession = current; } }; const closeSession = exports.closeSession = function () { if (_fs2.default.existsSync('.update')) { _fs2.default.unlinkSync('.update'); savedSession = undefined; } session = undefined; host = process.env.PUSHY_REGISTRY || defaultEndpoint; }; async function query(url, options) { const resp = await (0, _nodeFetch2.default)(url, options); const text = await resp.text(); let json; try { json = JSON.parse(text); } catch (e) { throw new Error(`Server error: ${text}`); } if (resp.status !== 200) { throw Object.assign(new Error(json.message || json.error), { status: resp.status }); } return json; } function queryWithoutBody(method) { return function (api) { return query(host + api, { method, headers: { 'User-Agent': userAgent, 'X-AccessToken': session ? session.token : '' } }); }; } function queryWithBody(method) { return function (api, body) { return query(host + api, { method, headers: { 'User-Agent': userAgent, 'Content-Type': 'application/json', 'X-AccessToken': session ? session.token : '' }, body: JSON.stringify(body) }); }; } const get = exports.get = queryWithoutBody('GET'); const post = exports.post = queryWithBody('POST'); const put = exports.put = queryWithBody('PUT'); const doDelete = exports.doDelete = queryWithBody('DELETE'); async function uploadFile(fn, key) { const { url, backupUrl, formData, maxSize } = await post('/upload', { ext: _path2.default.extname(fn) }); let realUrl = url; if (backupUrl) { if (global.USE_ACC_OSS) { realUrl = backupUrl; } else { const pingResult = await tcpPing({ address: url.replace('https://', ''), attempts: 4, timeout: 1000 }); // console.log({pingResult}); if (isNaN(pingResult.avg) || pingResult.avg > 150) { realUrl = backupUrl; } } // console.log({realUrl}); } const fileSize = _fs2.default.statSync(fn).size; if (maxSize && fileSize > (0, _filesizeParser2.default)(maxSize)) { throw new Error(`此文件大小${(fileSize / 1048576).toFixed(1)}m, 超出当前额度${maxSize}。您可以考虑升级付费业务以提升此额度。详情请访问: ${_utils.pricingPageUrl}`); } const bar = new _progress2.default(' 上传中 [:bar] :percent :etas', { complete: '=', incomplete: ' ', total: fileSize }); const info = await new Promise((resolve, reject) => { if (key) { formData.key = key; } formData.file = _fs2.default.createReadStream(fn); formData.file.on('data', function (data) { bar.tick(data.length); }); _request2.default.post(realUrl, { formData }, (err, resp, body) => { if (err) { return reject(err); } if (resp.statusCode > 299) { return reject(Object.assign(new Error(body), { status: resp.statusCode })); } resolve({ hash: formData.key }); }); }); return info; }