"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.uploadByCos=void 0;const tslib_1=require("tslib"),url_config_1=require("../config/url.config"),tools_1=require("../utils/tools"),request_1=require("../utils/request"),sign_1=require("../utils/sign"),pack_1=require("./utils/pack"),config_1=require("../config/config"),upload_1=require("./upload"),log=tslib_1.__importStar(require("../utils/log")),jsonParse_1=require("../utils/jsonParse"),zlib=require("zlib"),crypto=require("crypto"),COS=require("cos-nodejs-sdk-v5");async function putBufferToCos(e,r){const t=new COS({Proxy:(0,request_1.getCiProxy)(),getAuthorization(e,t){t({TmpSecretId:r.secret_id,TmpSecretKey:r.secret_key,XCosSecurityToken:r.token,ExpiredTime:r.expired_time})}});try{return await new Promise((o,i)=>{t.putObject({Bucket:r.bucket,Region:"ap-shanghai",Key:r.object,Body:e,onProgress(e){}},(e,r)=>{if(e)return console.error(e),i(e.error);o(r)})})}catch(e){throw new Error("upload to cos failed: "+e.message)}}async function innerRequest(e,r){const t=await(0,request_1.request)({url:e,method:"post",body:r,headers:{"content-type":"application/json"}});let o;try{o=JSON.parse(t.body)}catch(r){const t=`request ${e} failed: resp body is not a valid json`;throw log.error(t),new Error(t)}if(0!==o.errCode)throw new Error(`request failed, errCode: ${o.errCode}, errMsg: ${o.errMsg}`);return o.data}async function uploadByCos(e,r,t,o){let i;try{const e=await(0,sign_1.getSignature)(t.privateKey,t.appid);i=await innerRequest(url_config_1.GET_UPLOAD_TOKEN,JSON.stringify({appid:t.appid,signature:e,robot:o}))}catch(e){return console.error("uploadToken error",e),{fallback:!0}}const s=e,a=crypto.randomBytes(12),n=crypto.createCipheriv("aes-256-gcm",Buffer.from(i.crypt_key,"base64"),a),u=Buffer.concat([n.update(s),n.final()]),c=n.getAuthTag(),p=Buffer.alloc(1);p.writeUInt8(c.length+a.length,0);const l=Buffer.concat([p,c,a,u]),d=Date.now();await putBufferToCos(l,i);const _=Date.now()-d,f=(0,tools_1.generateMD5)(s),g=await(0,sign_1.getSignature)(t.privateKey,t.appid),y=`${r}&task_id=${i.task_id}&new_hash=${f}&upload_cos_cost_time=${_}`;log.info("request url:",y);const w=await(0,request_1.request)({url:y,method:"post",body:zlib.gzipSync((0,pack_1.pack)({[upload_1.SIGNATURE_FILE_NAME]:JSON.stringify({signature:g,version:config_1.CI_VERSION})}).buffer)});if(0!==(0,jsonParse_1.jsonRespParse)(w.body.toString(),r).errCode)throw new Error(w.body.toString());for(;;){const e=await(0,sign_1.getSignature)(t.privateKey,t.appid),r=await innerRequest(`${url_config_1.GET_ASYNC_RESULT}?task_id=${i.task_id}`,JSON.stringify({appid:t.appid,signature:e,robot:o}));if(1!==r.status){if(0===r.status)return{fallback:!1,body:r,uploadCOSCostTime:_};if(3===r.status)throw new Error(`upload failed with status ${r.status}, task not found`);throw new Error("upload failed with status "+r.status)}await new Promise(e=>{setTimeout(e,1e3)})}}exports.uploadByCos=uploadByCos;