base.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. # -*- coding: utf-8 -*-
  2. """
  3. 平台发布基类
  4. 提供通用的发布接口和工具方法
  5. """
  6. import asyncio
  7. import json
  8. import os
  9. from abc import ABC, abstractmethod
  10. from dataclasses import dataclass, field
  11. from datetime import datetime
  12. from typing import List, Optional, Callable
  13. from playwright.async_api import async_playwright, Browser, BrowserContext, Page
  14. @dataclass
  15. class PublishParams:
  16. """发布参数"""
  17. title: str
  18. video_path: str
  19. description: str = ""
  20. cover_path: Optional[str] = None
  21. tags: List[str] = field(default_factory=list)
  22. publish_date: Optional[datetime] = None
  23. location: str = "重庆市"
  24. def __post_init__(self):
  25. if not self.description:
  26. self.description = self.title
  27. @dataclass
  28. class PublishResult:
  29. """发布结果"""
  30. success: bool
  31. platform: str
  32. video_id: str = ""
  33. video_url: str = ""
  34. message: str = ""
  35. error: str = ""
  36. class BasePublisher(ABC):
  37. """
  38. 平台发布基类
  39. 所有平台发布器都需要继承此类
  40. """
  41. platform_name: str = "base"
  42. login_url: str = ""
  43. publish_url: str = ""
  44. cookie_domain: str = ""
  45. def __init__(self, headless: bool = True):
  46. self.headless = headless
  47. self.browser: Optional[Browser] = None
  48. self.context: Optional[BrowserContext] = None
  49. self.page: Optional[Page] = None
  50. self.on_progress: Optional[Callable[[int, str], None]] = None
  51. def set_progress_callback(self, callback: Callable[[int, str], None]):
  52. """设置进度回调"""
  53. self.on_progress = callback
  54. def report_progress(self, progress: int, message: str):
  55. """报告进度"""
  56. print(f"[{self.platform_name}] [{progress}%] {message}")
  57. if self.on_progress:
  58. self.on_progress(progress, message)
  59. @staticmethod
  60. def parse_cookies(cookies_str: str) -> list:
  61. """解析 cookie 字符串为列表"""
  62. try:
  63. cookies = json.loads(cookies_str)
  64. if isinstance(cookies, list):
  65. return cookies
  66. except json.JSONDecodeError:
  67. pass
  68. # 字符串格式: name=value; name2=value2
  69. cookies = []
  70. for item in cookies_str.split(';'):
  71. item = item.strip()
  72. if '=' in item:
  73. name, value = item.split('=', 1)
  74. cookies.append({
  75. 'name': name.strip(),
  76. 'value': value.strip(),
  77. 'domain': '',
  78. 'path': '/'
  79. })
  80. return cookies
  81. @staticmethod
  82. def cookies_to_string(cookies: list) -> str:
  83. """将 cookie 列表转换为字符串"""
  84. return '; '.join([f"{c['name']}={c['value']}" for c in cookies])
  85. async def init_browser(self, storage_state: str = None):
  86. """初始化浏览器"""
  87. playwright = await async_playwright().start()
  88. self.browser = await playwright.chromium.launch(headless=self.headless)
  89. if storage_state and os.path.exists(storage_state):
  90. self.context = await self.browser.new_context(storage_state=storage_state)
  91. else:
  92. self.context = await self.browser.new_context()
  93. self.page = await self.context.new_page()
  94. return self.page
  95. async def set_cookies(self, cookies: list):
  96. """设置 cookies"""
  97. if not self.context:
  98. raise Exception("Browser context not initialized")
  99. # 设置默认域名
  100. for cookie in cookies:
  101. if 'domain' not in cookie or not cookie['domain']:
  102. cookie['domain'] = self.cookie_domain
  103. await self.context.add_cookies(cookies)
  104. async def close_browser(self):
  105. """关闭浏览器"""
  106. if self.context:
  107. await self.context.close()
  108. if self.browser:
  109. await self.browser.close()
  110. async def save_cookies(self, file_path: str):
  111. """保存 cookies 到文件"""
  112. if self.context:
  113. await self.context.storage_state(path=file_path)
  114. async def wait_for_upload_complete(self, success_selector: str, timeout: int = 300):
  115. """等待上传完成"""
  116. if not self.page:
  117. raise Exception("Page not initialized")
  118. for _ in range(timeout // 3):
  119. try:
  120. count = await self.page.locator(success_selector).count()
  121. if count > 0:
  122. return True
  123. except:
  124. pass
  125. await asyncio.sleep(3)
  126. self.report_progress(30, "正在上传视频...")
  127. return False
  128. @abstractmethod
  129. async def publish(self, cookies: str, params: PublishParams) -> PublishResult:
  130. """
  131. 发布视频 - 子类必须实现
  132. Args:
  133. cookies: cookie 字符串或 JSON
  134. params: 发布参数
  135. Returns:
  136. PublishResult: 发布结果
  137. """
  138. pass
  139. async def run(self, cookies: str, params: PublishParams) -> PublishResult:
  140. """
  141. 运行发布任务
  142. 包装了 publish 方法,添加了异常处理和资源清理
  143. """
  144. try:
  145. return await self.publish(cookies, params)
  146. except Exception as e:
  147. import traceback
  148. traceback.print_exc()
  149. return PublishResult(
  150. success=False,
  151. platform=self.platform_name,
  152. error=str(e)
  153. )
  154. finally:
  155. await self.close_browser()