Let's use AI to Earn!
TypeScript auto-publishdouyindouyin-apielectron-appelectron-reactkuaishoukwaipublishedshipinhaotoolxiaohongshu
feat: 小红书、抖音、快手、视频号,分片上传失败后添加重试的逻辑,最大重试次数为3,重试间隔为1秒。
gaoSirf4a900b4247d
diff --git a/commont/utils.ts b/commont/utils.tsindex ec94a6cd..fdef43e9 100644--- a/commont/utils.ts+++ b/commont/utils.ts@@ -17,3 +17,31 @@ export function getFilePathNameCommon(path: string) {export function sleep(ms: number) {return new Promise((resolve) => setTimeout(resolve, ms));}++/**+ * 重试+ * @param max 重试上限+ * @param callback 每次循环的回调,返回boolean,为true则会结束循环+ * @param interval 重试间隔时间+ * @returns true=成功,false=失败+ */+export async function RetryWhile(+ callback: (count: number) => Promise<boolean | undefined>,+ max: number,+ interval: number = 1000,+) {+ let count = 0;+ let flag = true;+ while (true) {+ const isEnd = await callback(count);+ if (isEnd === true) break;+ if (count > max) {+ flag = false;+ break;+ }+ count++;+ await sleep(interval);+ console.log(`开始第 ${count} 次重试`);+ }+ return flag;+}diff --git a/electron/plat/Kwai/index.ts b/electron/plat/Kwai/index.tsindex 0919cb70..3964151b 100644--- a/electron/plat/Kwai/index.ts+++ b/electron/plat/Kwai/index.ts@@ -14,6 +14,7 @@ import {IKwaiUserInfoResponse,ILoginResponse,KwaiSubmitResponse,+ KwaiWorkItem,RefreshWorksResponse,UploadFinishResponse,UploadPpreResponse,@@ -22,7 +23,7 @@ import { CookieToString } from '../utils';import { BrowserWindow, screen } from 'electron';import kwaiSign from './sign/KwaiSign';import { FileUtils } from '../../util/file';-import { getFilePathNameCommon } from '../../../commont/utils';+import { getFilePathNameCommon, RetryWhile } from '../../../commont/utils';import FormData from 'form-data';import fs from 'fs';@@ -92,22 +93,30 @@ class KwaiPub {for (const i in filePartInfo.blockInfo) {callback(40, `上传视频(${i}/${filePartInfo.blockInfo.length})`);- const chunkStart =- i === '0' ? 0 : filePartInfo.blockInfo[parseInt(i) - 1];- const chunkEnd = filePartInfo.blockInfo[i] - 1;- const chunkContent = await FileUtils.getFilePartContent(- params.videoPath,- chunkStart,- chunkEnd,- );- const uploadVideoRes = await requestNet({- method: 'POST',- url: `https://upload.kuaishouzt.com/api/upload/fragment?upload_token=${preRes.data.data.token}&fragment_id=${i}`,- isFile: true,- body: chunkContent,- });- console.log(`分片上传:(${i}/${filePartInfo.blockInfo.length})`);- console.log(uploadVideoRes.data);++ const isSuccess = await RetryWhile(async () => {+ const chunkStart =+ i === '0' ? 0 : filePartInfo.blockInfo[parseInt(i) - 1];+ const chunkEnd = filePartInfo.blockInfo[i] - 1;+ const chunkContent = await FileUtils.getFilePartContent(+ params.videoPath,+ chunkStart,+ chunkEnd,+ );+ const uploadVideoRes = await requestNet({+ method: 'POST',+ url: `https://upload.kuaishouzt.com/api/upload/fragment?upload_token=${preRes.data.data.token}&fragment_id=${i}`,+ isFile: true,+ body: chunkContent,+ });+ if (uploadVideoRes.data.result === 1) {+ return true;+ }+ console.log(`分片上传:(${i}/${filePartInfo.blockInfo.length})`);+ }, 3);+ if (!isSuccess) {+ throw new Error('分片上传失败,请稍后重试!');+ }}callback(60, `查询分片上传结果...`);@@ -201,14 +210,19 @@ class KwaiPub {return reject(submitRes.data.message);}callback(95, `正在查询发布结果...`);- const worksList = await this.getWorks(params.cookies, {- queryType: '2',- });- console.log(worksList);- const work = worksList.data.data.list.find(- (v) => v.unPublishCoverKey === coverRes.data.data.coverKey,- );- if (!work) throw '作品查询失败!';+ let work: KwaiWorkItem | undefined;+ await RetryWhile(async () => {+ const worksList = await this.getWorks(params.cookies, {+ queryType: '2',+ limit: 20,+ });+ console.log('worksList:', worksList);+ work = worksList.data.data.list.find(+ (v) => v.unPublishCoverKey === coverRes.data.data.coverKey,+ );+ console.log('work:', work);+ if (work) return true;+ }, 5);console.log('发布成功!');resolve({shareLink: ``,diff --git a/electron/plat/Kwai/kwai.type.ts b/electron/plat/Kwai/kwai.type.tsindex 73d1599b..95e91fcc 100644--- a/electron/plat/Kwai/kwai.type.ts+++ b/electron/plat/Kwai/kwai.type.ts@@ -188,38 +188,40 @@ export type RefreshWorksResponse = IKwaiUserCommonResponse<{}[];}>;+export type KwaiWorkItem = {+ publishId: number;+ workId: string;+ title: string;+ publishCoverUrl: string;+ unPublishCoverKey: string | null;+ userId: number;+ userIdStr: string;+ userName: string;+ userHead: string;+ playCount: number;+ likeCount: number;+ commentCount: number;+ uploadTime: number;+ durationSecond: number;+ judgementTitle: string;+ judgementStatus: number;+ publishStatus: number;+ operations: string[];+ publishType: number;+ photoStatus: number;+ photoTop: boolean;+ collectionTitle: string;+ collectionId: number;+ awdId: number;+ hotspotActivity: null;+ hotspot: null;+ showAtlasIcon: boolean;+ showDuration: boolean;+};+// 获取作品,开发者后台export type GetWorksListResponse = IKwaiUserCommonResponse<{- list: {- publishId: number;- workId: string;- title: string;- publishCoverUrl: string;- unPublishCoverKey: string | null;- userId: number;- userIdStr: string;- userName: string;- userHead: string;- playCount: number;- likeCount: number;- commentCount: number;- uploadTime: number;- durationSecond: number;- judgementTitle: string;- judgementStatus: number;- publishStatus: number;- operations: string[];- publishType: number;- photoStatus: number;- photoTop: boolean;- collectionTitle: string;- collectionId: number;- awdId: number;- hotspotActivity: null;- hotspot: null;- showAtlasIcon: boolean;- showDuration: boolean;- }[];+ list: KwaiWorkItem[];}>;// 获取作品列表diff --git a/electron/plat/douyin/index.ts b/electron/plat/douyin/index.tsindex c9ea05a5..2fa3eb84 100644--- a/electron/plat/douyin/index.ts+++ b/electron/plat/douyin/index.ts@@ -24,6 +24,7 @@ import {import requestNet from '../requestNet';import { jsonToQueryString } from '../../util';import { DeclarationDouyin } from './common.douyin';+import { RetryWhile } from '../../../commont/utils';export type DouyinPlatformSettingType = {// 自主声明@@ -1482,54 +1483,62 @@ export class DouyinService {`上传视频(${i}/${filePartInfo.blockInfo.length})`,);console.log(`开始上传第 ${parseInt(i) + 1} 个分片...`);- // 设置当前文件分片信息- const nowUploadParams = JSON.parse(JSON.stringify(uploadParams));- nowUploadParams['part_number'] = parseInt(i) + 1;- nowUploadParams['part_offset'] = parseInt(i) * this.fileBlockSize;-- // 获取分片内容- const chunkStart =- i === '0' ? 0 : filePartInfo.blockInfo[parseInt(i) - 1];- const chunkEnd = filePartInfo.blockInfo[i] - 1;- const chunkContent = await FileUtils.getFilePartContent(- filePath,- chunkStart,- chunkEnd,- );+ let errorMsg = '';+ const isSuccess = await RetryWhile(async () => {+ // 设置当前文件分片信息+ const nowUploadParams = JSON.parse(JSON.stringify(uploadParams));+ nowUploadParams['part_number'] = parseInt(i) + 1;+ nowUploadParams['part_offset'] = parseInt(i) * this.fileBlockSize;++ // 获取分片内容+ const chunkStart =+ i === '0' ? 0 : filePartInfo.blockInfo[parseInt(i) - 1];+ const chunkEnd = filePartInfo.blockInfo[i] - 1;+ const chunkContent = await FileUtils.getFilePartContent(+ filePath,+ chunkStart,+ chunkEnd,+ );- // 获取文件crc32- const fileCrc32 = crc32(chunkContent).toString(16);-- // 执行分片上传- const uploadPartRes = await this.uploadFile(- uploadUrl + '?' + this.httpBuildQuery(nowUploadParams),- chunkContent,- {- Authorization: uploadNodes.StoreInfos[0].Auth,- 'Content-Crc32': fileCrc32,- 'Content-Type': 'application/octet-stream',- 'X-Logical-Part-Mode':- uploadNodes.UploadHeader['X-Logical-Part-Mode'],- 'X-Storage-U': userUid,- },- 'POST',- );- console.log(`第 ${parseInt(i) + 1} 个分片上传结果:`, uploadPartRes);+ // 获取文件crc32+ const fileCrc32 = crc32(chunkContent).toString(16);++ // 执行分片上传+ const uploadPartRes = await this.uploadFile(+ uploadUrl + '?' + this.httpBuildQuery(nowUploadParams),+ chunkContent,+ {+ Authorization: uploadNodes.StoreInfos[0].Auth,+ 'Content-Crc32': fileCrc32,+ 'Content-Type': 'application/octet-stream',+ 'X-Logical-Part-Mode':+ uploadNodes.UploadHeader['X-Logical-Part-Mode'],+ 'X-Storage-U': userUid,+ },+ 'POST',+ );+ console.log(`第 ${parseInt(i) + 1} 个分片上传结果:`, uploadPartRes);- if (uploadPartRes === null) {- reject('上传文件失败');- return false;- }+ if (uploadPartRes === null) {+ errorMsg = '上传文件失败';+ return false;+ }- if (uploadPartRes.code !== 2000) {- reject(uploadPartRes.message);- return false;- }+ if (uploadPartRes.code !== 2000) {+ errorMsg = uploadPartRes.message;+ return false;+ }+ // 上传分片成功+ uploadBlockRes.push(+ `${uploadPartRes.data.part_number}:${uploadPartRes.data.crc32}`,+ );+ return true;+ }, 3);- // 上传分片成功- uploadBlockRes.push(- `${uploadPartRes.data.part_number}:${uploadPartRes.data.crc32}`,- );+ if (!isSuccess) {+ reject(errorMsg);+ break;+ }}// 分片上传完成,合并分片diff --git a/electron/plat/shipinhao/index.ts b/electron/plat/shipinhao/index.tsindex 77823e02..42df7909 100644--- a/electron/plat/shipinhao/index.ts+++ b/electron/plat/shipinhao/index.ts@@ -14,6 +14,7 @@ import {WxSPHGetMixListResponse,} from './wxShp.type';import { v4 as uuidv4 } from 'uuid';+import { RetryWhile } from '../../../commont/utils';interface UserInfo {authorId: string;nickname: string;@@ -209,7 +210,7 @@ export class ShipinhaoService {timestamp: new Date().getTime(),},});-+if (res.errCode === 0) {if (endDate && startDate) {// 如果传入了日期范围,返回数组格式@@ -693,47 +694,55 @@ export class ShipinhaoService {}const uploadId = uploadIdRes.UploadID;- const uploadPartInfo = [];+ const uploadPartInfo: any[] = [];// 分片上传文件for (let i = 0; i < filePartInfo.blockInfo.length; i++) {- if (this.callback)- this.callback(- 50,- `上传视频(${i}/${filePartInfo.blockInfo.length})`,+ let errorMsg = '';+ const isSuccess = await RetryWhile(async () => {+ if (this.callback)+ this.callback(+ 50,+ `上传视频(${i}/${filePartInfo.blockInfo.length})`,+ );+ console.log(+ `开始上传第 ${i + 1}/${filePartInfo.blockInfo.length} 个分片`,+ );+ const chunkStart = i === 0 ? 0 : filePartInfo.blockInfo[i - 1];+ const chunkEnd = filePartInfo.blockInfo[i] - 1;+ const chunkContent = await FileUtils.getFilePartContent(+ filePath,+ chunkStart,+ chunkEnd,);- console.log(- `开始上传第 ${i + 1}/${filePartInfo.blockInfo.length} 个分片`,- );- const chunkStart = i === 0 ? 0 : filePartInfo.blockInfo[i - 1];- const chunkEnd = filePartInfo.blockInfo[i] - 1;- const chunkContent = await FileUtils.getFilePartContent(- filePath,- chunkStart,- chunkEnd,- );- // 开始上传- const uploadUrl = `${this.uploadpartdfsUrl}?UploadID=${uploadId}&PartNumber=${i + 1}&QuickUpload=2`;- const uploadPartRes = await this.uploadFile(uploadUrl, chunkContent, {- Authorization: uploadParams.authKey,- 'X-Arguments': uploadArgumentsString,- 'Content-Type': 'application/octet-stream',- });+ // 开始上传+ const uploadUrl = `${this.uploadpartdfsUrl}?UploadID=${uploadId}&PartNumber=${i + 1}&QuickUpload=2`;+ const uploadPartRes = await this.uploadFile(uploadUrl, chunkContent, {+ Authorization: uploadParams.authKey,+ 'X-Arguments': uploadArgumentsString,+ 'Content-Type': 'application/octet-stream',+ });- if (!uploadPartRes?.ETag) {- throw new Error(- '上传视频失败,失败原因3:' + uploadPartRes.data?.['X-Errno'] ||- '未知错误',- );- }+ if (!uploadPartRes?.ETag) {+ errorMsg =+ '上传视频失败,失败原因3:' + uploadPartRes.data?.['X-Errno'] ||+ '未知错误';+ console.error(errorMsg);+ }- // 上传成功- uploadPartInfo.push({- PartNumber: i + 1,- ETag: uploadPartRes.ETag,- });- console.log(`第 ${i + 1} 个分片上传成功`);+ // 上传成功+ uploadPartInfo.push({+ PartNumber: i + 1,+ ETag: uploadPartRes.ETag,+ });+ console.log(`第 ${i + 1} 个分片上传成功`);++ return true;+ }, 3);+ if (!isSuccess) {+ throw new Error(errorMsg);+ }}const completeBody = {diff --git a/electron/plat/xiaohongshu/index.ts b/electron/plat/xiaohongshu/index.tsindex 773fd5b9..1d6ddc44 100644--- a/electron/plat/xiaohongshu/index.ts+++ b/electron/plat/xiaohongshu/index.ts@@ -13,6 +13,7 @@ import {XhsCommentPostResponse,XiaohongshuApiResponse,} from './xiaohongshu.type';+import { RetryWhile } from '../../../commont/utils';export type XSLPlatformSettingType = {// 标题@@ -170,10 +171,6 @@ export class XiaohongshuService {// Monitor cookie status with intervalthis.cookieIntervalList[winContentsId] = setInterval(async () => {try {- console.log(- this.win!.webContents.getURL().includes(this.loginUrlHome),- );- console.log(this.win!.webContents.getURL().includes(this.loginUrl));if (this.win!.webContents.getURL().includes(this.loginUrlHome)) {const cookies2 = await session.fromPartition(partition)@@ -220,7 +217,7 @@ export class XiaohongshuService {console.error('Failed to get cookies:', error);reject(new Error('Failed to get website cookies'));}- }, 3000); // Check every 3 seconds+ }, 1500); // Check every 3 seconds});}@@ -324,7 +321,7 @@ export class XiaohongshuService {// 处理30天的数据const dataList = [];const startTimestamp = new Date(startDate).getTime();- const endTimestamp = new Date(endDate).getTime()+1;+ const endTimestamp = new Date(endDate).getTime() + 1;// 获取所有列表数据const rise_fans_list = userInfo.data.thirty.rise_fans_list || [];@@ -715,7 +712,7 @@ export class XiaohongshuService {}// 分片上传文件- const uploadPartInfo = [];+ const uploadPartInfo: any[] = [];for (const i in filePartInfo.blockInfo) {if (this.callback)@@ -723,40 +720,46 @@ export class XiaohongshuService {50,`上传视频(${i}/${filePartInfo.blockInfo.length})`,);+ const isSuccess = await RetryWhile(async () => {+ const chunkStart =+ i === '0' ? 0 : filePartInfo.blockInfo[parseInt(i) - 1];+ const chunkEnd = filePartInfo.blockInfo[i] - 1;+ const chunkContent = await FileUtils.getFilePartContent(+ filePath,+ chunkStart,+ chunkEnd,+ );- const chunkStart =- i === '0' ? 0 : filePartInfo.blockInfo[parseInt(i) - 1];- const chunkEnd = filePartInfo.blockInfo[i] - 1;- const chunkContent = await FileUtils.getFilePartContent(- filePath,- chunkStart,- chunkEnd,- );-- // 开始上传- const uploadPartRes = await this.uploadFile(- uploadBaseUrl +- `?uploadId=${uploadId}&partNumber=${parseInt(i) + 1}`,- chunkContent,- {- Referer: this.loginUrl,- 'X-Cos-Security-Token': uploadToken,- },- );+ // 开始上传+ const uploadPartRes = await this.uploadFile(+ uploadBaseUrl ++ `?uploadId=${uploadId}&partNumber=${parseInt(i) + 1}`,+ chunkContent,+ {+ Referer: this.loginUrl,+ 'X-Cos-Security-Token': uploadToken,+ },+ );- const headers = uploadPartRes.headers;- if (!headers.hasOwnProperty('etag') || headers['etag'] === '') {+ const headers = uploadPartRes.headers;+ if (!headers.hasOwnProperty('etag') || headers['etag'] === '') {+ return false;+ }++ // 分片上传成功+ uploadPartInfo.push({+ Part: {+ PartNumber: parseInt(i) + 1,+ ETag: headers['etag'],+ },+ });+ return true;+ }, 3);++ if (!isSuccess) {reject('上传视频失败,失败原因:上传分片失败');- return;+ break;}-- // 分片上传成功- uploadPartInfo.push({- Part: {- PartNumber: parseInt(i) + 1,- ETag: headers['etag'],- },- });}// 合并分片@@ -1383,7 +1386,7 @@ export class XiaohongshuService {// 生成搜索ID的函数function base36encode(number: number): string {const digits = '0123456789abcdefghijklmnopqrstuvwxyz';- let base36 = "";+ let base36 = '';while (number > 0) {const remainder = number % 36;base36 = digits[remainder] + base36;@@ -1398,7 +1401,10 @@ export class XiaohongshuService {return base36encode(Number(timestamp + randomValue));}- console.log('------ getSearchNodeList --- generateSearchId::', generateSearchId());+ console.log(+ '------ getSearchNodeList --- generateSearchId::',+ generateSearchId(),+ );console.log('------ getSearchNodeList --- asdadsda::', qe, page);const body = {diff --git a/src/icp/publish.ts b/src/icp/publish.tsindex 67b06af8..cb084b66 100644--- a/src/icp/publish.ts+++ b/src/icp/publish.ts@@ -34,6 +34,7 @@ import { parseTopicString } from '../utils';import { PublishVideoResult } from '../../electron/main/plat/module';import { ImgTextModel } from '../../electron/db/models/imgText';import type { pubRecordListQuery } from '../../electron/global/table';+import { PubStatus } from '../../electron/db/models/pubRecord';// 创建发布记录export async function icpCreatePubRecord(pubRecord: Partial<PubRecordModel>) {@@ -43,6 +44,7 @@ export async function icpCreatePubRecord(pubRecord: Partial<PubRecordModel>) {{...pubRecord,id: undefined,+ status: PubStatus.UNPUBLISH,},);return res;diff --git a/src/views/publish/children/videoPage/useVideoPageStore.ts b/src/views/publish/children/videoPage/useVideoPageStore.tsindex 299d63df..87b9e9e0 100644--- a/src/views/publish/children/videoPage/useVideoPageStore.ts+++ b/src/views/publish/children/videoPage/useVideoPageStore.ts@@ -398,10 +398,12 @@ export const useVideoPageStore = create(try {methods.setOperateId();- commonPubParams = {- ...pubRecord,- describe: pubRecord?.desc,- };+ for (const key in commonPubParams) {+ if (pubRecord?.[key as 'title']) {+ commonPubParams[key as 'title'] = pubRecord![key as 'title'];+ }+ }+ commonPubParams['describe'] = pubRecord?.desc;if (pubRecord!.commonCoverPath) {const cover = await getImgFile(pubRecord!.commonCoverPath);@@ -450,12 +452,10 @@ export const useVideoPageStore = create(coverFileMap.set(coverPath, cover);const pubParams = {- ...pubRecord,+ ...commonPubParams,cover: cover,describe: pubRecord.desc,};- pubParams.id = undefined;- pubParams.failMsg = '';videoListChoose.push({id: generateUUID(),