polyv-vod-api-sdk 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +139 -2
- package/dist/auth/signature.d.ts +67 -0
- package/dist/auth/signature.d.ts.map +1 -0
- package/dist/client.d.ts +37 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/errors/index.d.ts +39 -0
- package/dist/errors/index.d.ts.map +1 -0
- package/dist/index.cjs +1479 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +6275 -0
- package/dist/index.d.ts +40 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1438 -0
- package/dist/index.js.map +1 -0
- package/dist/services/callback.service.d.ts +24 -0
- package/dist/services/callback.service.d.ts.map +1 -0
- package/dist/services/category.service.d.ts +24 -0
- package/dist/services/category.service.d.ts.map +1 -0
- package/dist/services/index.d.ts +7 -0
- package/dist/services/index.d.ts.map +1 -0
- package/dist/services/playsafe.service.d.ts +19 -0
- package/dist/services/playsafe.service.d.ts.map +1 -0
- package/dist/services/statistics.service.d.ts +23 -0
- package/dist/services/statistics.service.d.ts.map +1 -0
- package/dist/services/upload.service.d.ts +48 -0
- package/dist/services/upload.service.d.ts.map +1 -0
- package/dist/services/video.service.d.ts +54 -0
- package/dist/services/video.service.d.ts.map +1 -0
- package/dist/types/category.d.ts +48 -0
- package/dist/types/category.d.ts.map +1 -0
- package/dist/types/client.d.ts +96 -0
- package/dist/types/client.d.ts.map +1 -0
- package/dist/types/generated/account.d.ts +37 -0
- package/dist/types/generated/account.d.ts.map +1 -0
- package/dist/types/generated/ad.d.ts +183 -0
- package/dist/types/generated/ad.d.ts.map +1 -0
- package/dist/types/generated/callback.d.ts +87 -0
- package/dist/types/generated/callback.d.ts.map +1 -0
- package/dist/types/generated/index.d.ts +19 -0
- package/dist/types/generated/index.d.ts.map +1 -0
- package/dist/types/generated/player.d.ts +127 -0
- package/dist/types/generated/player.d.ts.map +1 -0
- package/dist/types/generated/playsafe.d.ts +421 -0
- package/dist/types/generated/playsafe.d.ts.map +1 -0
- package/dist/types/generated/private.d.ts +99 -0
- package/dist/types/generated/private.d.ts.map +1 -0
- package/dist/types/generated/statistics.d.ts +978 -0
- package/dist/types/generated/statistics.d.ts.map +1 -0
- package/dist/types/generated/sub_account.d.ts +393 -0
- package/dist/types/generated/sub_account.d.ts.map +1 -0
- package/dist/types/generated/vert.d.ts +191 -0
- package/dist/types/generated/vert.d.ts.map +1 -0
- package/dist/types/generated/video_codec.d.ts +212 -0
- package/dist/types/generated/video_codec.d.ts.map +1 -0
- package/dist/types/generated/video_management.d.ts +1913 -0
- package/dist/types/generated/video_management.d.ts.map +1 -0
- package/dist/types/generated/video_upload.d.ts +150 -0
- package/dist/types/generated/video_upload.d.ts.map +1 -0
- package/dist/types/index.d.ts +6 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/playsafe.d.ts +136 -0
- package/dist/types/playsafe.d.ts.map +1 -0
- package/dist/types/upload.d.ts +156 -0
- package/dist/types/upload.d.ts.map +1 -0
- package/dist/types/video.d.ts +185 -0
- package/dist/types/video.d.ts.map +1 -0
- package/dist/upload/checkpoint.d.ts +44 -0
- package/dist/upload/checkpoint.d.ts.map +1 -0
- package/dist/upload/chunked-uploader.d.ts +72 -0
- package/dist/upload/chunked-uploader.d.ts.map +1 -0
- package/dist/upload/direct-uploader.d.ts +52 -0
- package/dist/upload/direct-uploader.d.ts.map +1 -0
- package/dist/upload/object-storage.d.ts +75 -0
- package/dist/upload/object-storage.d.ts.map +1 -0
- package/dist/utils/file.d.ts +9 -0
- package/dist/utils/file.d.ts.map +1 -0
- package/dist/utils/rate-limiter.d.ts +20 -0
- package/dist/utils/rate-limiter.d.ts.map +1 -0
- package/dist/version.d.ts +3 -0
- package/dist/version.d.ts.map +1 -0
- package/package.json +59 -4
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,1479 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var crypto = require('crypto');
|
|
4
|
+
var promises = require('timers/promises');
|
|
5
|
+
var promises$1 = require('fs/promises');
|
|
6
|
+
var path = require('path');
|
|
7
|
+
var os = require('os');
|
|
8
|
+
var fs = require('fs');
|
|
9
|
+
var stream = require('stream');
|
|
10
|
+
|
|
11
|
+
var __defProp = Object.defineProperty;
|
|
12
|
+
var __export = (target, all) => {
|
|
13
|
+
for (var name in all)
|
|
14
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
// src/version.ts
|
|
18
|
+
var VERSION = "0.1.0";
|
|
19
|
+
function compactParams(params) {
|
|
20
|
+
const compacted = {};
|
|
21
|
+
for (const [key, value] of Object.entries(params)) {
|
|
22
|
+
if (value === void 0 || value === null || value === "") continue;
|
|
23
|
+
compacted[key] = String(value);
|
|
24
|
+
}
|
|
25
|
+
return compacted;
|
|
26
|
+
}
|
|
27
|
+
function sha1Hex(text) {
|
|
28
|
+
return crypto.createHash("sha1").update(text, "utf8").digest("hex");
|
|
29
|
+
}
|
|
30
|
+
function md5Hex(text) {
|
|
31
|
+
return crypto.createHash("md5").update(text, "utf8").digest("hex");
|
|
32
|
+
}
|
|
33
|
+
function buildSha1SignString(params, secretKey) {
|
|
34
|
+
const compacted = compactParams(params);
|
|
35
|
+
const query = Object.keys(compacted).sort().map((key) => `${key}=${compacted[key]}`).join("&");
|
|
36
|
+
return query + secretKey;
|
|
37
|
+
}
|
|
38
|
+
function signSha1(params, secretKey) {
|
|
39
|
+
return sha1Hex(buildSha1SignString(params, secretKey)).toUpperCase();
|
|
40
|
+
}
|
|
41
|
+
function buildMd5SignString(params, secretKey) {
|
|
42
|
+
const compacted = compactParams(params);
|
|
43
|
+
const joined = Object.keys(compacted).sort().map((key) => `${key}${compacted[key]}`).join("");
|
|
44
|
+
return secretKey + joined + secretKey;
|
|
45
|
+
}
|
|
46
|
+
function signMd5(params, secretKey) {
|
|
47
|
+
return md5Hex(buildMd5SignString(params, secretKey)).toUpperCase();
|
|
48
|
+
}
|
|
49
|
+
function createUploadSignature(secretKey, writeToken, ptime = Date.now()) {
|
|
50
|
+
return {
|
|
51
|
+
ptime,
|
|
52
|
+
sign: md5Hex(`${secretKey}${ptime}`),
|
|
53
|
+
hash: md5Hex(`${ptime}${writeToken}`)
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
function callbackSignCandidates(input, secretKey) {
|
|
57
|
+
const { type, eventType, vid, format, df, fileUrl } = input;
|
|
58
|
+
const candidates = [];
|
|
59
|
+
if (type === "upload" && vid) candidates.push(`upload${vid}${secretKey}`);
|
|
60
|
+
if (type && fileUrl) candidates.push(`${type}${fileUrl}${secretKey}`);
|
|
61
|
+
if (type && format && vid && df !== void 0 && df !== null && df !== "") {
|
|
62
|
+
candidates.push(`${type}${format}${vid}${df}${secretKey}`);
|
|
63
|
+
}
|
|
64
|
+
if (type && vid) candidates.push(`${type}${vid}${secretKey}`);
|
|
65
|
+
if (eventType && vid) candidates.push(`${eventType}${vid}${secretKey}`);
|
|
66
|
+
if (type && vid) candidates.push(`manage${type}${vid}${secretKey}`);
|
|
67
|
+
if (eventType) candidates.push(`${eventType}${secretKey}`);
|
|
68
|
+
return candidates;
|
|
69
|
+
}
|
|
70
|
+
function verifyCallbackSignature(input, secretKey) {
|
|
71
|
+
if (!input.sign) return false;
|
|
72
|
+
const expected = input.sign.toLowerCase();
|
|
73
|
+
return callbackSignCandidates(input, secretKey).some((plain) => md5Hex(plain) === expected);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// src/errors/index.ts
|
|
77
|
+
var PolyVVodError = class extends Error {
|
|
78
|
+
kind;
|
|
79
|
+
code;
|
|
80
|
+
httpStatus;
|
|
81
|
+
data;
|
|
82
|
+
requestId;
|
|
83
|
+
retryable;
|
|
84
|
+
cause;
|
|
85
|
+
constructor(kind, message, details = {}) {
|
|
86
|
+
super(message);
|
|
87
|
+
this.name = "PolyVVodError";
|
|
88
|
+
this.kind = kind;
|
|
89
|
+
this.code = details.code;
|
|
90
|
+
this.httpStatus = details.httpStatus;
|
|
91
|
+
this.data = details.data;
|
|
92
|
+
this.requestId = details.requestId;
|
|
93
|
+
this.retryable = details.retryable ?? false;
|
|
94
|
+
this.cause = details.cause;
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
function isPolyVVodError(error) {
|
|
98
|
+
return error instanceof PolyVVodError;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// src/types/video.ts
|
|
102
|
+
var PUBLISHED_STATUSES = [60, 61];
|
|
103
|
+
var FAILED_STATUSES = [40, 41, 51];
|
|
104
|
+
var VIDEO_STATUS_TEXT = {
|
|
105
|
+
[-1]: "deleted",
|
|
106
|
+
6: "processing",
|
|
107
|
+
10: "waiting-encode",
|
|
108
|
+
20: "encoding",
|
|
109
|
+
40: "encode-failed",
|
|
110
|
+
41: "not-playable",
|
|
111
|
+
50: "waiting-audit",
|
|
112
|
+
51: "audit-rejected",
|
|
113
|
+
60: "published",
|
|
114
|
+
61: "published"
|
|
115
|
+
};
|
|
116
|
+
function describeVideoStatus(status) {
|
|
117
|
+
return VIDEO_STATUS_TEXT[status] ?? `unknown(${status})`;
|
|
118
|
+
}
|
|
119
|
+
function isPublished(status) {
|
|
120
|
+
return PUBLISHED_STATUSES.includes(status);
|
|
121
|
+
}
|
|
122
|
+
function isTerminalFailure(status) {
|
|
123
|
+
return FAILED_STATUSES.includes(status);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// src/services/video.service.ts
|
|
127
|
+
var VIDEO_PATH = "/v2/video/{userid}";
|
|
128
|
+
var SIGN_USERID_VIDS_CATAID = { scheme: "sha1", keys: ["userid", "vids", "cataid", "ptime"] };
|
|
129
|
+
function normalizeVids(vids, max, what = "vids") {
|
|
130
|
+
const list = (Array.isArray(vids) ? vids : String(vids ?? "").split(",")).map((vid) => vid.trim()).filter(Boolean);
|
|
131
|
+
if (list.length === 0) throw new PolyVVodError("validation", `${what} must contain at least one video id`);
|
|
132
|
+
if (list.length > max) throw new PolyVVodError("validation", `${what} accepts at most ${max} video ids, got ${list.length}`);
|
|
133
|
+
return list.join(",");
|
|
134
|
+
}
|
|
135
|
+
function parseSkippedVids(data) {
|
|
136
|
+
if (data === void 0 || data === null || data === "") return [];
|
|
137
|
+
const items = Array.isArray(data) ? data : listedVids(String(data));
|
|
138
|
+
return items.map((item) => typeof item === "object" && item !== null ? String(item.vid ?? "") : String(item).trim()).filter(Boolean);
|
|
139
|
+
}
|
|
140
|
+
function listedVids(text) {
|
|
141
|
+
const bracketed = /^invalidVids\s*:\s*\[(.*)\]$/i.exec(text.trim());
|
|
142
|
+
return (bracketed ? bracketed[1] : text).split(/[,\s]+/);
|
|
143
|
+
}
|
|
144
|
+
function isVideoNotFound(error) {
|
|
145
|
+
return isPolyVVodError(error) && error.kind === "api" && error.code === 400 && /找不到视频|not exist|not found/i.test(error.message);
|
|
146
|
+
}
|
|
147
|
+
var VideoService = class {
|
|
148
|
+
constructor(client) {
|
|
149
|
+
this.client = client;
|
|
150
|
+
}
|
|
151
|
+
searchVideos(params = {}) {
|
|
152
|
+
return this.client.request({
|
|
153
|
+
method: "GET",
|
|
154
|
+
path: "/v2/video/search-videos",
|
|
155
|
+
params: {
|
|
156
|
+
filters: Array.isArray(params.filters) ? params.filters.join(",") : params.filters,
|
|
157
|
+
cateId: params.cataId,
|
|
158
|
+
title: params.title,
|
|
159
|
+
tag: params.tag,
|
|
160
|
+
uploader: params.uploader,
|
|
161
|
+
status: params.status,
|
|
162
|
+
containSubCate: params.containSubCate === void 0 ? void 0 : String(params.containSubCate),
|
|
163
|
+
startTime: params.startTime,
|
|
164
|
+
endTime: params.endTime,
|
|
165
|
+
startModifyTime: params.startModifyTime,
|
|
166
|
+
endModifyTime: params.endModifyTime,
|
|
167
|
+
encrypted: params.encrypted === void 0 ? void 0 : String(params.encrypted),
|
|
168
|
+
playAuthEnable: params.playAuthEnable === void 0 ? void 0 : String(params.playAuthEnable),
|
|
169
|
+
sort: params.sort,
|
|
170
|
+
page: params.page,
|
|
171
|
+
pageSize: params.pageSize
|
|
172
|
+
}
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
/** Details of up to 100 videos. */
|
|
176
|
+
async getVideoInfo(vids) {
|
|
177
|
+
return this.client.request({
|
|
178
|
+
method: "GET",
|
|
179
|
+
path: `${VIDEO_PATH}/get-video-info`,
|
|
180
|
+
params: { vid: normalizeVids(vids, 100) }
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
async getVideo(vid) {
|
|
184
|
+
if (!vid) throw new PolyVVodError("validation", "vid is required");
|
|
185
|
+
const items = await this.getVideoInfo(vid);
|
|
186
|
+
return items?.[0];
|
|
187
|
+
}
|
|
188
|
+
async updateVideoInfo(params) {
|
|
189
|
+
if (!params.vid) throw new PolyVVodError("validation", "vid is required");
|
|
190
|
+
return this.client.request({
|
|
191
|
+
method: "POST",
|
|
192
|
+
path: `${VIDEO_PATH}/video-info`,
|
|
193
|
+
params: { vid: params.vid, title: params.title, describ: params.description, tag: params.tag, publishUrl: params.publishUrl },
|
|
194
|
+
idempotent: false
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Deletes up to 500 videos.
|
|
199
|
+
*
|
|
200
|
+
* A resolved call does not mean every video is gone. `skipped` lists the vids the platform
|
|
201
|
+
* does not know; the others are deleted. When it knows none of them it rejects the whole
|
|
202
|
+
* request with `all vids illegal`, whether or not `ignoreInvalidVids` is set.
|
|
203
|
+
*
|
|
204
|
+
* A video that is still being transcoded is deleted like any other.
|
|
205
|
+
*/
|
|
206
|
+
async deleteVideos(vids, options = {}) {
|
|
207
|
+
const data = await this.client.request({
|
|
208
|
+
method: "POST",
|
|
209
|
+
path: "/v2/video/del-videos",
|
|
210
|
+
params: {
|
|
211
|
+
vids: normalizeVids(vids, 500),
|
|
212
|
+
deleteType: options.deleteType ?? 1,
|
|
213
|
+
ignoreInvalidVids: options.ignoreInvalidVids === false ? "N" : "Y"
|
|
214
|
+
},
|
|
215
|
+
idempotent: false
|
|
216
|
+
});
|
|
217
|
+
return { skipped: parseSkippedVids(data) };
|
|
218
|
+
}
|
|
219
|
+
/** Restores up to 100 videos from the recycle bin. */
|
|
220
|
+
async recoverVideos(vids) {
|
|
221
|
+
return this.client.request({
|
|
222
|
+
method: "POST",
|
|
223
|
+
path: `${VIDEO_PATH}/recover-videos`,
|
|
224
|
+
params: { vids: normalizeVids(vids, 100) },
|
|
225
|
+
idempotent: false
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
/** Moves videos into a category. */
|
|
229
|
+
async moveVideos(params) {
|
|
230
|
+
if (params.cataId === void 0 || params.cataId === null || params.cataId === "") {
|
|
231
|
+
throw new PolyVVodError("validation", "cataId is required");
|
|
232
|
+
}
|
|
233
|
+
return this.client.request({
|
|
234
|
+
method: "POST",
|
|
235
|
+
path: `${VIDEO_PATH}/changeCata`,
|
|
236
|
+
auth: SIGN_USERID_VIDS_CATAID,
|
|
237
|
+
params: { vids: normalizeVids(params.vids, 500), cataid: params.cataId },
|
|
238
|
+
idempotent: false
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
/** Bans or unbans up to 500 videos. Only published videos can be banned and only banned ones unbanned. */
|
|
242
|
+
async setForbidden(params) {
|
|
243
|
+
return this.client.request({
|
|
244
|
+
method: "POST",
|
|
245
|
+
path: `${VIDEO_PATH}/forbidden`,
|
|
246
|
+
params: { vids: normalizeVids(params.vids, 500), forbidden: params.forbidden ? 1 : 0 },
|
|
247
|
+
idempotent: false
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
/** Duration and size of the given videos, or of every video in a category. */
|
|
251
|
+
async getDurationAndSize(params = {}) {
|
|
252
|
+
const vids = params.vids === void 0 ? void 0 : normalizeVids(params.vids, 500);
|
|
253
|
+
if (vids === void 0 && !params.cataId) {
|
|
254
|
+
throw new PolyVVodError("validation", "Pass vids, cataId, or both");
|
|
255
|
+
}
|
|
256
|
+
return this.client.request({ method: "GET", path: `${VIDEO_PATH}/getSizeByCata`, params: { vids, cataid: params.cataId } });
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Polls a video until it is published or definitively failed.
|
|
260
|
+
*
|
|
261
|
+
* Transcoding starts about a minute after the upload and takes about 80 seconds for a small
|
|
262
|
+
* clip, so plan for minutes rather than seconds.
|
|
263
|
+
*
|
|
264
|
+
* @throws {PolyVVodError} `validation`, or a polling error that is not "video not found"
|
|
265
|
+
*/
|
|
266
|
+
async waitUntilPublished(vid, options = {}) {
|
|
267
|
+
if (!vid) throw new PolyVVodError("validation", "vid is required");
|
|
268
|
+
const timeoutMs = options.timeoutMs ?? 10 * 6e4;
|
|
269
|
+
const intervalMs = options.intervalMs ?? 5e3;
|
|
270
|
+
const deadline = Date.now() + timeoutMs;
|
|
271
|
+
let info;
|
|
272
|
+
for (; ; ) {
|
|
273
|
+
try {
|
|
274
|
+
info = await this.getVideo(vid);
|
|
275
|
+
} catch (error) {
|
|
276
|
+
if (!isVideoNotFound(error)) throw error;
|
|
277
|
+
}
|
|
278
|
+
const status = info?.basicInfo?.status;
|
|
279
|
+
if (status !== void 0 && info && isPublished(status)) return { state: "published", info };
|
|
280
|
+
if (status !== void 0 && info && isTerminalFailure(status)) return { state: "failed", info };
|
|
281
|
+
if (Date.now() + intervalMs > deadline) return { state: "timeout", info };
|
|
282
|
+
await promises.setTimeout(intervalMs, void 0, { signal: options.signal });
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
};
|
|
286
|
+
|
|
287
|
+
// src/services/category.service.ts
|
|
288
|
+
var CATEGORY_PATH = "/v2/video/{userid}";
|
|
289
|
+
function requireCataId(cataId) {
|
|
290
|
+
if (cataId === void 0 || cataId === null || cataId === "") {
|
|
291
|
+
throw new PolyVVodError("validation", "cataId is required");
|
|
292
|
+
}
|
|
293
|
+
return cataId;
|
|
294
|
+
}
|
|
295
|
+
var CategoryService = class {
|
|
296
|
+
constructor(client) {
|
|
297
|
+
this.client = client;
|
|
298
|
+
}
|
|
299
|
+
/** The category tree below `cataId` (`1`, the root, by default). */
|
|
300
|
+
async getCategories(cataId = 1) {
|
|
301
|
+
return this.client.request({
|
|
302
|
+
method: "GET",
|
|
303
|
+
path: `${CATEGORY_PATH}/cataJson`,
|
|
304
|
+
// `cataid` is sent but does not take part in the signature.
|
|
305
|
+
auth: { scheme: "sha1", keys: ["userid", "ptime"] },
|
|
306
|
+
params: { cataid: requireCataId(cataId) }
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
async addCategory(params) {
|
|
310
|
+
const name = params.cataname?.trim();
|
|
311
|
+
if (!name) throw new PolyVVodError("validation", "cataname is required");
|
|
312
|
+
if (name.length > 40) throw new PolyVVodError("validation", "cataname must not exceed 40 characters");
|
|
313
|
+
return this.client.request({
|
|
314
|
+
method: "POST",
|
|
315
|
+
path: `${CATEGORY_PATH}/addCata`,
|
|
316
|
+
params: { cataname: name, parentid: requireCataId(params.parentid) },
|
|
317
|
+
idempotent: false
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
async renameCategory(params) {
|
|
321
|
+
const name = params.cataname?.trim();
|
|
322
|
+
if (!name) throw new PolyVVodError("validation", "cataname is required");
|
|
323
|
+
return this.client.request({
|
|
324
|
+
method: "POST",
|
|
325
|
+
path: `${CATEGORY_PATH}/updateCata`,
|
|
326
|
+
auth: { scheme: "sha1", keys: ["userid", "cataname", "cataid", "ptime"] },
|
|
327
|
+
params: { cataid: requireCataId(params.cataid), cataname: name },
|
|
328
|
+
idempotent: false
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
/** Settings of a top-level category; they apply to videos uploaded afterwards. */
|
|
332
|
+
async updateCategorySetting(params) {
|
|
333
|
+
const yn = (value) => value === void 0 ? void 0 : value ? "Y" : "N";
|
|
334
|
+
return this.client.request({
|
|
335
|
+
method: "POST",
|
|
336
|
+
path: `${CATEGORY_PATH}/updateCataProfile`,
|
|
337
|
+
params: {
|
|
338
|
+
cataid: requireCataId(params.cataid),
|
|
339
|
+
isSettings: yn(params.isSettings),
|
|
340
|
+
keepSource: params.keepSource === void 0 ? void 0 : params.keepSource ? 1 : 0,
|
|
341
|
+
encrypt: params.encrypt === void 0 ? void 0 : params.encrypt ? 1 : 0,
|
|
342
|
+
hlslevel: params.hlslevel,
|
|
343
|
+
isEdu: params.isEdu === void 0 ? void 0 : params.isEdu ? 1 : 0,
|
|
344
|
+
encode_aac: params.encodeAac === void 0 ? void 0 : params.encodeAac ? 1 : 0,
|
|
345
|
+
playerId: params.playerId
|
|
346
|
+
},
|
|
347
|
+
idempotent: false
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
async moveCategory(params) {
|
|
351
|
+
return this.client.request({
|
|
352
|
+
method: "POST",
|
|
353
|
+
path: "/v2/cata/{userid}/change",
|
|
354
|
+
params: { cataid: requireCataId(params.cataid), destCataid: requireCataId(params.destCataid) },
|
|
355
|
+
idempotent: false
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
/** Deletes an empty category. */
|
|
359
|
+
async deleteCategory(cataid) {
|
|
360
|
+
return this.client.request({
|
|
361
|
+
method: "POST",
|
|
362
|
+
path: `${CATEGORY_PATH}/deleteCata`,
|
|
363
|
+
auth: { scheme: "sha1", keys: ["userid", "cataid", "ptime"] },
|
|
364
|
+
params: { cataid: requireCataId(cataid) },
|
|
365
|
+
idempotent: false
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
};
|
|
369
|
+
|
|
370
|
+
// src/types/upload.ts
|
|
371
|
+
var DIRECT_UPLOAD_MAX_BYTES = 2 * 1024 * 1024 * 1024;
|
|
372
|
+
var DEFAULT_PART_SIZE = 5 * 1024 * 1024;
|
|
373
|
+
var MIN_PART_SIZE = 100 * 1024;
|
|
374
|
+
async function fileStats(filePath) {
|
|
375
|
+
try {
|
|
376
|
+
return await promises$1.stat(filePath);
|
|
377
|
+
} catch (error) {
|
|
378
|
+
const reason = error.code === "ENOENT" ? "no such file" : error.message;
|
|
379
|
+
throw new PolyVVodError("validation", `Cannot read file "${filePath}": ${reason}`, { cause: error });
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
var defaultCheckpointDir = () => path.resolve(os.tmpdir(), "polyv-vod-upload");
|
|
383
|
+
function checkpointPath(checkpointDir, filePath) {
|
|
384
|
+
const digest = crypto.createHash("sha1").update(path.resolve(filePath)).digest("hex").slice(0, 32);
|
|
385
|
+
return path.resolve(checkpointDir, `${digest}-${path.basename(filePath)}.json`);
|
|
386
|
+
}
|
|
387
|
+
function isCheckpointFor(checkpoint, file) {
|
|
388
|
+
return checkpoint.fileSize === file.size && checkpoint.fileModifiedMs === file.mtimeMs;
|
|
389
|
+
}
|
|
390
|
+
async function readCheckpoint(path) {
|
|
391
|
+
let text;
|
|
392
|
+
try {
|
|
393
|
+
text = await promises$1.readFile(path, "utf8");
|
|
394
|
+
} catch (error) {
|
|
395
|
+
if (isMissing(error)) return null;
|
|
396
|
+
throw error;
|
|
397
|
+
}
|
|
398
|
+
try {
|
|
399
|
+
const parsed = JSON.parse(text);
|
|
400
|
+
if (parsed?.version !== 1 || typeof parsed.vid !== "string" || typeof parsed.uploadId !== "string") return null;
|
|
401
|
+
return parsed;
|
|
402
|
+
} catch {
|
|
403
|
+
return null;
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
async function writeCheckpoint(path$1, checkpoint) {
|
|
407
|
+
await promises$1.mkdir(path.dirname(path$1), { recursive: true, mode: 448 });
|
|
408
|
+
const temporary = `${path$1}.${process.pid}.${crypto.randomUUID().slice(0, 8)}.tmp`;
|
|
409
|
+
try {
|
|
410
|
+
await promises$1.writeFile(temporary, `${JSON.stringify(checkpoint, null, 2)}
|
|
411
|
+
`, { mode: 384 });
|
|
412
|
+
await promises$1.rename(temporary, path$1);
|
|
413
|
+
} catch (error) {
|
|
414
|
+
await removeCheckpoint(temporary);
|
|
415
|
+
throw error;
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
async function removeCheckpoint(path) {
|
|
419
|
+
try {
|
|
420
|
+
await promises$1.unlink(path);
|
|
421
|
+
} catch (error) {
|
|
422
|
+
if (!isMissing(error)) throw error;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
function isMissing(error) {
|
|
426
|
+
return error.code === "ENOENT";
|
|
427
|
+
}
|
|
428
|
+
var EXPIRED_CREDENTIAL_CODES = /* @__PURE__ */ new Set(["InvalidAccessKeyId", "SecurityTokenExpired"]);
|
|
429
|
+
function isCredentialsExpired(error) {
|
|
430
|
+
return error instanceof PolyVVodError && typeof error.code === "string" && EXPIRED_CREDENTIAL_CODES.has(error.code);
|
|
431
|
+
}
|
|
432
|
+
function buildStringToSign(input) {
|
|
433
|
+
const { method, headers, vendor, resource, subResources } = input;
|
|
434
|
+
const vendorHeaders = Object.entries(headers).filter(([name]) => name.toLowerCase().startsWith(`x-${vendor}-`)).map(([name, value]) => ({ name: name.toLowerCase(), value: value.trim() })).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0).map(({ name, value }) => `${name}:${value}
|
|
435
|
+
`).join("");
|
|
436
|
+
const header = (name) => {
|
|
437
|
+
const found = Object.entries(headers).find(([candidate]) => candidate.toLowerCase() === name);
|
|
438
|
+
return found ? found[1] : "";
|
|
439
|
+
};
|
|
440
|
+
const canonicalQuery = Object.keys(subResources).sort().map((name) => subResources[name] ? `${name}=${subResources[name]}` : name).join("&");
|
|
441
|
+
return `${method}
|
|
442
|
+
${header("content-md5")}
|
|
443
|
+
${header("content-type")}
|
|
444
|
+
${header("date")}
|
|
445
|
+
${vendorHeaders}${resource}${canonicalQuery ? `?${canonicalQuery}` : ""}`;
|
|
446
|
+
}
|
|
447
|
+
function md5Base64(data) {
|
|
448
|
+
return crypto.createHash("md5").update(data).digest("base64");
|
|
449
|
+
}
|
|
450
|
+
function encodeKey(key) {
|
|
451
|
+
return key.split("/").map(encodeURIComponent).join("/");
|
|
452
|
+
}
|
|
453
|
+
function xmlTag(xml, tag) {
|
|
454
|
+
const value = new RegExp(`<${tag}>([^<]*)</${tag}>`, "s").exec(xml)?.[1];
|
|
455
|
+
return value?.replace(/"/g, '"').replace(/'/g, "'").replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&");
|
|
456
|
+
}
|
|
457
|
+
function parseParts(xml) {
|
|
458
|
+
const parts = [];
|
|
459
|
+
for (const match of xml.matchAll(/<Part>([\s\S]*?)<\/Part>/g)) {
|
|
460
|
+
const partNumber = Number(xmlTag(match[1], "PartNumber"));
|
|
461
|
+
const etag = xmlTag(match[1], "ETag");
|
|
462
|
+
if (Number.isInteger(partNumber) && etag) parts.push({ partNumber, etag });
|
|
463
|
+
}
|
|
464
|
+
return parts;
|
|
465
|
+
}
|
|
466
|
+
var ObjectStorageClient = class {
|
|
467
|
+
constructor(credentials, options = {}) {
|
|
468
|
+
this.credentials = credentials;
|
|
469
|
+
this.options = options;
|
|
470
|
+
}
|
|
471
|
+
/** Starts a multipart upload and returns its upload id. */
|
|
472
|
+
async initiate(key) {
|
|
473
|
+
const response = await this.request("POST", key, { uploads: "" }, { "Content-Type": "text/plain" });
|
|
474
|
+
const uploadId = xmlTag(response.text, "UploadId");
|
|
475
|
+
if (response.status !== 200 || !uploadId) throw this.failure("initiate multipart upload", response);
|
|
476
|
+
return uploadId;
|
|
477
|
+
}
|
|
478
|
+
async uploadPart(key, uploadId, partNumber, body) {
|
|
479
|
+
const response = await this.request(
|
|
480
|
+
"PUT",
|
|
481
|
+
key,
|
|
482
|
+
{ partNumber: String(partNumber), uploadId },
|
|
483
|
+
{ "Content-Type": "text/plain", "Content-MD5": md5Base64(body) },
|
|
484
|
+
body
|
|
485
|
+
);
|
|
486
|
+
if (response.status !== 200 || !response.etag) throw this.failure(`upload part ${partNumber}`, response);
|
|
487
|
+
return response.etag;
|
|
488
|
+
}
|
|
489
|
+
/** Parts the storage already holds for this upload. */
|
|
490
|
+
async listParts(key, uploadId) {
|
|
491
|
+
const response = await this.request("GET", key, { uploadId });
|
|
492
|
+
if (response.status !== 200) throw this.failure("list parts", response);
|
|
493
|
+
return parseParts(response.text);
|
|
494
|
+
}
|
|
495
|
+
async complete(key, uploadId, parts, callbackBase64) {
|
|
496
|
+
const xml = `<CompleteMultipartUpload>${parts.map((part) => `<Part><PartNumber>${part.partNumber}</PartNumber><ETag>${part.etag}</ETag></Part>`).join("")}</CompleteMultipartUpload>`;
|
|
497
|
+
const headers = {
|
|
498
|
+
"Content-Type": "application/xml",
|
|
499
|
+
"Content-MD5": md5Base64(Buffer.from(xml)),
|
|
500
|
+
// Tells the storage to notify the platform once the object is complete.
|
|
501
|
+
[`x-${this.credentials.kind}-callback`]: callbackBase64
|
|
502
|
+
};
|
|
503
|
+
const response = await this.request("POST", key, { uploadId }, headers, Buffer.from(xml));
|
|
504
|
+
return { status: response.status, body: response.text };
|
|
505
|
+
}
|
|
506
|
+
async abort(key, uploadId) {
|
|
507
|
+
const response = await this.request("DELETE", key, { uploadId });
|
|
508
|
+
if (response.status !== 204 && response.status !== 200 && response.status !== 404) {
|
|
509
|
+
throw this.failure("abort multipart upload", response);
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
async request(method, key, subResources, headers = {}, body) {
|
|
513
|
+
const { kind, bucket, origin, accessKey, secretKey, sessionToken } = this.credentials;
|
|
514
|
+
const allHeaders = {
|
|
515
|
+
[`x-${kind}-security-token`]: sessionToken,
|
|
516
|
+
Date: (/* @__PURE__ */ new Date()).toUTCString(),
|
|
517
|
+
...headers
|
|
518
|
+
};
|
|
519
|
+
const stringToSign = buildStringToSign({ method, headers: allHeaders, vendor: kind, resource: `/${bucket}/${key}`, subResources });
|
|
520
|
+
const signature = crypto.createHmac("sha1", secretKey).update(stringToSign, "utf8").digest("base64");
|
|
521
|
+
const query = Object.keys(subResources).sort().map((name) => {
|
|
522
|
+
const value = subResources[name];
|
|
523
|
+
return value ? `${name}=${encodeURIComponent(value)}` : name;
|
|
524
|
+
}).join("&");
|
|
525
|
+
const url = `${origin}/${encodeKey(key)}${query ? `?${query}` : ""}`;
|
|
526
|
+
let response;
|
|
527
|
+
try {
|
|
528
|
+
response = await (this.options.fetch ?? globalThis.fetch)(url, {
|
|
529
|
+
method,
|
|
530
|
+
headers: { ...allHeaders, Authorization: `${kind.toUpperCase()} ${accessKey}:${signature}` },
|
|
531
|
+
body,
|
|
532
|
+
signal: this.options.signal
|
|
533
|
+
});
|
|
534
|
+
} catch (error) {
|
|
535
|
+
const cancelled = this.options.signal?.aborted === true;
|
|
536
|
+
throw new PolyVVodError("upload", cancelled ? "Upload cancelled" : `Storage request failed: ${messageOf(error)}`, {
|
|
537
|
+
cause: error,
|
|
538
|
+
retryable: !cancelled
|
|
539
|
+
});
|
|
540
|
+
}
|
|
541
|
+
return { status: response.status, text: await response.text(), etag: response.headers.get("etag") ?? "" };
|
|
542
|
+
}
|
|
543
|
+
failure(what, response) {
|
|
544
|
+
return new PolyVVodError("upload", `${what} failed: HTTP ${response.status} ${xmlTag(response.text, "Code") ?? ""} ${truncate(xmlTag(response.text, "Message") ?? response.text)}`.trim(), {
|
|
545
|
+
code: xmlTag(response.text, "Code"),
|
|
546
|
+
httpStatus: response.status,
|
|
547
|
+
retryable: response.status === 429 || response.status >= 500
|
|
548
|
+
});
|
|
549
|
+
}
|
|
550
|
+
};
|
|
551
|
+
function messageOf(error) {
|
|
552
|
+
return error instanceof Error ? error.message : String(error);
|
|
553
|
+
}
|
|
554
|
+
function truncate(text, max = 200) {
|
|
555
|
+
return text.length > max ? `${text.slice(0, max)}\u2026` : text;
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
// src/upload/chunked-uploader.ts
|
|
559
|
+
var CHUNKED_INIT_PATH = "/v2/uploadvideo/{userid}/init";
|
|
560
|
+
var CHUNKED_TOKEN_PATH = "/v2/uploadvideo/{userid}/token";
|
|
561
|
+
var CHUNKED_UPLOAD_TYPE = "java_sdk_chunk_v1";
|
|
562
|
+
var MAX_PART_SIZE = 5 * 1024 * 1024 * 1024;
|
|
563
|
+
var DEFAULT_CONCURRENCY = 3;
|
|
564
|
+
function selectStorage(source, preference = "auto") {
|
|
565
|
+
const useObs = preference === "obs" || preference === "auto" && !!source.hwObsInfo;
|
|
566
|
+
if (useObs) {
|
|
567
|
+
const obs = source.hwObsInfo;
|
|
568
|
+
if (!obs) {
|
|
569
|
+
throw new PolyVVodError("upload", "Huawei OBS was requested but the platform issued no OBS credentials");
|
|
570
|
+
}
|
|
571
|
+
return {
|
|
572
|
+
credentials: {
|
|
573
|
+
kind: "obs",
|
|
574
|
+
accessKey: obs.ak,
|
|
575
|
+
secretKey: obs.sk,
|
|
576
|
+
sessionToken: obs.securitytoken,
|
|
577
|
+
bucket: obs.bucketName,
|
|
578
|
+
origin: `https://${obs.bucketName}.${obs.endpoint}`
|
|
579
|
+
},
|
|
580
|
+
callback: Buffer.from(
|
|
581
|
+
JSON.stringify({ callbackUrl: obs.callbackUrl, callbackBody: obs.callbackBody, callbackBodyType: obs.callbackBodyType })
|
|
582
|
+
).toString("base64"),
|
|
583
|
+
dir: obs.dir
|
|
584
|
+
};
|
|
585
|
+
}
|
|
586
|
+
const { accessId, accessKey, token, host, bucketName, dir, encodedCallback } = source;
|
|
587
|
+
if (!accessId || !accessKey || !token || !host || !bucketName || !dir || !encodedCallback) {
|
|
588
|
+
throw new PolyVVodError("upload", "Aliyun OSS was requested but the platform issued no complete OSS credentials");
|
|
589
|
+
}
|
|
590
|
+
return {
|
|
591
|
+
credentials: {
|
|
592
|
+
kind: "oss",
|
|
593
|
+
accessKey: accessId,
|
|
594
|
+
secretKey: accessKey,
|
|
595
|
+
sessionToken: token,
|
|
596
|
+
bucket: bucketName,
|
|
597
|
+
origin: host.replace(/^http:/i, "https:")
|
|
598
|
+
},
|
|
599
|
+
callback: encodedCallback,
|
|
600
|
+
dir
|
|
601
|
+
};
|
|
602
|
+
}
|
|
603
|
+
function normalizePartSize(partSize) {
|
|
604
|
+
if (partSize === void 0) return DEFAULT_PART_SIZE;
|
|
605
|
+
if (!Number.isInteger(partSize) || partSize <= 0) {
|
|
606
|
+
throw new PolyVVodError("validation", "partSize must be a positive integer");
|
|
607
|
+
}
|
|
608
|
+
if (partSize > MAX_PART_SIZE) {
|
|
609
|
+
throw new PolyVVodError("validation", `partSize must not exceed ${MAX_PART_SIZE} bytes`);
|
|
610
|
+
}
|
|
611
|
+
return Math.max(partSize, MIN_PART_SIZE);
|
|
612
|
+
}
|
|
613
|
+
async function uploadFileChunked(client, options) {
|
|
614
|
+
const filePath = path.resolve(options.filePath);
|
|
615
|
+
const file = await fileStats(filePath);
|
|
616
|
+
if (!file.isFile()) throw new PolyVVodError("validation", `Not a file: ${filePath}`);
|
|
617
|
+
if (file.size === 0) throw new PolyVVodError("validation", `File is empty: ${filePath}`);
|
|
618
|
+
const partSize = normalizePartSize(options.partSize);
|
|
619
|
+
const partCount = Math.ceil(file.size / partSize);
|
|
620
|
+
const concurrency = Math.min(Math.max(Math.trunc(options.concurrency ?? DEFAULT_CONCURRENCY), 1), partCount);
|
|
621
|
+
const title = options.title ?? path.basename(filePath, path.extname(filePath));
|
|
622
|
+
const signal = options.signal;
|
|
623
|
+
signal?.throwIfAborted();
|
|
624
|
+
const checkpointFile = checkpointPath(options.checkpointDir ?? defaultCheckpointDir(), filePath);
|
|
625
|
+
let saved = options.resume === false ? null : await readCheckpoint(checkpointFile);
|
|
626
|
+
if (saved && !isCheckpointFor(saved, file)) {
|
|
627
|
+
saved = null;
|
|
628
|
+
await removeCheckpoint(checkpointFile);
|
|
629
|
+
}
|
|
630
|
+
const keptTitle = saved?.title ?? title;
|
|
631
|
+
const init = await client.request({
|
|
632
|
+
method: "POST",
|
|
633
|
+
path: CHUNKED_INIT_PATH,
|
|
634
|
+
params: saved ? { title: keptTitle, filesize: file.size, vid: saved.vid, autoid: 0, uploadType: CHUNKED_UPLOAD_TYPE } : {
|
|
635
|
+
title,
|
|
636
|
+
describ: options.description,
|
|
637
|
+
cataid: options.cataId,
|
|
638
|
+
tag: options.tag,
|
|
639
|
+
luping: options.luping ? 1 : 0,
|
|
640
|
+
filesize: file.size,
|
|
641
|
+
keepsource: options.keepSource ? 1 : 0,
|
|
642
|
+
extra: JSON.stringify({ watermarkLocation: options.watermarkLocation ?? "", watermark: options.watermark ?? "" }),
|
|
643
|
+
autoid: 1,
|
|
644
|
+
uploadType: CHUNKED_UPLOAD_TYPE,
|
|
645
|
+
state: options.state
|
|
646
|
+
},
|
|
647
|
+
idempotent: false,
|
|
648
|
+
signal
|
|
649
|
+
});
|
|
650
|
+
const vid = init?.vid;
|
|
651
|
+
if (!vid) throw new PolyVVodError("upload", "The platform did not reserve a vid for the upload");
|
|
652
|
+
let selection = selectStorage(init, options.storage);
|
|
653
|
+
const extension = path.extname(filePath).replace(/^\./, "").toLowerCase();
|
|
654
|
+
const key = `${selection.dir}${vid}.${extension || "mp4"}`;
|
|
655
|
+
const storageOptions = { fetch: options.storageFetch, signal };
|
|
656
|
+
let storage = new ObjectStorageClient(selection.credentials, storageOptions);
|
|
657
|
+
const uploadId = saved?.uploadId ?? await storage.initiate(key);
|
|
658
|
+
const checkpoint = {
|
|
659
|
+
version: 1,
|
|
660
|
+
vid,
|
|
661
|
+
title: keptTitle,
|
|
662
|
+
key,
|
|
663
|
+
storage: selection.credentials.kind,
|
|
664
|
+
uploadId,
|
|
665
|
+
fileSize: file.size,
|
|
666
|
+
fileModifiedMs: file.mtimeMs,
|
|
667
|
+
partSize,
|
|
668
|
+
createdAt: saved?.createdAt ?? Date.now(),
|
|
669
|
+
parts: []
|
|
670
|
+
};
|
|
671
|
+
await writeCheckpoint(checkpointFile, checkpoint);
|
|
672
|
+
const guarded = async (operation) => {
|
|
673
|
+
try {
|
|
674
|
+
return await operation(storage);
|
|
675
|
+
} catch (error) {
|
|
676
|
+
if (!isCredentialsExpired(error)) throw error;
|
|
677
|
+
const token = await client.request({ method: "GET", path: CHUNKED_TOKEN_PATH, signal });
|
|
678
|
+
selection = selectStorage({ ...init, ...token }, selection.credentials.kind);
|
|
679
|
+
storage = new ObjectStorageClient(selection.credentials, storageOptions);
|
|
680
|
+
return operation(storage);
|
|
681
|
+
}
|
|
682
|
+
};
|
|
683
|
+
const partBytes = (partNumber) => Math.min(partSize, file.size - (partNumber - 1) * partSize);
|
|
684
|
+
const report = (stored2) => {
|
|
685
|
+
if (!options.onProgress) return;
|
|
686
|
+
let uploadedBytes = 0;
|
|
687
|
+
for (const partNumber of stored2.keys()) uploadedBytes += partBytes(partNumber);
|
|
688
|
+
options.onProgress({ uploadedBytes, totalBytes: file.size, uploadedParts: stored2.size, totalParts: partCount });
|
|
689
|
+
};
|
|
690
|
+
const stored = /* @__PURE__ */ new Map();
|
|
691
|
+
for (const part of await guarded((current) => current.listParts(key, uploadId))) {
|
|
692
|
+
stored.set(part.partNumber, part.etag);
|
|
693
|
+
}
|
|
694
|
+
report(stored);
|
|
695
|
+
const pending = [];
|
|
696
|
+
for (let partNumber = 1; partNumber <= partCount; partNumber += 1) {
|
|
697
|
+
if (!stored.has(partNumber)) pending.push(partNumber);
|
|
698
|
+
}
|
|
699
|
+
const handle = await promises$1.open(filePath, "r");
|
|
700
|
+
let persisting = Promise.resolve();
|
|
701
|
+
const persist = () => {
|
|
702
|
+
persisting = persisting.then(() => writeCheckpoint(checkpointFile, checkpoint));
|
|
703
|
+
return persisting;
|
|
704
|
+
};
|
|
705
|
+
try {
|
|
706
|
+
let stopped = false;
|
|
707
|
+
let next = 0;
|
|
708
|
+
const runner = async () => {
|
|
709
|
+
while (!stopped && next < pending.length) {
|
|
710
|
+
const partNumber = pending[next];
|
|
711
|
+
next += 1;
|
|
712
|
+
try {
|
|
713
|
+
signal?.throwIfAborted();
|
|
714
|
+
const body = await readPart(handle, partNumber, file.size, partSize);
|
|
715
|
+
const etag = await guarded((current) => current.uploadPart(key, uploadId, partNumber, body));
|
|
716
|
+
stored.set(partNumber, etag);
|
|
717
|
+
checkpoint.parts = sortedParts(stored);
|
|
718
|
+
await persist();
|
|
719
|
+
report(stored);
|
|
720
|
+
} catch (error) {
|
|
721
|
+
stopped = true;
|
|
722
|
+
throw error;
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
};
|
|
726
|
+
const outcome = await Promise.allSettled(Array.from({ length: Math.min(concurrency, pending.length) }, runner));
|
|
727
|
+
const failure = outcome.find((item) => item.status === "rejected");
|
|
728
|
+
if (failure) throw failure.reason;
|
|
729
|
+
} finally {
|
|
730
|
+
await handle.close();
|
|
731
|
+
}
|
|
732
|
+
const completed = await guarded((current) => current.complete(key, uploadId, sortedParts(stored), selection.callback));
|
|
733
|
+
if (completed.status !== 200) {
|
|
734
|
+
throw new PolyVVodError("upload", `The file reached the storage but the platform callback failed (HTTP ${completed.status}): ${completed.body.slice(0, 200)}`, {
|
|
735
|
+
httpStatus: completed.status
|
|
736
|
+
});
|
|
737
|
+
}
|
|
738
|
+
await removeCheckpoint(checkpointFile);
|
|
739
|
+
options.onProgress?.({ uploadedBytes: file.size, totalBytes: file.size, uploadedParts: partCount, totalParts: partCount });
|
|
740
|
+
return { vid, mode: "chunked", title: keptTitle, status: 6, resumed: saved !== null, parts: partCount };
|
|
741
|
+
}
|
|
742
|
+
async function abortChunkedUpload(client, options) {
|
|
743
|
+
const filePath = path.resolve(options.filePath);
|
|
744
|
+
const checkpointFile = checkpointPath(options.checkpointDir ?? defaultCheckpointDir(), filePath);
|
|
745
|
+
const saved = await readCheckpoint(checkpointFile);
|
|
746
|
+
if (!saved) return false;
|
|
747
|
+
const init = await client.request({
|
|
748
|
+
method: "POST",
|
|
749
|
+
path: CHUNKED_INIT_PATH,
|
|
750
|
+
params: { title: saved.title ?? "abort", filesize: saved.fileSize, vid: saved.vid, autoid: 0, uploadType: CHUNKED_UPLOAD_TYPE },
|
|
751
|
+
idempotent: false,
|
|
752
|
+
signal: options.signal
|
|
753
|
+
});
|
|
754
|
+
const selection = selectStorage(init, saved.storage);
|
|
755
|
+
await new ObjectStorageClient(selection.credentials, { fetch: options.storageFetch, signal: options.signal }).abort(saved.key, saved.uploadId);
|
|
756
|
+
await removeCheckpoint(checkpointFile);
|
|
757
|
+
return true;
|
|
758
|
+
}
|
|
759
|
+
function sortedParts(stored) {
|
|
760
|
+
return [...stored.entries()].sort(([a], [b]) => a - b).map(([partNumber, etag]) => ({ partNumber, etag }));
|
|
761
|
+
}
|
|
762
|
+
async function readPart(handle, partNumber, fileSize, partSize) {
|
|
763
|
+
const offset = (partNumber - 1) * partSize;
|
|
764
|
+
const length = Math.min(partSize, fileSize - offset);
|
|
765
|
+
const buffer = Buffer.allocUnsafe(length);
|
|
766
|
+
let read = 0;
|
|
767
|
+
while (read < length) {
|
|
768
|
+
const { bytesRead } = await handle.read(buffer, read, length - read, offset + read);
|
|
769
|
+
if (bytesRead === 0) throw new PolyVVodError("upload", `Unexpected end of file while reading part ${partNumber}`);
|
|
770
|
+
read += bytesRead;
|
|
771
|
+
}
|
|
772
|
+
return buffer;
|
|
773
|
+
}
|
|
774
|
+
var DIRECT_UPLOAD_PATH = "/uc/services/rest?method=uploadfile";
|
|
775
|
+
var DIRECT_UPLOAD_ERRORS = {
|
|
776
|
+
"1": "No user is linked to this writetoken",
|
|
777
|
+
"2": "The file or the writetoken is empty",
|
|
778
|
+
"3": "The JSONRPC parameter is missing",
|
|
779
|
+
"4": "The file type is not supported, or the file is larger than 2 GB",
|
|
780
|
+
"14": "The file MD5 does not match",
|
|
781
|
+
"15": "The platform failed to process the upload",
|
|
782
|
+
"16": "The account has no storage space left"
|
|
783
|
+
};
|
|
784
|
+
function multipartStream(parts, boundary, onBytes) {
|
|
785
|
+
async function* body() {
|
|
786
|
+
for (const part of parts) {
|
|
787
|
+
let header = `--${boundary}\r
|
|
788
|
+
Content-Disposition: form-data; name="${part.name}"`;
|
|
789
|
+
if (part.filename !== void 0) header += `; filename="${part.filename.replace(/["\r\n]/g, "_")}"`;
|
|
790
|
+
header += "\r\n";
|
|
791
|
+
if (part.contentType) header += `Content-Type: ${part.contentType}\r
|
|
792
|
+
`;
|
|
793
|
+
header += "\r\n";
|
|
794
|
+
yield Buffer.from(header, "utf8");
|
|
795
|
+
if (part.value !== void 0) yield Buffer.from(part.value, "utf8");
|
|
796
|
+
if (part.stream) {
|
|
797
|
+
for await (const chunk of part.stream) {
|
|
798
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
799
|
+
onBytes(buffer.length);
|
|
800
|
+
yield buffer;
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
yield Buffer.from("\r\n");
|
|
804
|
+
}
|
|
805
|
+
yield Buffer.from(`--${boundary}--\r
|
|
806
|
+
`);
|
|
807
|
+
}
|
|
808
|
+
return stream.Readable.from(body(), { objectMode: false });
|
|
809
|
+
}
|
|
810
|
+
async function uploadFileDirect(client, options) {
|
|
811
|
+
const { writeToken, baseUrls, headers, userAgent, fetch } = client.config;
|
|
812
|
+
if (!writeToken) throw new PolyVVodError("auth", "The direct upload needs writeToken");
|
|
813
|
+
const file = await fileStats(options.filePath);
|
|
814
|
+
if (!file.isFile()) throw new PolyVVodError("validation", `Not a file: ${options.filePath}`);
|
|
815
|
+
if (file.size === 0) throw new PolyVVodError("validation", `File is empty: ${options.filePath}`);
|
|
816
|
+
if (file.size > DIRECT_UPLOAD_MAX_BYTES) {
|
|
817
|
+
throw new PolyVVodError("validation", `The direct upload supports files up to 2 GB; this file is ${file.size} bytes. Use the chunked upload instead.`);
|
|
818
|
+
}
|
|
819
|
+
const signal = options.signal;
|
|
820
|
+
signal?.throwIfAborted();
|
|
821
|
+
const fileName = path.basename(options.filePath);
|
|
822
|
+
const title = options.title ?? path.basename(fileName, path.extname(fileName));
|
|
823
|
+
const metadata = { title };
|
|
824
|
+
if (options.tag) metadata.tag = options.tag;
|
|
825
|
+
if (options.description) metadata.desc = options.description;
|
|
826
|
+
const field = (name, value) => value === void 0 ? [] : [{ name, value: String(value) }];
|
|
827
|
+
const parts = [
|
|
828
|
+
{ name: "writetoken", value: writeToken },
|
|
829
|
+
{ name: "JSONRPC", value: JSON.stringify(metadata) },
|
|
830
|
+
{ name: "format", value: "json" },
|
|
831
|
+
...field("cataid", options.cataId),
|
|
832
|
+
...field("luping", options.luping ? 1 : void 0),
|
|
833
|
+
...field("fileMd5", options.fileMd5?.toUpperCase()),
|
|
834
|
+
...field("state", options.state),
|
|
835
|
+
...field("watermark", options.watermark),
|
|
836
|
+
...field("watermarkLocation", options.watermarkLocation),
|
|
837
|
+
...field("fcharset", options.fcharset),
|
|
838
|
+
{ name: "Filedata", filename: fileName, contentType: "application/octet-stream", stream: fs.createReadStream(options.filePath) }
|
|
839
|
+
];
|
|
840
|
+
const boundary = `----polyv-vod-sdk-${crypto.randomUUID()}`;
|
|
841
|
+
let uploadedBytes = 0;
|
|
842
|
+
const body = multipartStream(parts, boundary, (count) => {
|
|
843
|
+
uploadedBytes += count;
|
|
844
|
+
options.onProgress?.({ uploadedBytes, totalBytes: file.size });
|
|
845
|
+
});
|
|
846
|
+
let response;
|
|
847
|
+
try {
|
|
848
|
+
response = await fetch(`${baseUrls.upload}${DIRECT_UPLOAD_PATH}`, {
|
|
849
|
+
method: "POST",
|
|
850
|
+
headers: {
|
|
851
|
+
"user-agent": userAgent,
|
|
852
|
+
...headers,
|
|
853
|
+
"content-type": `multipart/form-data; boundary=${boundary}`
|
|
854
|
+
},
|
|
855
|
+
body,
|
|
856
|
+
// Node requires `duplex: 'half'` whenever the request body is a stream.
|
|
857
|
+
...{ duplex: "half" },
|
|
858
|
+
signal
|
|
859
|
+
});
|
|
860
|
+
} catch (error) {
|
|
861
|
+
body.destroy();
|
|
862
|
+
if (signal?.aborted) throw new PolyVVodError("upload", "Upload cancelled", { cause: error });
|
|
863
|
+
throw new PolyVVodError("upload", `Upload failed: ${messageOf2(error)}`, { cause: error, retryable: true });
|
|
864
|
+
}
|
|
865
|
+
const text = await response.text();
|
|
866
|
+
const parsed = parseJson(text);
|
|
867
|
+
const item = Array.isArray(parsed?.data) ? parsed.data[0] : void 0;
|
|
868
|
+
const code = parsed?.error;
|
|
869
|
+
if (!response.ok || String(code) !== "0" || !item?.vid) {
|
|
870
|
+
throw new PolyVVodError("upload", `Direct upload failed: ${DIRECT_UPLOAD_ERRORS[String(code)] ?? `HTTP ${response.status}`}`, {
|
|
871
|
+
code: code === void 0 || code === null ? response.status : String(code),
|
|
872
|
+
httpStatus: response.status,
|
|
873
|
+
data: parsed?.data
|
|
874
|
+
});
|
|
875
|
+
}
|
|
876
|
+
const status = Number(item.status);
|
|
877
|
+
return { vid: item.vid, mode: "direct", title: item.title ?? title, status: Number.isFinite(status) ? status : void 0, resumed: false };
|
|
878
|
+
}
|
|
879
|
+
function parseJson(text) {
|
|
880
|
+
try {
|
|
881
|
+
return JSON.parse(text);
|
|
882
|
+
} catch {
|
|
883
|
+
return null;
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
function messageOf2(error) {
|
|
887
|
+
return error instanceof Error ? error.message : String(error);
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
// src/services/upload.service.ts
|
|
891
|
+
var UploadService = class {
|
|
892
|
+
constructor(client) {
|
|
893
|
+
this.client = client;
|
|
894
|
+
}
|
|
895
|
+
/**
|
|
896
|
+
* Uploads a local file.
|
|
897
|
+
*
|
|
898
|
+
* `mode` picks the path: the direct upload is one request and stops at 2 GB; the chunked
|
|
899
|
+
* upload rescales to any size and resumes after an interruption. `auto` (default) switches to
|
|
900
|
+
* the chunked upload above 2 GB.
|
|
901
|
+
*
|
|
902
|
+
* @throws {PolyVVodError} `validation`, `auth`, `api`, `network` or `upload`
|
|
903
|
+
*/
|
|
904
|
+
async uploadFile(options) {
|
|
905
|
+
const mode = options.mode ?? "auto";
|
|
906
|
+
if (mode === "direct") return uploadFileDirect(this.client, options);
|
|
907
|
+
if (mode === "chunked") return uploadFileChunked(this.client, options);
|
|
908
|
+
let size = 0;
|
|
909
|
+
try {
|
|
910
|
+
size = (await promises$1.stat(options.filePath)).size;
|
|
911
|
+
} catch {
|
|
912
|
+
}
|
|
913
|
+
return size > DIRECT_UPLOAD_MAX_BYTES ? uploadFileChunked(this.client, options) : uploadFileDirect(this.client, options);
|
|
914
|
+
}
|
|
915
|
+
/** Discards an interrupted chunked upload. Resolves to false when there is nothing to abort. */
|
|
916
|
+
abortChunkedUpload(options) {
|
|
917
|
+
return abortChunkedUpload(this.client, options);
|
|
918
|
+
}
|
|
919
|
+
/**
|
|
920
|
+
* Signature the browser upload SDK (`@polyv/vod-upload-js-sdk`) expects:
|
|
921
|
+
* `videoUpload.updateUserData({ userid, ptime, sign, hash })`. Valid for 3 minutes.
|
|
922
|
+
*/
|
|
923
|
+
createBrowserUploadSignature() {
|
|
924
|
+
const { secretKey, writeToken } = this.client.config;
|
|
925
|
+
if (!writeToken) throw new PolyVVodError("auth", "The upload signature needs writeToken");
|
|
926
|
+
return createUploadSignature(secretKey, writeToken);
|
|
927
|
+
}
|
|
928
|
+
/**
|
|
929
|
+
* Pulls videos from public URLs. The platform processes them asynchronously; results arrive
|
|
930
|
+
* through the callback or show up in the sync tasks.
|
|
931
|
+
*/
|
|
932
|
+
async uploadByUrl(params) {
|
|
933
|
+
const infos = params.uploadInfos ?? [];
|
|
934
|
+
const useInfos = infos.length > 0;
|
|
935
|
+
if (!useInfos && !params.fileUrl) throw new PolyVVodError("validation", "Pass uploadInfos or fileUrl");
|
|
936
|
+
if (infos.length > 100) throw new PolyVVodError("validation", "uploadInfos accepts at most 100 items");
|
|
937
|
+
infos.forEach((item, index) => {
|
|
938
|
+
const at = `uploadInfos[${index}]`;
|
|
939
|
+
if (!/^https?:\/\//.test(item.fileUrl ?? "")) throw new PolyVVodError("validation", `${at}.fileUrl must be an http(s) URL`);
|
|
940
|
+
if (item.fileUrl.length > 1e3) throw new PolyVVodError("validation", `${at}.fileUrl must not exceed 1000 characters`);
|
|
941
|
+
if (!item.title) throw new PolyVVodError("validation", `${at}.title is required`);
|
|
942
|
+
if (item.title.length > 100) throw new PolyVVodError("validation", `${at}.title must not exceed 100 characters`);
|
|
943
|
+
if (item.state && item.state.length > 100) throw new PolyVVodError("validation", `${at}.state must not exceed 100 characters`);
|
|
944
|
+
if (item.tag && item.tag.length > 200) throw new PolyVVodError("validation", `${at}.tag must not exceed 200 characters`);
|
|
945
|
+
});
|
|
946
|
+
return this.client.request({
|
|
947
|
+
method: "POST",
|
|
948
|
+
path: "/v2/video/grab/{userid}/upload/multi",
|
|
949
|
+
params: {
|
|
950
|
+
cataid: params.cataId,
|
|
951
|
+
luping: params.luping === void 0 ? void 0 : params.luping ? 1 : 0,
|
|
952
|
+
watermark: params.watermark,
|
|
953
|
+
watermarkLocation: params.watermarkLocation,
|
|
954
|
+
// The JSON array is signed as the raw string it is sent as.
|
|
955
|
+
uploadInfos: useInfos ? JSON.stringify(infos) : void 0,
|
|
956
|
+
fileUrl: useInfos ? void 0 : params.fileUrl,
|
|
957
|
+
title: useInfos ? void 0 : params.title
|
|
958
|
+
},
|
|
959
|
+
idempotent: false
|
|
960
|
+
});
|
|
961
|
+
}
|
|
962
|
+
/** URL-upload tasks, newest first. */
|
|
963
|
+
listSyncTasks(params = {}) {
|
|
964
|
+
return this.client.request({
|
|
965
|
+
method: "GET",
|
|
966
|
+
path: "/v2/video/grab/{userid}/list",
|
|
967
|
+
params: { page: params.page, pageSize: params.pageSize }
|
|
968
|
+
});
|
|
969
|
+
}
|
|
970
|
+
/** CSV listing the videos of a task. */
|
|
971
|
+
async exportSyncTask(taskId) {
|
|
972
|
+
if (!taskId) throw new PolyVVodError("validation", "taskId is required");
|
|
973
|
+
return this.client.request({
|
|
974
|
+
method: "GET",
|
|
975
|
+
path: "/v2/video/grab/{userid}/listVideos/export",
|
|
976
|
+
params: { taskId },
|
|
977
|
+
envelope: "none"
|
|
978
|
+
});
|
|
979
|
+
}
|
|
980
|
+
async deleteSyncTask(taskId) {
|
|
981
|
+
if (!taskId) throw new PolyVVodError("validation", "taskId is required");
|
|
982
|
+
return this.client.request({
|
|
983
|
+
method: "POST",
|
|
984
|
+
path: "/v2/video/grab/{userid}/delete",
|
|
985
|
+
params: { taskId },
|
|
986
|
+
idempotent: false
|
|
987
|
+
});
|
|
988
|
+
}
|
|
989
|
+
};
|
|
990
|
+
|
|
991
|
+
// src/services/playsafe.service.ts
|
|
992
|
+
var PlaySafeService = class {
|
|
993
|
+
constructor(client) {
|
|
994
|
+
this.client = client;
|
|
995
|
+
}
|
|
996
|
+
/**
|
|
997
|
+
* Creates a Playsafe token for playing an encrypted video.
|
|
998
|
+
*
|
|
999
|
+
* Reusing the same `videoId`, `viewerId`, `viewerIp` and `iswxa` while a token is still valid
|
|
1000
|
+
* extends that token instead of issuing a new one.
|
|
1001
|
+
*/
|
|
1002
|
+
async createPlayToken(params) {
|
|
1003
|
+
if (!params.videoId) throw new PolyVVodError("validation", "videoId is required");
|
|
1004
|
+
if (!params.viewerId) throw new PolyVVodError("validation", "viewerId is required");
|
|
1005
|
+
if (!/^[A-Za-z0-9_-]+$/.test(params.viewerId)) {
|
|
1006
|
+
throw new PolyVVodError("validation", 'viewerId must consist of letters, digits, "-" and "_"');
|
|
1007
|
+
}
|
|
1008
|
+
if (params.expires !== void 0 && (params.expires <= 0 || params.expires > 24 * 3600)) {
|
|
1009
|
+
throw new PolyVVodError("validation", "expires must be between 1 second and 24 hours");
|
|
1010
|
+
}
|
|
1011
|
+
return this.client.request({
|
|
1012
|
+
method: "POST",
|
|
1013
|
+
host: "hls",
|
|
1014
|
+
path: "/service/v1/token",
|
|
1015
|
+
// This endpoint signs with MD5 over every parameter sent, `userid` included.
|
|
1016
|
+
auth: "md5",
|
|
1017
|
+
in: "body",
|
|
1018
|
+
params: {
|
|
1019
|
+
userid: this.client.config.userId,
|
|
1020
|
+
videoId: params.videoId,
|
|
1021
|
+
ts: Date.now(),
|
|
1022
|
+
viewerId: params.viewerId,
|
|
1023
|
+
viewerIp: params.viewerIp,
|
|
1024
|
+
viewerName: params.viewerName,
|
|
1025
|
+
expires: params.expires,
|
|
1026
|
+
disposable: params.disposable === void 0 ? void 0 : String(params.disposable),
|
|
1027
|
+
iswxa: params.iswxa === void 0 ? void 0 : params.iswxa ? 1 : 0,
|
|
1028
|
+
type: params.type,
|
|
1029
|
+
extraParams: params.extraParams,
|
|
1030
|
+
securitySeed: params.securitySeed
|
|
1031
|
+
},
|
|
1032
|
+
idempotent: false
|
|
1033
|
+
});
|
|
1034
|
+
}
|
|
1035
|
+
};
|
|
1036
|
+
|
|
1037
|
+
// src/services/statistics.service.ts
|
|
1038
|
+
var StatisticsService = class {
|
|
1039
|
+
constructor(client) {
|
|
1040
|
+
this.client = client;
|
|
1041
|
+
}
|
|
1042
|
+
/** Space and traffic usage, for one day (`yyyy-MM-dd`) or since the current plan started. */
|
|
1043
|
+
async getAccountUsage(date) {
|
|
1044
|
+
if (date !== void 0 && !/^\d{4}-\d{2}-\d{2}$/.test(date)) {
|
|
1045
|
+
throw new PolyVVodError("validation", "date must be formatted yyyy-MM-dd");
|
|
1046
|
+
}
|
|
1047
|
+
return this.client.request({
|
|
1048
|
+
method: "POST",
|
|
1049
|
+
path: "/v2/user/{userid}/main",
|
|
1050
|
+
params: { date },
|
|
1051
|
+
idempotent: true
|
|
1052
|
+
});
|
|
1053
|
+
}
|
|
1054
|
+
/** Total play count of specific videos. */
|
|
1055
|
+
async getVideoPlayTimes(vids, realTime = false) {
|
|
1056
|
+
const list = (Array.isArray(vids) ? vids : String(vids ?? "").split(",")).map((vid) => vid.trim()).filter(Boolean);
|
|
1057
|
+
if (list.length === 0) throw new PolyVVodError("validation", "vids must contain at least one video id");
|
|
1058
|
+
return this.client.request({
|
|
1059
|
+
method: "POST",
|
|
1060
|
+
path: "/v2/data/{userid}/play-times",
|
|
1061
|
+
params: { vids: list.join(","), realTime: realTime ? 1 : 0 },
|
|
1062
|
+
idempotent: true
|
|
1063
|
+
});
|
|
1064
|
+
}
|
|
1065
|
+
/** Play counts per day, week or month, for one video or for the whole account. */
|
|
1066
|
+
async getPlayTimes(params = {}) {
|
|
1067
|
+
if (params.period && params.period !== "daily" && params.dr !== "this_month" && params.dr !== "last_month") {
|
|
1068
|
+
throw new PolyVVodError("validation", "period weekly or monthly needs dr to be this_month or last_month");
|
|
1069
|
+
}
|
|
1070
|
+
return this.client.request({
|
|
1071
|
+
method: "GET",
|
|
1072
|
+
path: "/v2/videoview/{userid}",
|
|
1073
|
+
params: { vid: params.vid, dr: params.dr, period: params.period }
|
|
1074
|
+
});
|
|
1075
|
+
}
|
|
1076
|
+
async getPlayTimesRank(params = {}) {
|
|
1077
|
+
for (const bound of [params.start, params.end]) {
|
|
1078
|
+
if (bound !== void 0 && !/^\d{4}-\d{2}-\d{2}$/.test(bound)) {
|
|
1079
|
+
throw new PolyVVodError("validation", "start and end must be formatted yyyy-MM-dd");
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
return this.client.request({ method: "GET", path: "/v2/videoview/{userid}/ranklist", params: { ...params } });
|
|
1083
|
+
}
|
|
1084
|
+
/** View log of one day. */
|
|
1085
|
+
async getDailyViewLog(params) {
|
|
1086
|
+
if (!/^\d{8}$/.test(params.day)) throw new PolyVVodError("validation", "day must be formatted yyyyMMdd");
|
|
1087
|
+
return this.client.request({
|
|
1088
|
+
method: "POST",
|
|
1089
|
+
path: "/v2/data/{userid}/viewlog",
|
|
1090
|
+
auth: { scheme: "sha1", keys: ["userid", "day", "ptime"] },
|
|
1091
|
+
params: { day: params.day, pageNum: params.pageNum, pageSize: params.pageSize },
|
|
1092
|
+
idempotent: true
|
|
1093
|
+
});
|
|
1094
|
+
}
|
|
1095
|
+
/** View log of one month, by pages. */
|
|
1096
|
+
async getMonthlyViewLog(params) {
|
|
1097
|
+
if (!/^\d{6}$/.test(params.month)) throw new PolyVVodError("validation", "month must be formatted yyyyMM");
|
|
1098
|
+
return this.client.request({
|
|
1099
|
+
method: "GET",
|
|
1100
|
+
path: `/v2/viewlog/{userid}/monthly/${params.month}`,
|
|
1101
|
+
// `month` is in the path and still has to be sent as a parameter, because it takes part in
|
|
1102
|
+
// the signature. The page size is `pageSize`: the `numPerPage` name from the docs is not
|
|
1103
|
+
// recognised by the signer and breaks the signature.
|
|
1104
|
+
params: {
|
|
1105
|
+
month: params.month,
|
|
1106
|
+
pageNum: params.pageNum,
|
|
1107
|
+
pageSize: params.pageSize,
|
|
1108
|
+
start: params.start,
|
|
1109
|
+
end: params.end,
|
|
1110
|
+
vid: params.vid,
|
|
1111
|
+
sessionId: params.sessionId,
|
|
1112
|
+
currentDay: params.currentDay
|
|
1113
|
+
}
|
|
1114
|
+
});
|
|
1115
|
+
}
|
|
1116
|
+
};
|
|
1117
|
+
|
|
1118
|
+
// src/services/callback.service.ts
|
|
1119
|
+
var CallbackService = class {
|
|
1120
|
+
constructor(client) {
|
|
1121
|
+
this.client = client;
|
|
1122
|
+
}
|
|
1123
|
+
getCallbackSetting() {
|
|
1124
|
+
return this.client.request({ method: "GET", path: "/vod/v4/user/setting/callback/get", auth: "v4", in: "query" });
|
|
1125
|
+
}
|
|
1126
|
+
/** Sets the callback URL; omitting it clears the setting. */
|
|
1127
|
+
updateCallbackSetting(params = {}) {
|
|
1128
|
+
return this.client.request({
|
|
1129
|
+
method: "POST",
|
|
1130
|
+
path: "/vod/v4/user/setting/callback/update",
|
|
1131
|
+
auth: "v4",
|
|
1132
|
+
in: "query",
|
|
1133
|
+
params: { callbackUrl: params.callbackUrl },
|
|
1134
|
+
idempotent: false
|
|
1135
|
+
});
|
|
1136
|
+
}
|
|
1137
|
+
/**
|
|
1138
|
+
* Whether an event callback really comes from the platform, for the events listed in
|
|
1139
|
+
* `docs/vod/api/callBack.md`. Feed it the callback's query and body fields.
|
|
1140
|
+
*/
|
|
1141
|
+
verifySignature(input) {
|
|
1142
|
+
return verifyCallbackSignature(input, this.client.config.secretKey);
|
|
1143
|
+
}
|
|
1144
|
+
};
|
|
1145
|
+
|
|
1146
|
+
// src/types/client.ts
|
|
1147
|
+
var DEFAULT_BASE_URLS = {
|
|
1148
|
+
api: "https://api.polyv.net",
|
|
1149
|
+
hls: "https://hls.videocc.net",
|
|
1150
|
+
upload: "https://v.polyv.net"
|
|
1151
|
+
};
|
|
1152
|
+
var RateLimiter = class {
|
|
1153
|
+
constructor(maxRequests, windowMs) {
|
|
1154
|
+
this.maxRequests = maxRequests;
|
|
1155
|
+
this.windowMs = windowMs;
|
|
1156
|
+
if (!Number.isFinite(maxRequests) || maxRequests <= 0) {
|
|
1157
|
+
throw new RangeError("maxRequests must be a positive number");
|
|
1158
|
+
}
|
|
1159
|
+
if (!Number.isFinite(windowMs) || windowMs <= 0) {
|
|
1160
|
+
throw new RangeError("windowMs must be a positive number");
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
issuedAt = [];
|
|
1164
|
+
/** Number of requests issued inside the current window. */
|
|
1165
|
+
get used() {
|
|
1166
|
+
this.prune(Date.now());
|
|
1167
|
+
return this.issuedAt.length;
|
|
1168
|
+
}
|
|
1169
|
+
/** Resolves once a request may be sent, waiting for the window to free up if needed. */
|
|
1170
|
+
async acquire() {
|
|
1171
|
+
for (; ; ) {
|
|
1172
|
+
const now = Date.now();
|
|
1173
|
+
this.prune(now);
|
|
1174
|
+
const oldest = this.issuedAt[0];
|
|
1175
|
+
if (this.issuedAt.length < this.maxRequests || oldest === void 0) {
|
|
1176
|
+
this.issuedAt.push(now);
|
|
1177
|
+
return;
|
|
1178
|
+
}
|
|
1179
|
+
await promises.setTimeout(Math.max(oldest + this.windowMs - now, 1));
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
prune(now) {
|
|
1183
|
+
while (this.issuedAt.length > 0 && this.issuedAt[0] <= now - this.windowMs) {
|
|
1184
|
+
this.issuedAt.shift();
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
};
|
|
1188
|
+
|
|
1189
|
+
// src/client.ts
|
|
1190
|
+
var DEFAULT_RATE_LIMIT = { maxRequests: 400, windowMs: 1e4 };
|
|
1191
|
+
var MAX_BACKOFF_MS = 5e3;
|
|
1192
|
+
function newRequestId() {
|
|
1193
|
+
return crypto.randomUUID().replace(/-/g, "");
|
|
1194
|
+
}
|
|
1195
|
+
function combineSignals(signal, timeoutMs) {
|
|
1196
|
+
const timeout = AbortSignal.timeout(timeoutMs);
|
|
1197
|
+
if (!signal) return timeout;
|
|
1198
|
+
const controller = new AbortController();
|
|
1199
|
+
const abort = (reason) => controller.abort(reason);
|
|
1200
|
+
if (signal.aborted) abort(signal.reason);
|
|
1201
|
+
else signal.addEventListener("abort", () => abort(signal.reason), { once: true });
|
|
1202
|
+
if (timeout.aborted) abort(timeout.reason);
|
|
1203
|
+
else timeout.addEventListener("abort", () => abort(timeout.reason), { once: true });
|
|
1204
|
+
return controller.signal;
|
|
1205
|
+
}
|
|
1206
|
+
function messageOf3(error) {
|
|
1207
|
+
return error instanceof Error ? error.message : String(error);
|
|
1208
|
+
}
|
|
1209
|
+
var PolyVVodClient = class {
|
|
1210
|
+
config;
|
|
1211
|
+
video;
|
|
1212
|
+
category;
|
|
1213
|
+
upload;
|
|
1214
|
+
playSafe;
|
|
1215
|
+
statistics;
|
|
1216
|
+
callback;
|
|
1217
|
+
limiter;
|
|
1218
|
+
constructor(config) {
|
|
1219
|
+
if (!config.userId || !config.secretKey) {
|
|
1220
|
+
throw new PolyVVodError("validation", "userId and secretKey are required");
|
|
1221
|
+
}
|
|
1222
|
+
if (config.maxRetries !== void 0 && config.maxRetries < 0) {
|
|
1223
|
+
throw new PolyVVodError("validation", "maxRetries must not be negative");
|
|
1224
|
+
}
|
|
1225
|
+
if (config.timeout !== void 0 && config.timeout <= 0) {
|
|
1226
|
+
throw new PolyVVodError("validation", "timeout must be a positive number");
|
|
1227
|
+
}
|
|
1228
|
+
this.config = {
|
|
1229
|
+
userId: config.userId,
|
|
1230
|
+
secretKey: config.secretKey,
|
|
1231
|
+
writeToken: config.writeToken || void 0,
|
|
1232
|
+
readToken: config.readToken || void 0,
|
|
1233
|
+
appId: config.appId || void 0,
|
|
1234
|
+
appSecret: config.appSecret || void 0,
|
|
1235
|
+
baseUrls: { ...DEFAULT_BASE_URLS, ...config.baseUrls ?? {} },
|
|
1236
|
+
timeout: config.timeout ?? 3e4,
|
|
1237
|
+
maxRetries: config.maxRetries ?? 2,
|
|
1238
|
+
retryDelayMs: config.retryDelayMs ?? 500,
|
|
1239
|
+
headers: { ...config.headers ?? {} },
|
|
1240
|
+
userAgent: config.userAgent ?? `polyv-vod-api-sdk/${VERSION}`,
|
|
1241
|
+
rateLimit: config.rateLimit === void 0 ? DEFAULT_RATE_LIMIT : config.rateLimit,
|
|
1242
|
+
fetch: config.fetch ?? globalThis.fetch
|
|
1243
|
+
};
|
|
1244
|
+
this.limiter = this.config.rateLimit ? new RateLimiter(this.config.rateLimit.maxRequests, this.config.rateLimit.windowMs) : null;
|
|
1245
|
+
this.video = new VideoService(this);
|
|
1246
|
+
this.category = new CategoryService(this);
|
|
1247
|
+
this.upload = new UploadService(this);
|
|
1248
|
+
this.playSafe = new PlaySafeService(this);
|
|
1249
|
+
this.statistics = new StatisticsService(this);
|
|
1250
|
+
this.callback = new CallbackService(this);
|
|
1251
|
+
}
|
|
1252
|
+
/**
|
|
1253
|
+
* Sends a request and returns the `data` of the response envelope.
|
|
1254
|
+
*
|
|
1255
|
+
* @throws {PolyVVodError} `validation`, `auth`, `api` or `network`
|
|
1256
|
+
*/
|
|
1257
|
+
async request(init) {
|
|
1258
|
+
const attempts = this.config.maxRetries + 1;
|
|
1259
|
+
let lastError = null;
|
|
1260
|
+
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
|
1261
|
+
if (attempt > 0) {
|
|
1262
|
+
await promises.setTimeout(Math.min(this.config.retryDelayMs * 2 ** (attempt - 1), MAX_BACKOFF_MS));
|
|
1263
|
+
}
|
|
1264
|
+
const prepared = this.prepare(init);
|
|
1265
|
+
if (prepared.host === "api" && this.limiter) {
|
|
1266
|
+
await this.limiter.acquire();
|
|
1267
|
+
}
|
|
1268
|
+
try {
|
|
1269
|
+
return await this.execute(prepared);
|
|
1270
|
+
} catch (error) {
|
|
1271
|
+
if (!(error instanceof PolyVVodError) || !error.retryable) throw error;
|
|
1272
|
+
lastError = error;
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
throw lastError;
|
|
1276
|
+
}
|
|
1277
|
+
prepare(init) {
|
|
1278
|
+
if (init.method !== "GET" && init.method !== "POST") {
|
|
1279
|
+
throw new PolyVVodError("validation", `Unsupported method "${init.method}"; only GET and POST are used by the VOD API`);
|
|
1280
|
+
}
|
|
1281
|
+
const host = init.host ?? "api";
|
|
1282
|
+
const params = this.signedParams(init);
|
|
1283
|
+
const placement = init.in ?? (init.method === "GET" ? "query" : "body");
|
|
1284
|
+
const path = init.path.replace("{userid}", encodeURIComponent(this.config.userId));
|
|
1285
|
+
return {
|
|
1286
|
+
method: init.method,
|
|
1287
|
+
url: `${this.config.baseUrls[host].replace(/\/+$/, "")}${path.startsWith("/") ? path : `/${path}`}`,
|
|
1288
|
+
params,
|
|
1289
|
+
placement,
|
|
1290
|
+
envelope: init.envelope ?? "standard",
|
|
1291
|
+
host,
|
|
1292
|
+
init
|
|
1293
|
+
};
|
|
1294
|
+
}
|
|
1295
|
+
/** Builds every transmitted parameter, including the auth ones and the signature. */
|
|
1296
|
+
signedParams(init) {
|
|
1297
|
+
const auth = init.auth ?? "sha1";
|
|
1298
|
+
const business = compactParams(init.params ?? {});
|
|
1299
|
+
const { userId, secretKey, appId, appSecret, writeToken } = this.config;
|
|
1300
|
+
if (auth === "sha1" || typeof auth === "object" && auth.scheme === "sha1") {
|
|
1301
|
+
const sent = { ...business, userid: userId, ptime: Date.now(), requestId: newRequestId() };
|
|
1302
|
+
const signed = typeof auth === "object" ? pick(sent, auth.keys) : sent;
|
|
1303
|
+
return { ...compactParams(sent), sign: signSha1(signed, secretKey) };
|
|
1304
|
+
}
|
|
1305
|
+
if (auth === "md5") {
|
|
1306
|
+
return { ...business, sign: signMd5(business, secretKey) };
|
|
1307
|
+
}
|
|
1308
|
+
if (auth === "v4") {
|
|
1309
|
+
if (!appId || !appSecret) {
|
|
1310
|
+
throw new PolyVVodError("auth", "This endpoint needs the account API credentials: set appId and appSecret");
|
|
1311
|
+
}
|
|
1312
|
+
const sent = { ...business, appId, timestamp: Date.now(), requestId: newRequestId() };
|
|
1313
|
+
return { ...compactParams(sent), sign: signMd5(sent, appSecret) };
|
|
1314
|
+
}
|
|
1315
|
+
if (auth === "writetoken") {
|
|
1316
|
+
if (!writeToken) {
|
|
1317
|
+
throw new PolyVVodError("auth", "This endpoint needs writeToken");
|
|
1318
|
+
}
|
|
1319
|
+
return { ...business, writetoken: writeToken };
|
|
1320
|
+
}
|
|
1321
|
+
return business;
|
|
1322
|
+
}
|
|
1323
|
+
async execute(prepared) {
|
|
1324
|
+
const { init } = prepared;
|
|
1325
|
+
const form = new URLSearchParams(prepared.params).toString();
|
|
1326
|
+
const url = prepared.placement === "query" ? `${prepared.url}${form ? `?${form}` : ""}` : prepared.url;
|
|
1327
|
+
const headers = { "user-agent": this.config.userAgent, ...this.config.headers };
|
|
1328
|
+
let body;
|
|
1329
|
+
if (prepared.method === "POST" && prepared.placement === "body") {
|
|
1330
|
+
body = form;
|
|
1331
|
+
headers["content-type"] = "application/x-www-form-urlencoded";
|
|
1332
|
+
}
|
|
1333
|
+
let response;
|
|
1334
|
+
let text;
|
|
1335
|
+
const timeoutMs = init.timeout ?? this.config.timeout;
|
|
1336
|
+
const mayRetry = init.idempotent ?? init.method === "GET";
|
|
1337
|
+
const signal = combineSignals(init.signal, timeoutMs);
|
|
1338
|
+
try {
|
|
1339
|
+
response = await this.config.fetch(url, { method: prepared.method, headers, body, signal });
|
|
1340
|
+
text = await response.text();
|
|
1341
|
+
} catch (error) {
|
|
1342
|
+
if (init.signal?.aborted) {
|
|
1343
|
+
throw new PolyVVodError("network", "Request cancelled", { cause: error });
|
|
1344
|
+
}
|
|
1345
|
+
if (signal.aborted) {
|
|
1346
|
+
throw new PolyVVodError("network", `Request timeout after ${timeoutMs}ms`, { cause: error, retryable: mayRetry });
|
|
1347
|
+
}
|
|
1348
|
+
throw new PolyVVodError("network", `Request failed: ${messageOf3(error)}`, { cause: error, retryable: mayRetry });
|
|
1349
|
+
}
|
|
1350
|
+
const parsed = parseJson2(text);
|
|
1351
|
+
if (prepared.envelope === "none") {
|
|
1352
|
+
return parsed ?? text;
|
|
1353
|
+
}
|
|
1354
|
+
const envelope = parsed ?? {};
|
|
1355
|
+
if (response.status === 200 && envelope.code === 200) {
|
|
1356
|
+
return envelope.data;
|
|
1357
|
+
}
|
|
1358
|
+
const transient = response.status === 429 || response.status >= 500;
|
|
1359
|
+
const detail = envelope.error;
|
|
1360
|
+
throw new PolyVVodError("api", envelope.message || detail?.desc || `HTTP ${response.status}`, {
|
|
1361
|
+
code: envelope.code ?? response.status,
|
|
1362
|
+
httpStatus: response.status,
|
|
1363
|
+
data: envelope.data,
|
|
1364
|
+
requestId: envelope.requestId,
|
|
1365
|
+
retryable: transient && mayRetry
|
|
1366
|
+
});
|
|
1367
|
+
}
|
|
1368
|
+
};
|
|
1369
|
+
function pick(source, keys) {
|
|
1370
|
+
const picked = {};
|
|
1371
|
+
for (const key of keys) {
|
|
1372
|
+
if (key in source) picked[key] = source[key];
|
|
1373
|
+
}
|
|
1374
|
+
return picked;
|
|
1375
|
+
}
|
|
1376
|
+
function parseJson2(text) {
|
|
1377
|
+
if (!text) return null;
|
|
1378
|
+
try {
|
|
1379
|
+
return JSON.parse(text);
|
|
1380
|
+
} catch {
|
|
1381
|
+
return null;
|
|
1382
|
+
}
|
|
1383
|
+
}
|
|
1384
|
+
|
|
1385
|
+
// src/types/generated/index.ts
|
|
1386
|
+
var generated_exports = {};
|
|
1387
|
+
__export(generated_exports, {
|
|
1388
|
+
_private: () => private_exports,
|
|
1389
|
+
account: () => account_exports,
|
|
1390
|
+
ad: () => ad_exports,
|
|
1391
|
+
callback: () => callback_exports,
|
|
1392
|
+
player: () => player_exports,
|
|
1393
|
+
playsafe: () => playsafe_exports,
|
|
1394
|
+
statistics: () => statistics_exports,
|
|
1395
|
+
sub_account: () => sub_account_exports,
|
|
1396
|
+
vert: () => vert_exports,
|
|
1397
|
+
video_codec: () => video_codec_exports,
|
|
1398
|
+
video_management: () => video_management_exports,
|
|
1399
|
+
video_upload: () => video_upload_exports
|
|
1400
|
+
});
|
|
1401
|
+
|
|
1402
|
+
// src/types/generated/account.ts
|
|
1403
|
+
var account_exports = {};
|
|
1404
|
+
|
|
1405
|
+
// src/types/generated/ad.ts
|
|
1406
|
+
var ad_exports = {};
|
|
1407
|
+
|
|
1408
|
+
// src/types/generated/callback.ts
|
|
1409
|
+
var callback_exports = {};
|
|
1410
|
+
|
|
1411
|
+
// src/types/generated/player.ts
|
|
1412
|
+
var player_exports = {};
|
|
1413
|
+
|
|
1414
|
+
// src/types/generated/playsafe.ts
|
|
1415
|
+
var playsafe_exports = {};
|
|
1416
|
+
|
|
1417
|
+
// src/types/generated/private.ts
|
|
1418
|
+
var private_exports = {};
|
|
1419
|
+
|
|
1420
|
+
// src/types/generated/statistics.ts
|
|
1421
|
+
var statistics_exports = {};
|
|
1422
|
+
|
|
1423
|
+
// src/types/generated/sub_account.ts
|
|
1424
|
+
var sub_account_exports = {};
|
|
1425
|
+
|
|
1426
|
+
// src/types/generated/vert.ts
|
|
1427
|
+
var vert_exports = {};
|
|
1428
|
+
|
|
1429
|
+
// src/types/generated/video_codec.ts
|
|
1430
|
+
var video_codec_exports = {};
|
|
1431
|
+
|
|
1432
|
+
// src/types/generated/video_management.ts
|
|
1433
|
+
var video_management_exports = {};
|
|
1434
|
+
|
|
1435
|
+
// src/types/generated/video_upload.ts
|
|
1436
|
+
var video_upload_exports = {};
|
|
1437
|
+
|
|
1438
|
+
exports.CallbackService = CallbackService;
|
|
1439
|
+
exports.CategoryService = CategoryService;
|
|
1440
|
+
exports.DEFAULT_BASE_URLS = DEFAULT_BASE_URLS;
|
|
1441
|
+
exports.DEFAULT_PART_SIZE = DEFAULT_PART_SIZE;
|
|
1442
|
+
exports.DIRECT_UPLOAD_MAX_BYTES = DIRECT_UPLOAD_MAX_BYTES;
|
|
1443
|
+
exports.FAILED_STATUSES = FAILED_STATUSES;
|
|
1444
|
+
exports.MIN_PART_SIZE = MIN_PART_SIZE;
|
|
1445
|
+
exports.ObjectStorageClient = ObjectStorageClient;
|
|
1446
|
+
exports.PUBLISHED_STATUSES = PUBLISHED_STATUSES;
|
|
1447
|
+
exports.PlaySafeService = PlaySafeService;
|
|
1448
|
+
exports.PolyVVodClient = PolyVVodClient;
|
|
1449
|
+
exports.PolyVVodError = PolyVVodError;
|
|
1450
|
+
exports.RateLimiter = RateLimiter;
|
|
1451
|
+
exports.StatisticsService = StatisticsService;
|
|
1452
|
+
exports.UploadService = UploadService;
|
|
1453
|
+
exports.VERSION = VERSION;
|
|
1454
|
+
exports.VIDEO_STATUS_TEXT = VIDEO_STATUS_TEXT;
|
|
1455
|
+
exports.VideoService = VideoService;
|
|
1456
|
+
exports.abortChunkedUpload = abortChunkedUpload;
|
|
1457
|
+
exports.buildMd5SignString = buildMd5SignString;
|
|
1458
|
+
exports.buildSha1SignString = buildSha1SignString;
|
|
1459
|
+
exports.buildStringToSign = buildStringToSign;
|
|
1460
|
+
exports.callbackSignCandidates = callbackSignCandidates;
|
|
1461
|
+
exports.compactParams = compactParams;
|
|
1462
|
+
exports.createUploadSignature = createUploadSignature;
|
|
1463
|
+
exports.describeVideoStatus = describeVideoStatus;
|
|
1464
|
+
exports.generated = generated_exports;
|
|
1465
|
+
exports.isCredentialsExpired = isCredentialsExpired;
|
|
1466
|
+
exports.isPolyVVodError = isPolyVVodError;
|
|
1467
|
+
exports.isPublished = isPublished;
|
|
1468
|
+
exports.isTerminalFailure = isTerminalFailure;
|
|
1469
|
+
exports.isVideoNotFound = isVideoNotFound;
|
|
1470
|
+
exports.normalizeVids = normalizeVids;
|
|
1471
|
+
exports.parseSkippedVids = parseSkippedVids;
|
|
1472
|
+
exports.selectStorage = selectStorage;
|
|
1473
|
+
exports.signMd5 = signMd5;
|
|
1474
|
+
exports.signSha1 = signSha1;
|
|
1475
|
+
exports.uploadFileChunked = uploadFileChunked;
|
|
1476
|
+
exports.uploadFileDirect = uploadFileDirect;
|
|
1477
|
+
exports.verifyCallbackSignature = verifyCallbackSignature;
|
|
1478
|
+
//# sourceMappingURL=index.cjs.map
|
|
1479
|
+
//# sourceMappingURL=index.cjs.map
|