Let's use AI to Earn!
TypeScript auto-publishdouyindouyin-apielectron-appelectron-reactkuaishoukwaipublishedshipinhaotoolxiaohongshu
feat: 添加消息提示(为了展示发布进度)
gaoSir4223276852f2
diff --git a/src/app/layout/BellMessage/bellMessage.module.scss b/src/app/layout/BellMessage/bellMessage.module.scssnew file mode 100644index 00000000..96137de9--- /dev/null+++ b/src/app/layout/BellMessage/bellMessage.module.scss@@ -0,0 +1,84 @@+.bellMessage {+ display: flex;+ width: 600px;+ height: 500px;+ :global {+ .bellMessage-menu {+ width: 200px;+ border-right: 1px solid var(--grayColor2);+ height: 100%;+ box-sizing: border-box;+ display: flex;+ flex-direction: column;+ .ant-menu {+ height: 100%;+ border-right: none;+ }+ &-title {+ font-weight: 900;+ font-size: var(--fs-sm);+ color: var(--grayColor10);+ padding: 0 0 0 18px;+ margin: 18px 0 10px 0;+ position: relative;+ &:after {+ content: "";+ display: flex;+ position: absolute;+ top: 50%;+ left: 0;+ transform: translateY(-50%);+ width: 2px;+ height: 70%;+ background: var(--colorPrimary5);+ }+ }+ }++ .bellMessage-content {+ box-sizing: border-box;+ height: 100%;+ width: 100%;+ overflow-y: auto;+ &-item {+ cursor: pointer;+ padding: 15px;+ border-bottom: 1px solid var(--grayColor2);+ background: transparent;+ transition: 0.3s;+ &-title {+ font-weight: 900;+ text-overflow: ellipsis;+ white-space: nowrap;+ overflow: hidden;+ width: 100%;+ }+ &-des {+ margin: 5px 0;+ }+ &-time {+ color: var(--grayColor6);+ font-size: var(--fs-xs);+ }+ &:hover {+ background: var(--grayColor0);+ }+ }+ &-empty {+ width: 100%;+ height: 100%;+ display: flex;+ justify-content: center;+ align-items: center;+ }+ }+ }+}++.bellMessagePopover {+ :global {+ .ant-popover-inner {+ padding: 0;+ }+ }+}\ No newline at end of filediff --git a/src/app/layout/BellMessage/index.tsx b/src/app/layout/BellMessage/index.tsxnew file mode 100644index 00000000..2675e904--- /dev/null+++ b/src/app/layout/BellMessage/index.tsx@@ -0,0 +1,155 @@+import { ForwardedRef, forwardRef, memo, useMemo, useState } from "react";+import styles from "./bellMessage.module.scss";+import { Empty, Menu, MenuProps, Popover, Tag } from "antd";+import { useShallow } from "zustand/react/shallow";+import { NoticeType, useBellMessageStroe } from "@/store/bellMessageStroe";+import { formatTime } from "@/utils";+import PubProgressModule from "@/app/[lng]/publish/components/PubProgressModule/PubProgressModule";+import { PubStatus } from "@/app/config/publishConfig";++export interface IBellmessageRef {}++export interface IBellmessageProps {+ children?: React.ReactNode;+}++type MenuItem = Required<MenuProps>["items"][number];+const menuItems: MenuItem[] = [+ {+ key: NoticeType.PubNotice,+ label: "发布通知",+ },+ // {+ // key: '1',+ // label: '系统通知',+ // },+ // {+ // key: `2`,+ // label: '更新公告',+ // },+ // {+ // key: `3`,+ // label: '私信通知',+ // },+ // {+ // key: `4`,+ // label: '任务通知',+ // },+];++export const PubRecordStatusTag = ({ status }: { status: PubStatus }) => {+ switch (status) {+ case 2:+ return <Tag color="error">全部发布失败</Tag>;+ case 1:+ return <Tag color="success">全部发布成功</Tag>;+ case 3:+ return <Tag color="warning">部分发布成功</Tag>;+ case 0:+ return <Tag color="processing">正在发布</Tag>;+ }+};++const Bellmessage = memo(+ forwardRef(+ ({ children }: IBellmessageProps, ref: ForwardedRef<IBellmessageRef>) => {+ const [menuKey, setMenuKey] = useState<string>(NoticeType.PubNotice);+ const { noticeMap } = useBellMessageStroe(+ useShallow((state) => ({+ noticeMap: state.noticeMap,+ })),+ );+ const [progressOpen, setProgressOpen] = useState(false);+ const [pubProgressData, setPubProgressData] = useState<any[]>([]);+ const [open, setOpen] = useState(false);++ const noticeList = useMemo(() => {+ return noticeMap.get(NoticeType.PubNotice) || [];+ }, [noticeMap]);++ return (+ <>+ <PubProgressModule+ pubProgressData={pubProgressData}+ open={progressOpen}+ onClose={() => setProgressOpen(false)}+ />+ <Popover+ open={open}+ onOpenChange={(newOpen) => setOpen(newOpen)}+ rootClassName={styles.bellMessagePopover}+ placement="bottomLeft"+ content={+ <>+ <div className={styles.bellMessage}>+ <div className="bellMessage-menu">+ <p className="bellMessage-menu-title">消息中心</p>+ <Menu+ selectedKeys={[NoticeType.PubNotice]}+ inlineIndent={15}+ mode="inline"+ items={menuItems}+ onClick={(e) => {+ setMenuKey(e.key);+ }}+ />+ </div>++ <div className="bellMessage-content">+ {noticeList.length === 0 ? (+ <div className="bellMessage-content-empty">+ <Empty />+ </div>+ ) : (+ <>+ {noticeList.map((v) => {+ return (+ <div+ className="bellMessage-content-item"+ onClick={() => {+ switch (menuKey) {+ case NoticeType.PubNotice:+ setOpen(false);+ setPubProgressData(v.pub!.progressList);+ setProgressOpen(true);+ break;+ }+ }}+ key={v.id}+ >+ <div+ className="bellMessage-content-item-title"+ title={v.title}+ >+ {v.title}+ </div>+ <div className="bellMessage-content-item-des">+ {menuKey === NoticeType.PubNotice ? (+ <PubRecordStatusTag status={v.pub!.status} />+ ) : (+ <></>+ )}+ </div>+ <div className="bellMessage-content-item-time">+ {formatTime(v.time)}+ </div>+ </div>+ );+ })}+ </>+ )}+ </div>+ </div>+ </>+ }+ >+ {children}+ </Popover>+ </>+ );+ },+ ),+);+Bellmessage.displayName = "Bellmessage";++export default Bellmessage;diff --git a/src/app/layout/LyaoutHeader.tsx b/src/app/layout/LyaoutHeader.tsxindex 0badcf2d..011978ed 100644--- a/src/app/layout/LyaoutHeader.tsx+++ b/src/app/layout/LyaoutHeader.tsx@@ -10,9 +10,14 @@ import { NoSSR } from "@kwooshung/react-no-ssr";import { Button, Dropdown, MenuProps } from "antd";import logo from "@/assets/images/logo.png";import defaultAvatar from "./images/defaultAvatar.jpg";-import { CaretDownOutlined, GlobalOutlined } from "@ant-design/icons";+import {+ BellOutlined,+ CaretDownOutlined,+ GlobalOutlined,+} from "@ant-design/icons";import { useRouter } from "next/navigation";import { useTransClient } from "@/app/i18n/client";+import Bellmessage from "@/app/layout/BellMessage";export interface ILyaoutHeaderRef {}@@ -32,7 +37,7 @@ function UserInfo() {router.push("/profile");}}>- {t('profile')}+ {t("profile")}</div>),},@@ -45,7 +50,7 @@ function UserInfo() {router.push("/");}}>- {t('logout')}+ {t("logout")}</div>),},@@ -63,7 +68,7 @@ function UserInfo() {height={35}/><div className={styles["layoutHeader-userinfo-name"]}>- {userInfo.name || t('unknownUser')}+ {userInfo.name || t("unknownUser")}</div><CaretDownOutlined /></div>@@ -82,7 +87,9 @@ const LyaoutHeader = memo(const toggleLanguage = () => {const newLng = userStore.lang === "zh-CN" ? "en" : "zh-CN";userStore.setLang(newLng);- router.push(`/${newLng}${location.pathname.replace(`/${userStore.lang}`, "")}`);+ router.push(+ `/${newLng}${location.pathname.replace(`/${userStore.lang}`, "")}`,+ );};useEffect(() => {@@ -115,6 +122,12 @@ const LyaoutHeader = memo(className={styles["layoutHeader_wrapper-right"]}suppressHydrationWarning={true}>+ <Bellmessage>+ <div style={{ cursor: "pointer" }}>+ <BellOutlined />+ <span style={{ marginLeft: "5px" }}>消息</span>+ </div>+ </Bellmessage><Buttontype="text"icon={<GlobalOutlined />}@@ -132,7 +145,7 @@ const LyaoutHeader = memo(router.push("/login");}}>- {t('login')}+ {t("login")}</Button>)}</NoSSR>diff --git a/src/app/plat/PlatBase.ts b/src/app/plat/PlatBase.tsindex 41ba73d7..d8575278 100644--- a/src/app/plat/PlatBase.ts+++ b/src/app/plat/PlatBase.ts@@ -1,5 +1,10 @@import { SocialAccount } from "@/api/types/account.type";-import { IPlatConstrParams } from "@/app/plat/plat.type";+import {+ IPlatConstrParams,+ IPublishResult,+ IVideoPublishItem,+ PubProgressType,+} from "@/app/plat/plat.type";export abstract class PlatBase {access_token: string;@@ -12,4 +17,11 @@ export abstract class PlatBase {this.access_token = params.access_token;this.refresh_token = params.refresh_token;}++ publishVideo(+ videoPubParams: IVideoPublishItem,+ onProgress: PubProgressType,+ ): Promise<IPublishResult> {+ throw new Error("Method not implemented.");+ }}diff --git a/src/app/plat/PlatManage.ts b/src/app/plat/PlatManage.tsindex 67f18047..031a28bf 100644--- a/src/app/plat/PlatManage.ts+++ b/src/app/plat/PlatManage.ts@@ -1,11 +1,42 @@import { PlatType } from "@/app/config/platConfig";+import { KwaiPlat } from "@/app/plat/platChildren/kwai/KwaiPlat";+import { PlatBase } from "@/app/plat/PlatBase";+import {+ IPlatConstrParams,+ IPublishResult,+ IVideoPublishItem,+} from "@/app/plat/plat.type";class PlatManage {- private getPlat(type: PlatType) {+ private getPlat(type: PlatType, params: IPlatConstrParams): PlatBase {switch (type) {case PlatType.KWAI:- return;+ return new KwaiPlat(params);}+ return new KwaiPlat(params);+ }++ public async publishVideo(+ pubArr: {+ videoPubParams: IVideoPublishItem;+ platType: PlatType;+ access_token: string;+ refresh_token: string;+ }[],+ ) {+ const task: Promise<IPublishResult>[] = [];+ for (const pub of pubArr) {+ task.push(+ this.getPlat(pub.platType, {+ access_token: pub.access_token,+ refresh_token: pub.refresh_token,+ }).publishVideo(pub.videoPubParams, (progress, msg) => {+ console.log(progress, msg);+ }),+ );+ }+ const pubRes = await Promise.all(task);+ console.log(pubRes);}}export const platManage = new PlatManage();diff --git a/src/app/plat/plat.type.ts b/src/app/plat/plat.type.tsindex 06980fd6..5f7a6c16 100644--- a/src/app/plat/plat.type.ts+++ b/src/app/plat/plat.type.ts@@ -1,7 +1,7 @@// plat构造器参数import { SocialAccount } from "@/api/types/account.type";-import {IPubParams} from "@/app/[lng]/publish/videoPage/videoPage.type";-import {IVideoFile} from "@/app/[lng]/publish/components/Choose/VideoChoose";+import { IPubParams } from "@/app/[lng]/publish/videoPage/videoPage.type";+import { IVideoFile } from "@/app/[lng]/publish/components/Choose/VideoChoose";export interface IPlatConstrParams {access_token: string;@@ -47,3 +47,16 @@ export interface PublishRes {export interface IVideoPublishItem extends IPubParams {video: IVideoFile;}++// 发布进度+export type PubProgressType = (progress: number, msg: string) => void;++// 发布结果+export interface IPublishResult {+ // 是否成功+ success: boolean;+ // 失败消息+ failMsg?: string;+ worksId: string;+ worksUrl: string;+}diff --git a/src/app/plat/platChildren/kwai/KwaiPlat.ts b/src/app/plat/platChildren/kwai/KwaiPlat.tsindex ff4a8b2d..9cf8009a 100644--- a/src/app/plat/platChildren/kwai/KwaiPlat.ts+++ b/src/app/plat/platChildren/kwai/KwaiPlat.ts@@ -5,9 +5,11 @@ import { requestPlatApi } from "@/utils/otherRequest";import { KwaiApiProxyUrl } from "@/constant";import { kwaiAppId } from "@/app/[lng]/accounts/plat/kwaiLogin";import { PlatType } from "@/app/config/platConfig";+import {IPublishResult, IVideoPublishItem, PubProgressType} from "@/app/plat/plat.type";+import { KwaiPubCore } from "@/app/plat/platChildren/kwai/KwaiPubCore";export class KwaiPlat extends PlatBase {- async getAccountInfo(): Promise<Partial<SocialAccount> | null> {+ public async getAccountInfo(): Promise<Partial<SocialAccount> | null> {const { user_info } = await this.request({url: "openapi/user_info",method: "GET",@@ -32,4 +34,17 @@ export class KwaiPlat extends PlatBase {};return requestPlatApi(params);}++ public async publishVideo(+ videoPubParams: IVideoPublishItem,+ onProgress: PubProgressType,+ ): Promise<IPublishResult> {+ const kwaiPubCore = new KwaiPubCore(this, videoPubParams, onProgress);+ const pubRes = await kwaiPubCore.publishVideo();+ return {+ worksId: pubRes.worksId,+ worksUrl: pubRes.worksUrl,+ success: true,+ };+ }}diff --git a/src/app/plat/platChildren/kwai/KwaiPubCore.ts b/src/app/plat/platChildren/kwai/KwaiPubCore.tsindex c1311199..33b69875 100644--- a/src/app/plat/platChildren/kwai/KwaiPubCore.ts+++ b/src/app/plat/platChildren/kwai/KwaiPubCore.ts@@ -1,28 +1,44 @@import { KwaiPlat } from "@/app/plat/platChildren/kwai/KwaiPlat";-import { IVideoPublishItem, PublishRes } from "@/app/plat/plat.type";+import {+ IVideoPublishItem,+ PublishRes,+ PubProgressType,+} from "@/app/plat/plat.type";import { calculateChunks, readBlobRange } from "@/app/plat/plat.util";-class KwaiPubCore {- kwaiPlat: KwaiPlat;- videoPubParams: IVideoPublishItem;- fileBlockSize = 4194304;+export class KwaiPubCore {+ private kwaiPlat: KwaiPlat;+ private videoPubParams: IVideoPublishItem;+ private fileBlockSize = 4194304;+ // 发布进度+ private readonly onProgress: PubProgressType;- constructor(kwaiPlat: KwaiPlat, pubParams: IVideoPublishItem) {+ constructor(+ kwaiPlat: KwaiPlat,+ pubParams: IVideoPublishItem,+ onProgress: PubProgressType,+ ) {this.kwaiPlat = kwaiPlat;this.videoPubParams = pubParams;+ this.onProgress = onProgress;}// 视频发布async publishVideo(): Promise<PublishRes> {- const startUploadInfo = await this.startUploadVideo();+ const startUploadInfo = await this._startUploadVideo();+ this.onProgress(10, "发起上传完成...");+// 获取分片的大小const chunkRange = calculateChunks(this.videoPubParams.video.size,this.fileBlockSize,);+ this.onProgress(20, "分片大小获取完成...");// 分片上传for (let i = 0; i < chunkRange.length; i++) {+ this.onProgress(50, `正在分片上传视频:${i} / ${chunkRange.length}`);+const range = chunkRange[i];// 获取要上传的视频分片const chunk = await readBlobRange(@@ -57,8 +73,12 @@ class KwaiPubCore {upload_token: startUploadInfo.upload_token,},});+ this.onProgress(70, `正在发布视频...`);+ console.log("分片上传完成:", completeRes);const formData = new FormData();+ formData.append("caption", " #分享转发 标题1 #推广昨品 ");+ formData.append("cover", this.videoPubParams.cover!.file);const pubRes = await this.kwaiPlat.request({url: "/kuaishoApi/openapi/photo/publish",method: "POST",@@ -70,10 +90,16 @@ class KwaiPubCore {},data: formData,});+ console.log(pubRes);++ return {+ worksId: "",+ worksUrl: "",+ };}// 发起上传- async startUploadVideo() {+ private async _startUploadVideo() {const res = await this.kwaiPlat.request({url: "openapi/photo/start_upload",method: "GET",