Let's use AI to Earn!
TypeScript auto-publishdouyindouyin-apielectron-appelectron-reactkuaishoukwaipublishedshipinhaotoolxiaohongshu
feat: 1. 项目中的所有用户数据引用改为全局。 2.导入发布记录完成。
gaoSir0ab31fe30b5b
diff --git a/src/layout/LayoutBody.tsx b/src/layout/LayoutBody.tsxindex cd7e7244..d2fd0f3b 100644--- a/src/layout/LayoutBody.tsx+++ b/src/layout/LayoutBody.tsx@@ -3,6 +3,7 @@ import { useEffect } from 'react';import { Navigate, Outlet } from 'react-router-dom';import Navigation from './Navigation';import styles from './layoutBody.module.scss';+import { useAccountStore } from '../store/account';export const LayoutBody = () => {const userStore = useUserStore();@@ -24,11 +25,20 @@ export const LayoutBody = () => {}};document.addEventListener('keydown', handleKeyDown);+return () => {document.removeEventListener('keydown', handleKeyDown);};}, []);+ useEffect(() => {+ if (userStore.token) {+ useAccountStore.getState().init();+ } else {+ useAccountStore.getState().clear();+ }+ }, [userStore.token]);+if (!userStore.token) {return <Navigate to="/login" replace />;}diff --git a/src/store/account.ts b/src/store/account.tsnew file mode 100644index 00000000..fb29b029--- /dev/null+++ b/src/store/account.ts@@ -0,0 +1,69 @@+import { create } from 'zustand';+import { combine } from 'zustand/middleware';+import lodash from 'lodash';+import { AccountInfo } from '../views/account/comment';+import { icpGetAccountList } from '../icp/account';+import { onAccountLoginFinish } from '../icp/receiveMsg';++export interface IAccountStore {+ accountList: AccountInfo[];+ accountMap: Map<number, AccountInfo>;+ unBindFn?: () => void;+}++const store: IAccountStore = {+ accountList: [],+ accountMap: new Map([]),+ unBindFn: undefined,+};++const getStore = () => {+ return lodash.cloneDeep(store);+};++// 视频发布所有组件的共享状态和方法+export const useAccountStore = create(+ combine(+ {+ ...getStore(),+ },+ (set, get, storeApi) => {+ const methods = {+ clear() {+ set({+ ...getStore(),+ });+ if (get().unBindFn) get().unBindFn!();+ },++ async getAccountList() {+ const accountMap = new Map<number, AccountInfo>([]);+ const result = await icpGetAccountList();+ if (!result) return;++ for (const item of result) {+ accountMap.set(item.id, item);+ }++ set({+ accountList: result,+ accountMap,+ });+ },++ async init() {+ methods.getAccountList();++ const unBindFn = onAccountLoginFinish(() => {+ methods.getAccountList();+ });++ set({+ unBindFn,+ });+ },+ };+ return methods;+ },+ ),+);diff --git a/src/store/pubStroe.ts b/src/store/pubStroe.tsindex 50948b4e..435ce804 100644--- a/src/store/pubStroe.ts+++ b/src/store/pubStroe.ts@@ -24,6 +24,12 @@ export const usePubStroe = createPersistStore(},(set, _get) => {return {+ clear() {+ set({+ ...state,+ });+ },+setMoreParamsOpen(moreParamsOpen: boolean) {set({moreParamsOpen,diff --git a/src/store/user.ts b/src/store/user.tsindex 4efe1f0e..ab85fbaf 100644--- a/src/store/user.ts+++ b/src/store/user.ts@@ -3,6 +3,8 @@ import { IRefreshToken, IUserInfo } from '@/api/types/user-t';import { userApi } from '@/api/user';import { StoreKey } from '@/utils/StroeEnum';import router from '@/router/index';+import { usePubStroe } from './pubStroe';+import { useAccountStore } from './account';export interface IUserStore {userInfo?: IUserInfo;@@ -28,6 +30,8 @@ export const useUserStore = createPersistStore(// 清除登录状态clearLoginStatus() {set({ ...state });+ usePubStroe.getState().clear();+ useAccountStore.getState().clear();},// 退出登录diff --git a/src/views/account/components/AccountSidebar/AccountSidebar.tsx b/src/views/account/components/AccountSidebar/AccountSidebar.tsxindex 91fd36f4..152505c6 100644--- a/src/views/account/components/AccountSidebar/AccountSidebar.tsx+++ b/src/views/account/components/AccountSidebar/AccountSidebar.tsx@@ -1,19 +1,8 @@-import {- ForwardedRef,- forwardRef,- memo,- useEffect,- useRef,- useState,-} from 'react';+import { ForwardedRef, forwardRef, memo, useRef, useState } from 'react';import styles from './AccountSidebar.module.scss';import { AccountInfo, AccountPlatInfoMap } from '../../comment';import { Avatar, Button, message, Popover } from 'antd';-import {- accountLogin,- acpAccountLoginCheck,- icpGetAccountList,-} from '../../../../icp/account';+import { accountLogin, acpAccountLoginCheck } from '../../../../icp/account';import AddAccountModal from '../AddAccountModal';import { AccountStatus } from '../../../../../commont/AccountEnum';import {@@ -22,10 +11,11 @@ import {WarningOutlined,} from '@ant-design/icons';import useCssVariables from '../../../../hooks/useCssVariables';-import { onAccountLoginFinish } from '../../../../icp/receiveMsg';import PubAccountDetModule, {IPubAccountDetModuleRef,} from '../../../publish/components/PubAccountDetModule/PubAccountDetModule';+import { useShallow } from 'zustand/react/shallow';+import { useAccountStore } from '../../../../store/account';export interface IAccountSidebarRef {}@@ -116,30 +106,14 @@ const AccountSidebar = memo({ activeAccountId, onAccountChange }: IAccountSidebarProps,ref: ForwardedRef<IAccountSidebarRef>,) => {- const [accountList, setAccountList] = useState<AccountInfo[]>([]);const [isAccountModalOpen, setIsAccountModalOpen] = useState(false);const pubAccountDetModuleRef = useRef<IPubAccountDetModuleRef>(null);-- /**- * 获取账户列表- */- const getAccountList = async () => {- try {- const result = await icpGetAccountList();- setAccountList(result || []);- } catch (error) {- console.error('获取账户列表失败', error);- message.error('获取账户列表失败');- }- };-- useEffect(() => {- getAccountList();-- return onAccountLoginFinish(() => {- getAccountList();- });- }, []);+ const { accountList, getAccountList } = useAccountStore(+ useShallow((state) => ({+ accountList: state.accountList,+ getAccountList: state.getAccountList,+ })),+ );return (<>diff --git a/src/views/publish/children/pubRecord/page.tsx b/src/views/publish/children/pubRecord/page.tsxindex f901ff3b..f2c77d59 100644--- a/src/views/publish/children/pubRecord/page.tsx+++ b/src/views/publish/children/pubRecord/page.tsx@@ -1,4 +1,4 @@-import { useEffect, useRef, useState } from 'react';+import { useEffect, useMemo, useState } from 'react';import { PubRecordModel } from '../../comment';import styles from './pubRecord.module.scss';import { icpGetPubRecordList, icpGetPubVideoRecord } from '@/icp/publish';@@ -25,6 +25,7 @@ import { useNavigate } from 'react-router-dom';import { AccountType } from '../../../../../commont/AccountEnum';import WebView from '../../../../components/WebView';import { getVideoFile } from '../../../../components/Choose/VideoChoose';+import { useAccountStore } from '../../../../store/account';export const ImageView = ({prm,@@ -54,15 +55,19 @@ export const ImageView = ({);};-export default function Page() {+export default function Page({+ hegiht = '78vh',+ onChange,+}: {+ hegiht?: string;+ onChange?: (ids: number[]) => void;+}) {const [pulRecardList, setRecardList] = useState<PubRecordModel[]>([]);const [open, setOpen] = useState(false);const [currPubRecordModel, setCurrPubRecordModel] =useState<PubRecordModel>();const [recordLoaidng, setRecordLoaidng] = useState(false);const [pubRecordList, setPubRecordList] = useState<VideoPul[]>([]);- // id=账户id,val=账户item数据- const accountMap = useRef<Map<number, AccountInfo>>(new Map());const navigate = useNavigate();const [examineVideo, setExamineVideo] = useState<{account?: AccountInfo;@@ -77,72 +82,81 @@ export default function Page() {open: false,jsCode: '',});-+ const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);+ const { accountMap } = useAccountStore(+ useShallow((state) => ({+ accountMap: state.accountMap,+ })),+ );const { restartPub } = useVideoPageStore(useShallow((state) => ({restartPub: state.restartPub,})),);- const columns: TableProps<PubRecordModel>['columns'] = [- {- title: '序号',- render: (text, prm, ind) => ind + 1,- width: 70,- key: '序号',- },- {- title: '发布内容',- render: (text, prm) => <ImageView prm={prm} width={50} height={70} />,- width: 200,- key: '发布内容',- },- {- title: '发布时间',- dataIndex: 'publishTime',- key: 'publishTime',- render: (text, prm) => formatTime(prm.publishTime),- width: 200,- },- {- title: '状态',- dataIndex: 'status',- key: 'status',- render: (text, prm) => {- switch (prm.status) {- case 2:- return <Tag color="error">全部发布失败</Tag>;- case 1:- return <Tag color="success">全部发布成功</Tag>;- case 3:- return <Tag color="warning">部分发布成功</Tag>;- }+ const columns = useMemo(() => {+ const columns: TableProps<PubRecordModel>['columns'] = [+ {+ title: '序号',+ render: (text, prm, ind) => ind + 1,+ width: 70,+ key: '序号',},- width: 100,- },- {- title: '操作',- width: 100,- key: '操作',- render: (text, prm) => (- <>- <Button- type="link"- onClick={async () => {- setOpen(true);- setCurrPubRecordModel(prm);- setRecordLoaidng(true);- const res = await icpGetPubVideoRecord(prm.id);- setRecordLoaidng(false);- setPubRecordList(res);- }}- >- 详情- </Button>- </>- ),- },- ];+ {+ title: '发布内容',+ render: (text, prm) => <ImageView prm={prm} width={30} height={50} />,+ width: 200,+ key: '发布内容',+ },+ {+ title: '发布时间',+ dataIndex: 'publishTime',+ key: 'publishTime',+ render: (text, prm) => formatTime(prm.publishTime),+ width: 200,+ },+ {+ title: '状态',+ dataIndex: 'status',+ key: 'status',+ render: (text, prm) => {+ switch (prm.status) {+ case 2:+ return <Tag color="error">全部发布失败</Tag>;+ case 1:+ return <Tag color="success">全部发布成功</Tag>;+ case 3:+ return <Tag color="warning">部分发布成功</Tag>;+ }+ },+ width: 100,+ },+ {+ title: '操作',+ width: 100,+ key: '操作',+ render: (text, prm) => (+ <>+ <Button+ type="link"+ onClick={async (e) => {+ e.stopPropagation();+ setOpen(true);+ setCurrPubRecordModel(prm);+ setRecordLoaidng(true);+ const res = await icpGetPubVideoRecord(prm.id);+ setRecordLoaidng(false);+ setPubRecordList(res);+ }}+ >+ 详情+ </Button>+ </>+ ),+ },+ ];+ return columns;+ }, []);async function GetPubList() {const res = await icpGetPubRecordList({@@ -157,17 +171,29 @@ export default function Page() {};useEffect(() => {- icpGetAccountList().then((res) => {- if (!res) return;- res.map((v) => {- accountMap.current.set(v.id, v);- });- GetPubList();- });- }, []);+ if (onChange) onChange(selectedRowKeys);+ }, [selectedRowKeys]);++ const rowSelection: TableProps<PubRecordModel>['rowSelection'] = {+ onChange: (+ selectedRowKeys: React.Key[],+ selectedRows: PubRecordModel[],+ ) => {+ setSelectedRowKeys(selectedRowKeys as number[]);+ },+ getCheckboxProps: (record: PubRecordModel) => ({+ name: record.title,+ }),+ selectedRowKeys,+ };return (- <div className={styles.pubRecord}>+ <div+ className={[+ styles.pubRecord,+ onChange && styles['pubRecord-component'],+ ].join(' ')}+ ><ModalzIndex={10000}open={examineVideo.open}@@ -216,8 +242,14 @@ export default function Page() {<Table<PubRecordModel>columns={columns}dataSource={pulRecardList}- scroll={{ y: '78vh' }}+ scroll={{ y: hegiht }}rowKey="id"+ rowSelection={onChange ? { type: 'radio', ...rowSelection } : undefined}+ onRow={(record) => ({+ onClick: () => {+ setSelectedRowKeys([record.id]);+ },+ })}/>{/*发布记录详情*/}@@ -228,7 +260,7 @@ export default function Page() {<ul className="pubRecord-record">{pubRecordList.map((v) => {- const account = accountMap.current.get(v.accountId);+ const account = accountMap.get(v.accountId);const plat = AccountPlatInfoMap.get(v.type);return (<li className="pubRecord-record-item" key={v.id}>@@ -268,9 +300,7 @@ export default function Page() {);restartPub(prl,- prl.map(- (k) => accountMap.current.get(k.accountId)!,- ),+ prl.map((k) => accountMap.get(k.accountId)!),);setRecordLoaidng(false);navigate('/publish/video');diff --git a/src/views/publish/children/pubRecord/pubRecord.module.scss b/src/views/publish/children/pubRecord/pubRecord.module.scssindex 6b6f3419..3dbbc580 100644--- a/src/views/publish/children/pubRecord/pubRecord.module.scss+++ b/src/views/publish/children/pubRecord/pubRecord.module.scss@@ -79,6 +79,14 @@}}+.pubRecord-component {+ :global {+ tr {+ cursor: pointer;+ }+ }+}+.pubRecord-pubCon {display: flex;align-items: center;diff --git a/src/views/publish/children/videoPage/components/NoChoosePage.tsx b/src/views/publish/children/videoPage/components/NoChoosePage.tsxindex edf5b7a9..1ef2241f 100644--- a/src/views/publish/children/videoPage/components/NoChoosePage.tsx+++ b/src/views/publish/children/videoPage/components/NoChoosePage.tsx@@ -1,4 +1,4 @@-import { ForwardedRef, forwardRef, memo } from 'react';+import { ForwardedRef, forwardRef, memo, useRef, useState } from 'react';import VideoChoose from '@/components/Choose/VideoChoose';import SupportPlat from '../../../components/SupportPlat/SupportPlat';import { PubType } from '../../../../../../commont/publish/PublishEnum';@@ -6,7 +6,10 @@ import { useVideoPageStore } from '@/views/publish/children/videoPage/useVideoPaimport { useShallow } from 'zustand/react/shallow';import localUpload from '../images/localUpload.png';import importRecord from '../images/importRecord.png';-import { Button } from 'antd';+import { Alert, Button, message, Modal } from 'antd';+import PubRecord from '../../pubRecord/page';+import { icpGetPubVideoRecord } from '../../../../../icp/publish';+import { useAccountStore } from '../../../../../store/account';export interface INoChoosePageRef {}@@ -15,17 +18,52 @@ export interface INoChoosePageProps {}// 未选择视频时暂时的组件const NoChoosePage = memo(forwardRef(({}: INoChoosePageProps, ref: ForwardedRef<INoChoosePageRef>) => {- const { addVideos, setLoadingPageLoading, setOperateId } =+ const { addVideos, setLoadingPageLoading, setOperateId, restartPub } =useVideoPageStore(useShallow((state) => ({addVideos: state.addVideos,setLoadingPageLoading: state.setLoadingPageLoading,setOperateId: state.setOperateId,+ restartPub: state.restartPub,})),);+ const [importPubRecordOpen, setImportPubRecordOpen] = useState(false);+ const pubRecordIds = useRef<number[]>([]);+ const { accountMap } = useAccountStore(+ useShallow((state) => ({+ accountMap: state.accountMap,+ })),+ );return (<div className="video-pubBefore">+ <Modal+ open={importPubRecordOpen}+ width="90%"+ title="导入发布记录"+ okText="确认导入"+ onCancel={() => setImportPubRecordOpen(false)}+ onOk={async () => {+ if (pubRecordIds.current.length === 0) {+ return message.warning('未选择任何数据');+ }+ const res = await icpGetPubVideoRecord(pubRecordIds.current[0]);+ restartPub(+ res,+ res.map((k) => accountMap.get(k.accountId)!),+ );+ setImportPubRecordOpen(false);+ }}+ >+ <Alert message="选择一条发布记录" />+ <PubRecord+ hegiht="55vh"+ onChange={async (ids) => {+ pubRecordIds.current = ids;+ }}+ />+ </Modal>+<h1>视频发布</h1><p className="video-pubBefore-tip">支持多视频、多平台、多账号同时发布@@ -53,6 +91,7 @@ const NoChoosePage = memo(<divclassName="videoChoose"onClick={() => {+ setImportPubRecordOpen(true);console.log('click');}}>diff --git a/src/views/publish/children/videoPage/useVideoPageStore.ts b/src/views/publish/children/videoPage/useVideoPageStore.tsindex e27d1d2f..5e5c88c6 100644--- a/src/views/publish/children/videoPage/useVideoPageStore.ts+++ b/src/views/publish/children/videoPage/useVideoPageStore.ts@@ -357,32 +357,41 @@ export const useVideoPageStore = create(// 根据发布记录重新发布设置参数async restartPub(pubRecordList: VideoModel[], accounts: AccountInfo[]) {- const videoListChoose: IVideoChooseItem[] = [];- methods.setOperateId();-- for (let i = 0; i < pubRecordList.length; i++) {- const pubRecord = pubRecordList[i];- const account = accounts[i];- const video = await getVideoFile(pubRecord.videoPath!);- const cover = await getImgFile(pubRecord.coverPath!);- const pubParams = {- ...pubRecord,- cover: cover,- describe: pubRecord.desc,- };- pubParams.id = undefined;- pubParams.failMsg = '';+ set({+ loadingPageLoading: true,+ });- videoListChoose.push({- id: generateUUID(),- account,- video,- pubParams,- });+ const videoListChoose: IVideoChooseItem[] = [];+ try {+ methods.setOperateId();++ for (let i = 0; i < pubRecordList.length; i++) {+ const pubRecord = pubRecordList[i];+ const account = accounts[i];+ const video = await getVideoFile(pubRecord.videoPath!);+ const cover = await getImgFile(pubRecord.coverPath!);+ const pubParams = {+ ...pubRecord,+ cover: cover,+ describe: pubRecord.desc,+ };+ pubParams.id = undefined;+ pubParams.failMsg = '';++ videoListChoose.push({+ id: generateUUID(),+ account,+ video,+ pubParams,+ });+ }+ } catch (e) {+ console.warn(e);}set({videoListChoose,+ loadingPageLoading: false,});},@@ -401,20 +410,24 @@ export const useVideoPageStore = create(});methods.setOperateId(operateId);- if (commonPubParams?.cover?.imgPath) {- commonPubParams.cover = await getImgFile(- commonPubParams.cover.imgPath,- );- }- for (const item of videoListChoose) {- if (item.video?.videoPath) {- item.video = await getVideoFile(item.video.videoPath);- }- if (item.pubParams.cover) {- item.pubParams.cover = await getImgFile(- item.pubParams.cover.imgPath,+ try {+ if (commonPubParams?.cover?.imgPath) {+ commonPubParams.cover = await getImgFile(+ commonPubParams.cover.imgPath,);}+ for (const item of videoListChoose) {+ if (item.video?.videoPath) {+ item.video = await getVideoFile(item.video.videoPath);+ }+ if (item.pubParams.cover) {+ item.pubParams.cover = await getImgFile(+ item.pubParams.cover.imgPath,+ );+ }+ }+ } catch (e) {+ console.warn(e);}set({diff --git a/src/views/publish/components/ChooseAccountModule/components/PlatChoose.tsx b/src/views/publish/components/ChooseAccountModule/components/PlatChoose.tsxindex f2cfb029..e77b7946 100644--- a/src/views/publish/components/ChooseAccountModule/components/PlatChoose.tsx+++ b/src/views/publish/components/ChooseAccountModule/components/PlatChoose.tsx@@ -11,7 +11,6 @@ import {import useCssVariables from '@/hooks/useCssVariables';import { AccountType } from '../../../../../../commont/AccountEnum';import { AccountInfo, AccountPlatInfoMap } from '@/views/account/comment';-import { icpGetAccountList } from '@/icp/account';import styles from '@/views/publish/components/ChooseAccountModule/chooseAccountModule.module.scss';import {Avatar,@@ -24,7 +23,8 @@ import {} from 'antd';import { PubType } from '../../../../../../commont/publish/PublishEnum';import { CheckOutlined } from '@ant-design/icons';-import { onAccountLoginFinish } from '@/icp/receiveMsg';+import { useAccountStore } from '../../../../../store/account';+import { useShallow } from 'zustand/react/shallow';export interface IPlatChooseRef {/**@@ -72,6 +72,11 @@ const PlatChoose = memo(>(new Map());// 每次change操作的数据const recentData = useRef<AccountInfo>();+ const { accountList } = useAccountStore(+ useShallow((state) => ({+ accountList: state.accountList,+ })),+ );// 经过 allowPlatSet 过滤后的账户数据const accountMapLast = useMemo(() => {@@ -119,37 +124,27 @@ const PlatChoose = memo([activePlat, choosedAcountMap],);- const getAccountList = () => {- icpGetAccountList().then((res) => {- if (!res) return;- setAccountMap((prevMap) => {- const newMap = new Map(prevMap);- Array.from(AccountPlatInfoMap).map(([key, value]) => {- if (value.pubTypes.has(pubType)) {- newMap.set(key, []);- }- });- // 添加渲染账户数据值- res.map((v) => {- newMap.get(v.type)?.push(v);- });- return newMap;+ useEffect(() => {+ setAccountMap((prevMap) => {+ const newMap = new Map(prevMap);+ Array.from(AccountPlatInfoMap).map(([key, value]) => {+ if (value.pubTypes.has(pubType)) {+ newMap.set(key, []);+ }+ });+ // 添加渲染账户数据值+ accountList.map((v) => {+ newMap.get(v.type)?.push(v);});+ return newMap;});- };+ }, [accountList]);useEffect(() => {- getAccountList();-- const revmoeListener = onAccountLoginFinish(() => {- getAccountList();- });-return () => {setAccountMap(new Map());setChoosedAcountMap(new Map());init();- revmoeListener();};}, []);