const sha1 = require("js-sha1"); const COS = require("./base.js"); import { EventEmitter } from "eventemitter3"; import { S3Client } from "@aws-sdk/client-s3"; import { Upload } from "@aws-sdk/lib-storage"; import axios from "axios"; import util, { HOST } from "./util"; import { vodError } from "./types"; import { VodReportEvent } from "./vod_reporter"; import * as uuidv4 from "uuid/v4"; export const vodAxios = axios.create(); const hostList = [ "vod-upload-accelerate2", "vod-upload-accelerate", "vod-upload-proxy", "vod-quic" ]; const targetHostList = [ "vod-upload-accelerate2", "vod-upload-proxy", "vod-quic" ]; const trimPrefix = (str: string, prefix: string) => str.startsWith(prefix) ? str.substring(prefix.length) : str; let hostIndex = 2; vodAxios.interceptors.response.use( function (response) { return response; }, function (error) { if (isNaN(error.code)) { error.code = 500; } return Promise.reject(error); } ); export type IGetSignature = () => Promise; export interface TcVodFileInfo { name: string; type: string; size: number; } export enum UploaderEvent { video_progress = "video_progress", media_progress = "media_progress", video_upload = "video_upload", media_upload = "media_upload", cover_progress = "cover_progress", cover_upload = "cover_upload" } interface IApplyUpload { signature: string; vodSessionKey?: string; videoName?: string; videoType?: string; videoSize?: number; coverName?: string; coverType?: string; coverSize?: number; fileId?: string; uploadFromWeb?: boolean; storageRegion?: string; ExpireTime?: string; } interface IApplyData { video: { storageSignature: string; storagePath: string; }; cover?: { storageSignature: string; storagePath: string; }; storageAppId: number; storageBucket: string; storageRegion: string; storageRegionV5: string; domain: string; vodSessionKey: string; tempCertificate: { secretId: string; secretKey: string; token: string; expiredTime: number; }; appId: number; timestamp: number; StorageRegionV5: string; } export interface IS3UploadProcessEvtData { loaded: number; total: number; speed: number; percent: number; } export interface IS3UploadCompleteEvtData { Location: string; Bucket: string; Key: string; ETag: string; } export interface UploaderOptions { getSignature: IGetSignature; videoFile?: File; mediaFile?: File; coverFile?: File; videoName?: string; mediaName?: string; fileId?: string; appId?: number; reportId?: string; applyRequestTimeout?: number; commitRequestTimeout?: number; retryDelay?: number; enableResume?: boolean; enableRaceRegion?: boolean; fileParallelLimit?: number; chunkParallelLimit?: number; chunkRetryTimes?: number; chunkSize?: number; sliceSize?: number; copyChunkParallelLimit?: number; copyChunkSize?: number; copySliceSize?: number; progressInterval?: number; dynamicAccelerate?: boolean; expireTime?: string; storageType?: string; } interface CosStrategyProps { FileParallelLimit?: number; ChunkParallelLimit?: number; ChunkRetryTimes?: number; ChunkSize?: number; SliceSize?: number; CopyChunkParallelLimit?: number; CopyChunkSize?: number; CopySliceSize?: number; ProgressInterval?: number; DynamicAccelerate?: boolean; [key: string]: number | boolean | undefined; } class Uploader extends EventEmitter implements UploaderOptions { getSignature: IGetSignature; cosStrategy: CosStrategyProps; videoFile: File; videoInfo: TcVodFileInfo; coverFile: File; coverInfo: TcVodFileInfo; cos: any; taskId: string; cosAuthTime: number; videoName: string; sessionName: string = ""; vodSessionKey: string = ""; appId: number = 0; fileId: string; reqKey: string = uuidv4(); reportId: string = ""; // resume from break point enableResume: boolean = true; enableRaceRegion: boolean = true; donePromise: Promise; // apply 请求的超时时间 applyRequestTimeout = 5000; applyRequestRetryCount = 3; // commit 请求的超时时间 commitRequestTimeout = 5000; commitRequestRetryCount = 3; // 重试请求的等待时间 retryDelay = 1000; targetAccelerate = false; storageType = "cos"; expireTime: string; // domain // static host = "43.156.222.23" || HOST.MAIN; static host = HOST.MAIN; constructor(params: UploaderOptions) { super(); this.validateInitParams(params); this.videoFile = params.mediaFile || params.videoFile; this.getSignature = params.getSignature; this.cosStrategy = this.getCosStrategy(params); this.enableResume = params.enableResume; this.videoName = params.mediaName || params.videoName; this.coverFile = params.coverFile; this.fileId = params.fileId; this.applyRequestTimeout = params.applyRequestTimeout || this.applyRequestTimeout; this.commitRequestTimeout = params.commitRequestTimeout || this.commitRequestTimeout; this.retryDelay = params.retryDelay || this.retryDelay; // custom report metrics this.appId = params.appId || this.appId; this.reportId = params.reportId || this.reportId; this.enableRaceRegion = params.enableRaceRegion; this.expireTime = params?.expireTime; this.storageType = params?.storageType || "cos"; this.cosAuthTime = 0; this.genFileInfo(); } getCosStrategy(params: UploaderOptions) { const sourceData: CosStrategyProps = { FileParallelLimit: params.fileParallelLimit, ChunkParallelLimit: params.chunkParallelLimit || 6, ChunkRetryTimes: params.chunkRetryTimes || 5, ChunkSize: params.chunkSize || 1048576 * 8, SliceSize: params.sliceSize, CopyChunkParallelLimit: params.copyChunkParallelLimit, CopyChunkSize: params.copyChunkSize, CopySliceSize: params.copySliceSize, ProgressInterval: params.progressInterval, DynamicAccelerate: params.dynamicAccelerate }; const cosStrategy = Object.keys(sourceData) .filter(key => sourceData[key] !== undefined) .reduce((acc, key) => ({ ...acc, [key]: sourceData[key] }), {}); return cosStrategy; } // set storage setStorage(name: string, value: string): void { if (!name) { return; } const cname = "webugc_" + sha1(name); try { localStorage.setItem(cname, value); } catch (e) { } } // get storage getStorage(name: string): string { if (!name) { return; } const cname = "webugc_" + sha1(name); let result = null; try { result = localStorage.getItem(cname); } catch (e) { } return result; } // delete storage delStorage(name: string): void { if (!name) { return; } const cname = "webugc_" + sha1(name); try { localStorage.removeItem(cname); } catch (e) { } } // validate init params validateInitParams(params: UploaderOptions): void { if (!util.isFunction(params.getSignature)) { throw new Error("getSignature must be a function"); } if (params.videoFile && !util.isFile(params.videoFile)) { throw new Error("videoFile must be a File"); } } genFileInfo(): void { // video file info const videoFile = this.videoFile; if (videoFile) { const lastDotIndex = videoFile.name.lastIndexOf("."); let videoName = ""; // if specified, use it. if (this.videoName) { if (!util.isString(this.videoName)) { throw new Error("mediaName must be a string"); } else if (/[:*?<>\"\\/|]/g.test(this.videoName)) { throw new Error( 'Cant use these chars in filename: \\ / : * ? " < > |' ); } else { videoName = this.videoName; } } else { // else use the meta info of file videoName = videoFile.name.substring(0, lastDotIndex); } this.videoInfo = { name: videoName, type: videoFile.name.substring(lastDotIndex + 1).toLowerCase(), size: videoFile.size }; this.sessionName += `${videoFile.name}_${videoFile.size};`; } // cover file info const coverFile = this.coverFile; if (coverFile) { const coverName = coverFile.name; const coverLastDotIndex = coverName.lastIndexOf("."); this.coverInfo = { name: coverName.substring(0, coverLastDotIndex), type: coverName.substring(coverLastDotIndex + 1).toLowerCase(), size: coverFile.size }; this.sessionName += `${coverFile.name}_${coverFile.size};`; } } async requestRegion(callback: any) { const self = this; const signature = await this.getSignature(); const sendParams = { signature: signature }; const requestStartTime = Date.now(); let response; try { response = await vodAxios.post( `https://vod2.qcloud.com/v3/index.php?Action=PrepareUploadUGC`, sendParams, { timeout: this.applyRequestTimeout, withCredentials: false } ); } catch (e) { return callback(); } const prepareData = response.data; if (prepareData.code === 0) { self.appId = self.appId || prepareData.data.appId; // 如果只有一个园区就不用竞速了 if ( !prepareData.data.cosRegionList || (prepareData.data.cosRegionList && prepareData.data.cosRegionList.length <= 1) ) { return callback(); } return self.regionRace(prepareData.data.cosRegionList, function ( res: any ) { self.emit(VodReportEvent.report_prepare, { data: { region: res }, requestStartTime: requestStartTime }); return callback(res); }); } else { return callback(); } } async regionRace(cosRegionList: any, cb: any) { return Promise.race( cosRegionList.map((item: any) => this.raceRequest(item)) ).then(res => { // wx.setStorageSync(COS_REGION_KEY, res); return cb(res); }); } async raceRequest(options: any) { return new Promise(async (resolve, reject) => { try { await vodAxios.head("https://" + options.domain, { timeout: this.applyRequestTimeout, withCredentials: false }); } catch (e) { // bucket是私有桶,有可能会失败,哪个先返回就用哪个 resolve(options.region); } resolve(options.region); }); } async applyUploadUGC( retryCount: number = 0, region?: string ): Promise { const self = this; const signature = await this.getSignature(); let sendParams: IApplyUpload; const videoInfo = this.videoInfo; const coverInfo = this.coverInfo; const vodSessionKey = this.vodSessionKey || (this.enableResume && this.getStorage(this.sessionName)); // resume from break point if (vodSessionKey) { sendParams = { signature: signature, vodSessionKey: vodSessionKey }; } else if (videoInfo) { sendParams = { signature: signature, videoName: videoInfo.name, videoType: videoInfo.type, videoSize: videoInfo.size }; if (coverInfo) { // upload video together with cover sendParams.coverName = coverInfo.name; sendParams.coverType = coverInfo.type; sendParams.coverSize = coverInfo.size; } } else if (this.fileId && coverInfo) { // alter cover sendParams = { signature: signature, fileId: this.fileId, coverName: coverInfo.name, coverType: coverInfo.type, coverSize: coverInfo.size }; } else { throw "Wrong params, please check and try again"; } sendParams.uploadFromWeb = true; if (this.expireTime) { sendParams.ExpireTime = this.expireTime; } const requestStartTime = new Date(); async function whenError(err?: vodError): Promise { if (err.code === 500) { Uploader.host = Uploader.host === HOST.MAIN ? HOST.BACKUP : HOST.MAIN; } self.emit(VodReportEvent.report_apply, { err: err, requestStartTime: requestStartTime }); self.delStorage(self.sessionName); if (self.applyRequestRetryCount == retryCount) { if (err) { throw err; } throw new Error(`apply upload failed`); } await util.delay(self.retryDelay); return self.applyUploadUGC(retryCount + 1); } let response; region && (sendParams.storageRegion = region); // sendParams.storageRegion = "vod-upload-proxy"; try { response = await vodAxios.post( `https://${Uploader.host}/v3/index.php?Action=ApplyUploadUGC`, sendParams, { timeout: this.applyRequestTimeout, withCredentials: false } ); } catch (e) { return whenError(e); } const applyResult = response.data; // all err code https://user-images.githubusercontent.com/1147375/51222454-bf6ef280-1978-11e9-8e33-1b0fdb2fe200.png if (applyResult.code == 0) { // if (window.performance && window.performance.mark) { // window.performance.mark("firstFrameStart"); // } const applyData = applyResult.data as IApplyData; const vodSessionKey = applyData.vodSessionKey; this.setStorage(this.sessionName, vodSessionKey); this.vodSessionKey = vodSessionKey; this.appId = applyData.appId; this.targetAccelerate = hostList.some(item => { return applyData.StorageRegionV5 === item; }); this.emit(VodReportEvent.report_apply, { data: applyData, requestStartTime: requestStartTime }); return applyData; } else { // return the apply result error info const err: vodError = new Error(applyResult.message); err.code = applyResult.code; return whenError(err); } } // 使用cos sdk上传 async uploadToCos(applyData: IApplyData) { // console.log("applyData", applyData); const self = this; const cosParam = { bucket: applyData.storageBucket + "-" + applyData.storageAppId, region: applyData.storageRegionV5 }; // 如果走直传,不走动态调整 if (!this.targetAccelerate) { this.cosStrategy.DynamicAccelerate = false; } const cos = new COS( Object.assign( { ForceSignHost: false, // UseRawKey: true, getAuthorization: async function ( options: object, callback: Function ) { const currentTimeStamp = util.getUnix(); const safeExpireTime = (applyData.tempCertificate.expiredTime - applyData.timestamp) * 0.9; if (self.cosAuthTime === 0) { self.cosAuthTime = currentTimeStamp; } else if ( self.cosAuthTime && currentTimeStamp - self.cosAuthTime >= safeExpireTime ) { applyData = await self.applyUploadUGC(); self.cosAuthTime = util.getUnix(); } callback({ TmpSecretId: applyData.tempCertificate.secretId, TmpSecretKey: applyData.tempCertificate.secretKey, XCosSecurityToken: applyData.tempCertificate.token, StartTime: applyData.timestamp, ExpiredTime: applyData.tempCertificate.expiredTime }); } }, this.cosStrategy ) ); this.cos = cos; cos.on("before-send", function (opt: any) { var url = opt.url; // console.log("self", url, self.cosStrategy.DynamicAccelerate); // 开启加速才会走代理域名http2上传,会付费 // 不开启加速走直传 if (!self.targetAccelerate) { return false; } if (!self.cosStrategy.DynamicAccelerate) { return false; } if (url.indexOf("https") === -1) { url = url.replace("http", "https"); } var u = url.match(/^(https?:\/\/([^\/]+)\/)([^\/]*\/?)(.*)$/); var v = url.match(/cos\.(.+)\.myqcloud/); if (url.indexOf("uploads") === -1) { opt.url = url.replace(v[1], targetHostList[hostIndex]); opt.headers["Vod-Forward-Cos"] = u[2]; } if (hostIndex <= targetHostList.length - 2) { hostIndex++; } else { hostIndex = 0; } }); const uploadCosParams = []; if (this.videoFile) { const cosVideoParam = { ...cosParam, file: this.videoFile, key: applyData.video.storagePath, onProgress: function (data: any) { self.emit(UploaderEvent.video_progress, data); self.emit(UploaderEvent.media_progress, data); }, onUpload: function (data: any) { self.emit(UploaderEvent.video_upload, data); self.emit(UploaderEvent.media_upload, data); }, onTaskReady: function (taskId: string) { self.taskId = taskId; } }; uploadCosParams.push(cosVideoParam); } if (this.coverFile) { const cosCoverParam = { ...cosParam, file: this.coverFile, key: applyData.cover.storagePath, onProgress: function (data: any) { self.emit(UploaderEvent.cover_progress, data); }, onUpload: function (data: any) { self.emit(UploaderEvent.cover_upload, data); }, onTaskReady: util.noop }; uploadCosParams.push(cosCoverParam); } const requestStartTime = new Date(); const uploadPromises = uploadCosParams.map(uploadCosParam => { return new Promise(function (resolve, reject) { cos.sliceUploadFile( { Bucket: uploadCosParam.bucket, Region: uploadCosParam.region, Key: uploadCosParam.key, Body: uploadCosParam.file, onTaskReady: uploadCosParam.onTaskReady, onProgress: uploadCosParam.onProgress }, function (err: any, data: any) { // only report video file if (uploadCosParam.file === self.videoFile) { self.emit(VodReportEvent.report_cos_upload, { err: err, requestStartTime: requestStartTime }); } if (!err) { uploadCosParam.onUpload(data); return resolve(); } self.delStorage(self.sessionName); if (JSON.stringify(err) === '{"error":"error","headers":{}}') { return reject(new Error("cors error")); } reject(err); } ); }); }); return await Promise.all(uploadPromises); } // 使用s3 sdk上传 async uploadToS3(applyData: IApplyData) { // console.log("applyData", applyData); const self = this; const uploadCosParams = []; const cosParam = { bucket: applyData.storageBucket + "-" + applyData.storageAppId }; const s3ClientOptions = { endpoint: `https://cos.${applyData.StorageRegionV5}.myqcloud.com`, // 标准版cos上传域名 credentials: { accessKeyId: applyData.tempCertificate.secretId, secretAccessKey: applyData.tempCertificate.secretKey, sessionToken: applyData.tempCertificate.token }, region: applyData.StorageRegionV5, maxAttempts: self.cosStrategy.ChunkRetryTimes, // 重试次数 forcePathStyle: false // 不使用路径风格 }; const s3 = new S3Client(s3ClientOptions); const sharedController = new AbortController(); self.cos = s3; // 为s3添加cancelTask函数,以兼容cos的对应功能 self.cos.cancelTask = function() { sharedController.abort(); }; if (self.videoFile) { const cosVideoParam = { ...cosParam, file: self.videoFile, key: trimPrefix(applyData.video.storagePath, "/"), onProgress: function (data: IS3UploadProcessEvtData) { self.emit(UploaderEvent.video_progress, data); self.emit(UploaderEvent.media_progress, data); }, onUpload: function (data: IS3UploadCompleteEvtData) { self.emit(UploaderEvent.video_upload, data); self.emit(UploaderEvent.media_upload, data); }, onTaskReady: util.noop // aws sdk没有提供taskId,使用空函数代替 }; uploadCosParams.push(cosVideoParam); } if (self.coverFile) { const cosCoverParam = { ...cosParam, file: self.coverFile, key: trimPrefix(applyData.cover.storagePath, "/"), onProgress: function (data: IS3UploadProcessEvtData) { self.emit(UploaderEvent.cover_progress, data); }, onUpload: function (data: IS3UploadCompleteEvtData) { self.emit(UploaderEvent.cover_upload, data); }, onTaskReady: util.noop // aws sdk没有提供taskId,先占位一个空函数 }; uploadCosParams.push(cosCoverParam); } const requestStartTime = new Date(); const uploadPromises = uploadCosParams.map(uploadCosParam => { return new Promise(function (resolve, reject) { const singleUpload = new Upload({ client: s3, params: { Bucket: uploadCosParam.bucket, Key: uploadCosParam.key, Body: uploadCosParam.file }, abortController: sharedController, // 共享中断控制器 partSize: self.cosStrategy.ChunkSize, // 配置分片大小 queueSize: self.cosStrategy.ChunkParallelLimit // 配置并发数 }); singleUpload .done() .then(info => { if (uploadCosParam.file === self.videoFile) { self.emit(VodReportEvent.report_cos_upload, { err: null, requestStartTime: requestStartTime }); } // 和cos的upload事件对齐 const evtData: IS3UploadCompleteEvtData = { Location: info.Location ? info.Location.replace(/^https?:\/\//, "") : '', // 包含域名和路径,无协议头 Bucket: `${info.Bucket}-${applyData.storageAppId}`, // 包含 APPID (BucketName-APPID 格式) Key: info.Key || '', ETag: info.ETag || '' }; uploadCosParam.onUpload(evtData); return resolve(); }) .catch((err: Error | null) => { if (uploadCosParam.file === self.videoFile) { self.emit(VodReportEvent.report_cos_upload, { err: err, requestStartTime: requestStartTime }); } self.delStorage(self.sessionName); return reject(err); }); // 进度条事件 singleUpload.on( "httpUploadProgress", (info) => { const loaded = info.loaded || 0 const total = info.total || 0 const percent = loaded ? loaded / total : 0; // 直接得到 0-1 const evtData: IS3UploadProcessEvtData = { loaded: loaded, total: total, speed: 0, // aws sdk没有提供上传速度,这里设置为0 percent: parseFloat(percent.toFixed(2)) // cos sdk的percent取值是0-1,为了和cos sdk保持一致,这里也转换成0-1,并保留两位小数 }; uploadCosParam.onProgress(evtData); } ); }); }); try { return await Promise.all(uploadPromises); } catch (err: unknown) { if (err instanceof Error && err.name === "AbortError") { // SDK 内部已自动调用 AbortMultipartUpload 清理碎片 console.log("本次上传任务已取消并清理"); } return Promise.reject(err); } } async commitUploadUGC(retryCount: number = 0) { const self = this; const signature = await this.getSignature(); this.delStorage(this.sessionName); const vodSessionKey = this.vodSessionKey; const requestStartTime = new Date(); async function whenError(err?: vodError): Promise { if (err.code === 500) { Uploader.host = Uploader.host === HOST.MAIN ? HOST.BACKUP : HOST.MAIN; } self.emit(VodReportEvent.report_commit, { err: err, requestStartTime: requestStartTime }); if (self.commitRequestRetryCount == retryCount) { if (err) { throw err; } throw new Error("commit upload failed"); } await util.delay(self.retryDelay); return self.commitUploadUGC(retryCount + 1); } let response; try { response = await vodAxios.post( `https://${Uploader.host}/v3/index.php?Action=CommitUploadUGC`, { signature: signature, vodSessionKey: vodSessionKey }, { timeout: this.commitRequestTimeout, withCredentials: false } ); } catch (e) { return whenError(e); } const commitResult = response.data; if (commitResult.code == 0) { // if (window.performance) { // window.performance.mark("firstFrameEnd"); // window.performance.measure( // "firstFrame", // "firstFrameStart", // "firstFrameEnd" // ); // console.log( // "duration", // window.performance.getEntriesByName("firstFrame")[0].duration // ); // } this.emit(VodReportEvent.report_commit, { data: { ...commitResult.data, vodSessionKey: vodSessionKey }, requestStartTime: requestStartTime }); return commitResult.data; } else { const err: vodError = new Error(commitResult.message); err.code = commitResult.code; return whenError(err); } } start() { const requestStartTime = new Date(); this.donePromise = this._start() .then(doneResult => { this.emit(VodReportEvent.report_done, { err: { code: 0 }, requestStartTime: requestStartTime }); return doneResult; }) .catch(err => { this.emit(VodReportEvent.report_done, { err: { code: (err && err.code) || util.CLIENT_ERROR_CODE.UPLOAD_FAIL }, requestStartTime: requestStartTime }); throw err; }); } async _start() { const uploadFunc = async (region?: string) => { const applyData = await this.applyUploadUGC(null, region); if (this.storageType === "s3") { await this.uploadToS3(applyData); } else { await this.uploadToCos(applyData); } return await this.commitUploadUGC(); }; if (this.enableRaceRegion) { return await this.requestRegion(uploadFunc); } else { return await uploadFunc(); } } done() { return this.donePromise; } cancel() { this.cos?.cancelTask(this.taskId); } } export default Uploader;