返回 Social Auto Upload
schedule.py
根目录 / uploader / zhihu_uploader / schedule.py
1 """知乎文章和视频的北京时间定时设置。"""
2 from datetime import datetime, timedelta
3 import re
4
5 from patchright.async_api import Page, expect
6
7 from uploader.zhihu_uploader.constants import (
8 ZHIHU_SCHEDULE_MAX_HOURS, ZHIHU_SCHEDULE_MINUTES, ZHIHU_TIMEZONE,
9 )
10
11
12 def validate_zhihu_schedule(value: datetime | None, now: datetime | None = None) -> datetime | None:
13 """按页面实际支持的范围校验时间;无时区 CLI 输入按北京时间解释。"""
14 if value is None:
15 return None
16 if not isinstance(value, datetime):
17 raise ValueError("知乎定时时间必须为 datetime;CLI 使用 --schedule YYYY-MM-DD HH:MM")
18 target = value.replace(tzinfo=ZHIHU_TIMEZONE) if value.tzinfo is None else value.astimezone(ZHIHU_TIMEZONE)
19 current = now or datetime.now(ZHIHU_TIMEZONE)
20 if current.tzinfo is None:
21 raise ValueError("知乎定时校验时钟必须包含时区")
22 if target.second or target.microsecond:
23 raise ValueError("知乎定时精确到分钟,不接受秒或微秒")
24 if not current + timedelta(minutes=ZHIHU_SCHEDULE_MINUTES) <= target <= current + timedelta(hours=ZHIHU_SCHEDULE_MAX_HOURS):
25 raise ValueError("知乎定时需在北京时间当前时刻 30 分钟后至 48 小时内")
26 return target
27
28
29 async def fill_zhihu_article_schedule(page: Page, value: datetime | None) -> None:
30 """通过文章发布面板的日期、小时、分钟选择器填写并读回排期。"""
31 target = validate_zhihu_schedule(value)
32 if target is None:
33 return
34
35 # 文章表单将“定时发布”作为单独开关;点击后弹出已观察到的计划时间面板。
36 await page.get_by_text("定时发布", exact=True).click()
37 panel_label = page.get_by_text("开启定时发布", exact=True)
38 await expect(panel_label).to_be_visible()
39 picker = page.locator(".DateTimePicker")
40 await expect(picker).to_have_count(1)
41 date_button = page.locator(".DatePicker-Button")
42 await expect(date_button).to_have_count(1)
43 shown_date = await date_button.inner_text()
44 if shown_date != target.strftime("%Y-%m-%d"):
45 await date_button.click()
46 calendar = page.locator(".Calendar")
47 await expect(calendar).to_be_visible()
48 shown_month = (await calendar.locator(".Calendar-topToolDate").inner_text()).strip()
49 wanted_month = f"{target.year} 年 {target.month} 月"
50 if shown_month != wanted_month:
51 # 48 小时范围最多只跨到相邻月份;按钮职责 class 来自页面日历实际 DOM。
52 await calendar.locator(".Calendar-topToolButton--nextMonth").click()
53 await expect(calendar.locator(".Calendar-topToolDate")).to_have_text(wanted_month)
54 day = calendar.locator("td.Calendar-day:not(.is-disabled):not(.is-not-this-month)").filter(
55 has_text=re.compile(rf"^{target.day}$"),
56 )
57 await expect(day).to_have_count(1)
58 await day.click()
59 await expect(date_button).to_have_text(target.strftime("%Y-%m-%d"))
60
61 # 页面将小时与分钟分成两个同构下拉;DOM 顺序已由实际弹层验证。
62 time_selects = picker.locator(".Select-button")
63 await expect(time_selects).to_have_count(2)
64 await time_selects.nth(0).click()
65 hour = page.get_by_role("option", name=f"{target.hour:02d}", exact=True)
66 await expect(hour).to_have_count(1)
67 if not await hour.is_enabled():
68 raise RuntimeError("知乎定时小时选项当前不可选,请检查时间范围")
69 await hour.click()
70 await time_selects.nth(1).click()
71 minute = page.get_by_role("option", name=f"{target.minute:02d}", exact=True)
72 await expect(minute).to_have_count(1)
73 if not await minute.is_enabled():
74 raise RuntimeError("知乎定时分钟选项当前不可选,请检查时间范围")
75 await minute.click()
76 await expect(time_selects.nth(0)).to_have_text(f"{target.hour:02d}")
77 await expect(time_selects.nth(1)).to_have_text(f"{target.minute:02d}")
78 confirm = page.get_by_role("button", name="确认", exact=True)
79 await expect(confirm).to_be_enabled()
80 await confirm.click()
81 await expect(panel_label).to_have_count(0)
82
83
84 async def fill_zhihu_video_schedule(page: Page, value: datetime | None) -> None:
85 """通过视频表单自己的定时区启用并读回日期与时间。"""
86 target = validate_zhihu_schedule(value)
87 if target is None:
88 return
89 schedule = page.locator(".VideoUploadForm-scheduledPublish")
90 await expect(schedule).to_have_count(1)
91 # 视频页脚本将该组件挂在 VideoUploadForm-scheduledPublish 行内。
92 toggle = schedule.locator('input[type="checkbox"]')
93 await expect(toggle).to_have_count(1)
94 if not await toggle.is_checked():
95 await toggle.check()
96 picker = schedule.locator(".DateTimePicker")
97 await expect(picker).to_be_visible()
98 date_button = picker.locator(".DatePicker-Button")
99 await expect(date_button).to_have_count(1)
100 shown_date = await date_button.inner_text()
101 if shown_date != target.strftime("%Y-%m-%d"):
102 await date_button.click()
103 calendar = page.locator(".Calendar")
104 await expect(calendar).to_be_visible()
105 shown_month = (await calendar.locator(".Calendar-topToolDate").inner_text()).strip()
106 wanted_month = f"{target.year} 年 {target.month} 月"
107 if shown_month != wanted_month:
108 await calendar.locator(".Calendar-topToolButton--nextMonth").click()
109 await expect(calendar.locator(".Calendar-topToolDate")).to_have_text(wanted_month)
110 day = calendar.locator("td.Calendar-day:not(.is-disabled):not(.is-not-this-month)").filter(
111 has_text=re.compile(rf"^{target.day}$"),
112 )
113 await expect(day).to_have_count(1)
114 await day.click()
115 await expect(date_button).to_have_text(target.strftime("%Y-%m-%d"))
116 time_selects = picker.locator(".Select-button")
117 await expect(time_selects).to_have_count(2)
118 await time_selects.nth(0).click()
119 hour = page.get_by_role("option", name=f"{target.hour:02d}", exact=True)
120 await expect(hour).to_have_count(1)
121 if not await hour.is_enabled():
122 raise RuntimeError("知乎定时小时选项当前不可选,请检查时间范围")
123 await hour.click()
124 await time_selects.nth(1).click()
125 minute = page.get_by_role("option", name=f"{target.minute:02d}", exact=True)
126 await expect(minute).to_have_count(1)
127 if not await minute.is_enabled():
128 raise RuntimeError("知乎定时分钟选项当前不可选,请检查时间范围")
129 await minute.click()
130 await expect(time_selects.nth(0)).to_have_text(f"{target.hour:02d}")
131 await expect(time_selects.nth(1)).to_have_text(f"{target.minute:02d}")
132
132 lines PYTHON