diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..fd1a1aa --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,101 @@ +## Project Overview + +This project, `social-auto-upload`, is a powerful automation tool designed to help content creators and operators efficiently publish video content to multiple domestic and international mainstream social media platforms in one click. The project implements video upload, scheduled release and other functions for platforms such as `Douyin`, `Bilibili`, `Xiaohongshu`, `Kuaishou`, `WeChat Channel`, `Baijiahao` and `TikTok`. + +The project consists of a Python backend and a Vue.js frontend. + +**Backend:** + +* Framework: Flask +* Core Functionality: + * Handles file uploads and management. + * Interacts with a SQLite database to store information about files and user accounts. + * Uses `playwright` for browser automation to interact with social media platforms. + * Provides a RESTful API for the frontend to consume. + * Uses Server-Sent Events (SSE) for real-time communication with the frontend during the login process. + +**Frontend:** + +* Framework: Vue.js +* Build Tool: Vite +* UI Library: Element Plus +* State Management: Pinia +* Routing: Vue Router +* Core Functionality: + * Provides a web interface for managing social media accounts, video files, and publishing videos. + * Communicates with the backend via a RESTful API. + +**Command-line Interface:** + +The project also provides a command-line interface (CLI) for users who prefer to work from the terminal. The CLI supports two main actions: + +* `login`: To log in to a social media platform. +* `upload`: To upload a video to a social media platform, with an option to schedule the upload. + +## Building and Running + +### Backend + +1. **Install dependencies:** + ```bash + pip install -r requirements.txt + ``` + +2. **Install Playwright browser drivers:** + ```bash + playwright install chromium + ``` + +3. **Initialize the database:** + ```bash + python db/createTable.py + ``` + +4. **Run the backend server:** + ```bash + python sau_backend.py + ``` + The backend server will start on `http://localhost:5409`. + +### Frontend + +1. **Navigate to the frontend directory:** + ```bash + cd sau_frontend + ``` + +2. **Install dependencies:** + ```bash + npm install + ``` + +3. **Run the development server:** + ```bash + npm run dev + ``` + The frontend development server will start on `http://localhost:5173`. + +### Command-line Interface + +To use the CLI, you can run the `cli_main.py` script with the appropriate arguments. + +**Login:** + +```bash +python cli_main.py login +``` + +**Upload:** + +```bash +python cli_main.py upload [-pt {0,1}] [-t YYYY-MM-DD HH:MM] +``` + +## Development Conventions + +* The backend code is located in the root directory and the `myUtils` and `uploader` directories. +* The frontend code is located in the `sau_frontend` directory. +* The project uses a SQLite database for data storage. The database file is located at `db/database.db`. +* The `conf.example.py` file should be copied to `conf.py` and configured with the appropriate settings. +* The `requirements.txt` file lists the Python dependencies. +* The `package.json` file in the `sau_frontend` directory lists the frontend dependencies. diff --git a/myUtils/postVideo.py b/myUtils/postVideo.py index e33f3d0..bd94e0b 100644 --- a/myUtils/postVideo.py +++ b/myUtils/postVideo.py @@ -10,7 +10,7 @@ from utils.constant import TencentZoneTypes from utils.files_times import generate_schedule_time_next_day -def post_video_tencent(title,files,tags,account_file,category=TencentZoneTypes.LIFESTYLE.value,enableTimer=False,videos_per_day = 1, daily_times=None,start_days = 0): +def post_video_tencent(title,files,tags,account_file,category=TencentZoneTypes.LIFESTYLE.value,enableTimer=False,videos_per_day = 1, daily_times=None,start_days = 0, is_draft=False): # 生成文件的完整路径 account_file = [Path(BASE_DIR / "cookiesFile" / file) for file in account_file] files = [Path(BASE_DIR / "videoFile" / file) for file in files] @@ -25,7 +25,7 @@ def post_video_tencent(title,files,tags,account_file,category=TencentZoneTypes.L print(f"视频文件名:{file}") print(f"标题:{title}") print(f"Hashtag:{tags}") - app = TencentVideo(title, str(file), tags, publish_datetimes[index], cookie, category) + app = TencentVideo(title, str(file), tags, publish_datetimes[index], cookie, category, is_draft) asyncio.run(app.main(), debug=False) diff --git a/sau_backend.py b/sau_backend.py index 83631d6..4b86f7e 100644 --- a/sau_backend.py +++ b/sau_backend.py @@ -139,9 +139,10 @@ def upload_save(): }), 200 except Exception as e: + print(f"Upload failed: {e}") return jsonify({ "code": 500, - "msg": str("upload failed!"), + "msg": f"upload failed: {e}", "data": None }), 500 @@ -157,14 +158,26 @@ def get_all_files(): cursor.execute("SELECT * FROM file_records") rows = cursor.fetchall() - # 将结果转为字典列表 - data = [dict(row) for row in rows] + # 将结果转为字典列表,并提取UUID + data = [] + for row in rows: + row_dict = dict(row) + # 从 file_path 中提取 UUID (文件名的第一部分,下划线前) + if row_dict.get('file_path'): + file_path_parts = row_dict['file_path'].split('_', 1) # 只分割第一个下划线 + if len(file_path_parts) > 0: + row_dict['uuid'] = file_path_parts[0] # UUID 部分 + else: + row_dict['uuid'] = '' + else: + row_dict['uuid'] = '' + data.append(row_dict) - return jsonify({ - "code": 200, - "msg": "success", - "data": data - }), 200 + return jsonify({ + "code": 200, + "msg": "success", + "data": data + }), 200 except Exception as e: return jsonify({ "code": 500, @@ -173,6 +186,37 @@ def get_all_files(): }), 500 +@app.route("/getAccounts", methods=['GET']) +def getAccounts(): + """快速获取所有账号信息,不进行cookie验证""" + try: + with sqlite3.connect(Path(BASE_DIR / "db" / "database.db")) as conn: + conn.row_factory = sqlite3.Row + cursor = conn.cursor() + cursor.execute(''' + SELECT * FROM user_info''') + rows = cursor.fetchall() + rows_list = [list(row) for row in rows] + + print("\n📋 当前数据表内容(快速获取):") + for row in rows: + print(row) + + return jsonify( + { + "code": 200, + "msg": None, + "data": rows_list + }), 200 + except Exception as e: + print(f"获取账号列表时出错: {str(e)}") + return jsonify({ + "code": 500, + "msg": f"获取账号列表失败: {str(e)}", + "data": None + }), 500 + + @app.route("/getValidAccounts",methods=['GET']) async def getValidAccounts(): with sqlite3.connect(Path(BASE_DIR / "db" / "database.db")) as conn: @@ -234,6 +278,18 @@ def delete_file(): record = dict(record) + # 获取文件路径并删除实际文件 + file_path = Path(BASE_DIR / "videoFile" / record['file_path']) + if file_path.exists(): + try: + file_path.unlink() # 删除文件 + print(f"✅ 实际文件已删除: {file_path}") + except Exception as e: + print(f"⚠️ 删除实际文件失败: {e}") + # 即使删除文件失败,也要继续删除数据库记录,避免数据不一致 + else: + print(f"⚠️ 实际文件不存在: {file_path}") + # 删除数据库记录 cursor.execute("DELETE FROM file_records WHERE id = ?", (file_id,)) conn.commit() @@ -338,6 +394,7 @@ def postVideo(): productLink = data.get('productLink', '') productTitle = data.get('productTitle', '') thumbnail_path = data.get('thumbnail', '') + is_draft = data.get('isDraft', False) # 新增参数:是否保存为草稿 videos_per_day = data.get('videosPerDay') daily_times = data.get('dailyTimes') @@ -351,7 +408,7 @@ def postVideo(): start_days) case 2: post_video_tencent(title, file_list, tags, account_list, category, enableTimer, videos_per_day, daily_times, - start_days) + start_days, is_draft) case 3: post_video_DouYin(title, file_list, tags, account_list, category, enableTimer, videos_per_day, daily_times, start_days, thumbnail_path, productLink, productTitle) @@ -450,6 +507,127 @@ def postVideoBatch(): "data": None }), 200 +# Cookie文件上传API +@app.route('/uploadCookie', methods=['POST']) +def upload_cookie(): + try: + if 'file' not in request.files: + return jsonify({ + "code": 500, + "msg": "没有找到Cookie文件", + "data": None + }), 400 + + file = request.files['file'] + if file.filename == '': + return jsonify({ + "code": 500, + "msg": "Cookie文件名不能为空", + "data": None + }), 400 + + if not file.filename.endswith('.json'): + return jsonify({ + "code": 500, + "msg": "Cookie文件必须是JSON格式", + "data": None + }), 400 + + # 获取账号信息 + account_id = request.form.get('id') + platform = request.form.get('platform') + + if not account_id or not platform: + return jsonify({ + "code": 500, + "msg": "缺少账号ID或平台信息", + "data": None + }), 400 + + # 从数据库获取账号的文件路径 + with sqlite3.connect(Path(BASE_DIR / "db" / "database.db")) as conn: + conn.row_factory = sqlite3.Row + cursor = conn.cursor() + cursor.execute('SELECT filePath FROM user_info WHERE id = ?', (account_id,)) + result = cursor.fetchone() + + if not result: + return jsonify({ + "code": 500, + "msg": "账号不存在", + "data": None + }), 404 + + # 保存上传的Cookie文件到对应路径 + cookie_file_path = Path(BASE_DIR / "cookiesFile" / result['filePath']) + cookie_file_path.parent.mkdir(parents=True, exist_ok=True) + + file.save(str(cookie_file_path)) + + # 更新数据库中的账号信息(可选,比如更新更新时间) + # 这里可以根据需要添加额外的处理逻辑 + + return jsonify({ + "code": 200, + "msg": "Cookie文件上传成功", + "data": None + }), 200 + + except Exception as e: + print(f"上传Cookie文件时出错: {str(e)}") + return jsonify({ + "code": 500, + "msg": f"上传Cookie文件失败: {str(e)}", + "data": None + }), 500 + + +# Cookie文件下载API +@app.route('/downloadCookie', methods=['GET']) +def download_cookie(): + try: + file_path = request.args.get('filePath') + if not file_path: + return jsonify({ + "code": 500, + "msg": "缺少文件路径参数", + "data": None + }), 400 + + # 验证文件路径的安全性,防止路径遍历攻击 + cookie_file_path = Path(BASE_DIR / "cookiesFile" / file_path).resolve() + base_path = Path(BASE_DIR / "cookiesFile").resolve() + + if not cookie_file_path.is_relative_to(base_path): + return jsonify({ + "code": 500, + "msg": "非法文件路径", + "data": None + }), 400 + + if not cookie_file_path.exists(): + return jsonify({ + "code": 500, + "msg": "Cookie文件不存在", + "data": None + }), 404 + + # 返回文件 + return send_from_directory( + directory=str(cookie_file_path.parent), + path=cookie_file_path.name, + as_attachment=True + ) + + except Exception as e: + print(f"下载Cookie文件时出错: {str(e)}") + return jsonify({ + "code": 500, + "msg": f"下载Cookie文件失败: {str(e)}", + "data": None + }), 500 + + # 包装函数:在线程中运行异步函数 def run_async_function(type,id,status_queue): match type: diff --git a/sau_frontend/.env.development b/sau_frontend/.env.development index beb93b5..cb033bc 100644 --- a/sau_frontend/.env.development +++ b/sau_frontend/.env.development @@ -2,7 +2,7 @@ NODE_ENV=development # API 基础地址 -VITE_API_BASE_URL=http://localhost:5409 +VITE_API_BASE_URL=/api # 应用端口 VITE_PORT=5173 diff --git a/sau_frontend/src/api/account.js b/sau_frontend/src/api/account.js index 1001d60..309d3af 100644 --- a/sau_frontend/src/api/account.js +++ b/sau_frontend/src/api/account.js @@ -2,21 +2,26 @@ import { http } from '@/utils/request' // 账号管理相关API export const accountApi = { - // 获取有效账号列表 + // 获取有效账号列表(带验证) getValidAccounts() { return http.get('/getValidAccounts') }, - + + // 获取账号列表(不带验证,快速加载) + getAccounts() { + return http.get('/getAccounts') + }, + // 添加账号 addAccount(data) { return http.post('/account', data) }, - + // 更新账号 updateAccount(data) { return http.post('/updateUserinfo', data) }, - + // 删除账号 deleteAccount(id) { return http.get(`/deleteAccount?id=${id}`) diff --git a/sau_frontend/src/api/material.js b/sau_frontend/src/api/material.js index 04b9c23..898cae1 100644 --- a/sau_frontend/src/api/material.js +++ b/sau_frontend/src/api/material.js @@ -8,9 +8,9 @@ export const materialApi = { }, // 上传素材 - uploadMaterial: (formData) => { + uploadMaterial: (formData, onUploadProgress) => { // 使用http.upload方法,它已经配置了正确的Content-Type - return http.upload('/uploadSave', formData) + return http.upload('/uploadSave', formData, onUploadProgress) }, // 删除素材 diff --git a/sau_frontend/src/utils/request.js b/sau_frontend/src/utils/request.js index 14654ff..73a25e6 100644 --- a/sau_frontend/src/utils/request.js +++ b/sau_frontend/src/utils/request.js @@ -87,11 +87,12 @@ export const http = { return request.delete(url, { params }) }, - upload(url, formData) { + upload(url, formData, onUploadProgress) { return request.post(url, formData, { headers: { 'Content-Type': 'multipart/form-data' - } + }, + onUploadProgress }) } } diff --git a/sau_frontend/src/views/AccountManagement.vue b/sau_frontend/src/views/AccountManagement.vue index a5938b8..dad1efc 100644 --- a/sau_frontend/src/views/AccountManagement.vue +++ b/sau_frontend/src/views/AccountManagement.vue @@ -30,7 +30,7 @@ @@ -47,9 +47,14 @@ @@ -57,6 +62,8 @@ @@ -93,7 +100,7 @@ @@ -110,9 +117,14 @@ @@ -120,6 +132,8 @@ @@ -156,7 +170,7 @@ @@ -173,9 +187,14 @@ @@ -183,6 +202,8 @@ @@ -219,7 +240,7 @@ @@ -236,9 +257,14 @@ @@ -246,6 +272,8 @@ @@ -282,7 +310,7 @@ @@ -299,9 +327,14 @@ @@ -309,6 +342,8 @@ @@ -393,7 +428,7 @@