wangzhibo
2025-07-30 25087cbe79c8c4992551477d55d9db8bbea2202e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
from flask import Flask, render_template_string, request, jsonify,redirect, url_for,abort
import os
from auto_media_publisher.scheduler.task_scheduler_thread import auto_media_publisherTaskSchedulerThread
from pathlib import Path
import json
from auto_media_publisher.config.conf_base import TASK_CONFIG_DIR
 
 
try:
    globle_schduler = auto_media_publisherTaskSchedulerThread()
    globle_schduler.daemon = True
    globle_schduler.start()
except Exception as e:
    print("[ERROR] 启动调度器失败:", e)
 
app = Flask(__name__)
 
@app.route("/")
def home():
    return redirect("/tasks")
 
@app.route("/tasks")
def tasks():
    infos = globle_schduler.get_task_info()
    return render_template_string("""
    <h2>任务状态</h2>
    <ul>
    {% for tid, info in infos.items() %}
        <li><b>{{ tid }}</b> | 上次运行:{{ info.last_run }}<br/>
        <pre>{{ info.last_log }}</pre></li>
    {% endfor %}
    </ul>
    """, infos=infos)
 
@app.route("/users")
def list_users():
    users = [p.name for p in Path(TASK_CONFIG_DIR).rglob("*.json")]
    return render_template_string("""
    <h2>用户列表</h2>
     <form method="POST" action="/user/new" style="margin-top:20px;">
        <label>用户ID(英文标识):</label>
        <input name="user_id" required>
        <label>用户名(中文):</label>
        <input name="username" required>
        <button type="submit">➕ 新建用户配置</button>
    </form>
    <ul>
    {% for u in users %}
        <li><a href="/user/{{ u }}">{{ u }}</a></li>
    {% endfor %}
    </ul>
    """, users=users)
 
@app.route("/user/<uid>", methods=["GET", "POST"])
def edit_user(uid):
    path = Path(TASK_CONFIG_DIR) / uid
    if not path.exists():
        abort(404)
    if request.method == "POST":
        raw_text = request.form["content"]
        cleaned_lines = [line.rstrip() for line in raw_text.splitlines() if line.strip()]
        cleaned_text = "\n".join(cleaned_lines) + "\n"
        path.write_text(cleaned_text, encoding="utf-8")
        return redirect(url_for("list_users"))
    else:
        content = ""
        if path.exists():
            content = path.read_text(encoding="utf-8")
        return render_template_string("""
        <h2>编辑用户配置:{{ uid }}</h2>
        <form method="POST">
            <textarea name="content" style="width:90%;height:300px">{{ content }}</textarea><br/>
            <button type="submit">保存</button>
        </form>
        """, uid=uid, content=content)
    
 
@app.route('/upload_auth', methods=['POST'])
def upload_cookie():
    username = request.form.get('username')
    if not username:
        return jsonify({'success': False, 'error': 'Missing username'})
    
    file = request.files.get('file')
    if file.filename == '':
        return jsonify({'success': False, 'error': 'No selected file'})
 
    if file and file.filename.endswith('.json'):
        try:
            save_path = os.path.join('./data/cookies', username,file.filename)
            os.makedirs(os.path.dirname(save_path), exist_ok=True)
            file.save(save_path)
            print(f"✅ 保存成功: {save_path}")
            return jsonify({'success': True})
        except Exception as e:
            print(f"❌ 保存失败: {e}")
            return jsonify({'success': False, 'error': str(e)})
 
    return jsonify({'success': False, 'error': 'Invalid file type'})
 
@app.route("/user/new", methods=["POST"])
def new_user():
    user_id = request.form.get("user_id", "").strip()
    username = request.form.get("username", "").strip()
 
    if not user_id or not username:
        return "用户ID 和 用户名 都不能为空", 400
 
    json_path = Path(TASK_CONFIG_DIR) / f"{user_id}.json"
    if json_path.exists():
        return f"配置文件 {user_id}.json 已存在", 400
 
    default_config = {
        "id": 1,
        "user": "13381602515",
        "username": "施教练",
        "city": "上海",
        "proxy": "http://127.0.0.1:8080",
        "enabled": 1,
        "tags": [
            "太极鸟",
            "机构用户"
        ],
        "datetime_created": "2025-07-14T09:00:00",
        "datetime_update": "2025-07-14T09:00:00",
        "platforms": [
            {
                "name": "douyin",
                "enabled": True,
                "task_type": "video_upload",
                "upload_times": [
                    "08:00",
                    "16:00"
                ]
            },
            {
                "name": "xiaohongshu",
                "enabled": False,
                "task_type": "video_upload",
                "upload_times": []
            }
        ]
    }
 
    json_path.write_text(json.dumps(default_config, indent=2, ensure_ascii=False), encoding="utf-8")
 
    return redirect(url_for("edit_user", uid=f"{user_id}.json"))
 
 
# 注册退出处理
#import atexit
#atexit.register(lambda: globle_schduler.shutdown(wait=False))
 
if __name__ == "__main__":
    app.run(port=5000, debug=True)   # 本地访问
    #app.run(host='0.0.0.0', port=5000,debug=True)   # 允许外网访问