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 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
| import xmlrpc.client import ssl import os import json import sys import re import requests import subprocess import shlex import time
if sys.platform.startswith('win'): sys.stdout.reconfigure(encoding='utf-8')
ssl._create_default_https_context = ssl._create_unverified_context
rootPath = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(rootPath,"config.json"),"rb") as f: config = json.loads(f.read())
ALL_IMAGE_PATTERN = re.compile(r'!\[(.*?)\]\((.*?)\)')
POST_DELAY_SECONDS = 3.5
def getExistingPostId(title): """ 通过检查最新文章列表,查找给定标题的文章 ID。 注意:MetaWeblog API 只能获取最近的 N 篇文章 (例如 20 篇)。 如果文章非常旧,可能无法找到。N 的值通常由博客平台决定。 """ print(f"🔄 尝试在最近的文章中查找标题为 '{title}' 的文章...") url = config["url"] username = config['username'] password = config['password'] NUMBER_OF_POSTS_TO_CHECK = 50
proxy = xmlrpc.client.ServerProxy(url) try: recent_posts = proxy.metaWeblog.getRecentPosts( '', username, password, NUMBER_OF_POSTS_TO_CHECK ) for post in recent_posts: if post['title'] == title: print(f"✅ 找到已存在的文章!Post ID: {post['postid']}") return post['postid'] print("➡️ 未找到同名文章,将创建新文章。") return None except Exception as e: print(f"❌ 查找现有文章时出错: {e}") return None
def uploadArticle(articles): for article in articles: with open(article,"r",encoding="utf8") as f: original_data = f.read() data_to_post = original_data md_dir = os.path.dirname(article) matches = list(ALL_IMAGE_PATTERN.finditer(data_to_post)) uploaded_map = {} for match in matches: alt_text = match.group(1) source_path = match.group(2) original_full_match = match.group(0) if source_path in uploaded_map: new_url = uploaded_map[source_path] print(f"➡️ 图片已处理: {source_path},使用缓存URL: {new_url}") else: if source_path.startswith('http'): upload_target = source_path else: upload_target = os.path.normpath(os.path.join(md_dir, source_path)) new_url = uploadImage(upload_target) if new_url: uploaded_map[source_path] = new_url else: print(f"⚠️ 图片 {source_path} 上传失败,将保留原地址。") continue new_image_reference = f"" data_to_post = data_to_post.replace(original_full_match, new_image_reference, 1) title = os.path.basename(article)[:-3]
post_id = getExistingPostId(title) post = dict( description = data_to_post, title = title, categories = ['[Markdown]'], ) proxy = xmlrpc.client.ServerProxy(config["url"]) userName = config["url"].split("/")[-1] if post_id: try: success = proxy.metaWeblog.editPost( post_id, config['username'], config['password'], post, True ) if success: print(f"🎉 文章更新成功 (Post ID: {post_id})") else: raise Exception("API 返回 False") article_url = f"https://www.cnblogs.com/{userName}/p/{post_id}.html"
except Exception as e: print(f"❌ 文章更新失败 (editPost): {e}") continue else: try: post['dateCreated'] = xmlrpc.client.DateTime() new_post_id = proxy.metaWeblog.newPost( '', config['username'], config['password'], post, True ) print(f"🎉 文章创建成功!新 Post ID: {new_post_id}") article_url = f"https://www.cnblogs.com/{userName}/p/{new_post_id}.html"
except Exception as e: print(f"❌ 文章创建失败 (newPost): {e}") print(f"⚠️ 遇到频率限制,暂停 {POST_DELAY_SECONDS * 2} 秒...") time.sleep(POST_DELAY_SECONDS * 2) continue
print(f"✅ 文章发布/更新成功: {article_url}") print(f"⏸️ 暂停 {POST_DELAY_SECONDS} 秒,以避免频率限制...") time.sleep(POST_DELAY_SECONDS)
def to_bash_path(win_path): """ 将 Windows 绝对路径转换为 Git Bash/MinGW 路径。 例如: C:/Users/name/ -> /c/Users/name/ """ if not win_path: return win_path normalized_path = win_path.replace('\\', '/') if re.match(r'^[A-Za-z]:/', normalized_path): drive = normalized_path[0].lower() rest_of_path = normalized_path[2:] return f'/{drive}{rest_of_path}' return normalized_path
def deployHexo(): """ 执行 Hexo 部署命令 (hexo clean, hexo g, hexo d),使用 Bash -c 选项进行安全封装。 """ hexo_root_path_win = config.get("hexo_root_path") bash_executable_path = config.get("bash_path") HEXO_EXE_PATH = config.get("hexo_path")
hexo_root_path_bash = to_bash_path(hexo_root_path_win)
commands_to_run = " && ".join([ f"{HEXO_EXE_PATH} clean", f"{HEXO_EXE_PATH} generate", f"{HEXO_EXE_PATH} deploy" ]) internal_command = f'cd {shlex.quote(hexo_root_path_bash)} && {commands_to_run}' quoted_bash_path = shlex.quote(bash_executable_path) cmd_list = [ quoted_bash_path.strip("'\""), "-c", internal_command ]
print("\n--- 🚀 开始执行 Hexo 部署流程 (使用 Bash 列表模式) ---") print(f"Bash Command List: {cmd_list}") try: result = subprocess.run( cmd_list, check=True, capture_output=True, text=True, encoding='utf-8' ) print("✅ Hexo 部署命令全部成功完成。")
except subprocess.CalledProcessError as e: print(f"❌ Bash 命令执行失败,请检查 Hexo 错误。") print(f"Stdout:\n{e.stdout}") print(f"Stderr:\n{e.stderr}") print("--- 终止 Hexo 部署流程 ---") return except FileNotFoundError: print(f"❌ 错误: 找不到 Bash 可执行文件: {quoted_bash_path}") print("--- 终止 Hexo 部署流程 ---") return except Exception as e: print(f"❌ 发生未知错误:{e}") print("--- 终止 Hexo 部署流程 ---") return
print("--- 🎉 Hexo 部署流程全部完成! ---") def uploadImage(image_path_or_url): """ 上传单个图片,无论是本地路径还是网络URL。 参数: image_path_or_url: 本地图片路径或网络图片的URL。 返回: 成功上传后返回的博客园图片URL字符串;失败则返回 None。 """ if image_path_or_url.startswith('http'): try:
response = requests.get(image_path_or_url, stream=True) response.raise_for_status() baseName = image_path_or_url.split('/')[-1].split('?')[0] if not baseName or '.' not in baseName: baseName = f"remote_image_{os.urandom(4).hex()}.png"
imageData = response.content suffix = baseName.split(".")[-1] print(f"🌍 正在下载并上传网络图片: {image_path_or_url}")
except Exception as e: print(f"❌ 错误:无法下载或处理网络图片 {image_path_or_url}: {e}") return None else: if not os.path.exists(image_path_or_url): print(f"⚠️ 警告:本地图片文件不存在,跳过上传:{image_path_or_url}") return None with open(image_path_or_url,"rb") as f: imageData = f.read()
baseName = os.path.basename(image_path_or_url) suffix = baseName.split(".")[-1] print(f"🖼️ 正在上传本地图片: {image_path_or_url}") file = dict( bits = imageData, name = baseName, type = f"image/{suffix}" ) try: proxy = xmlrpc.client.ServerProxy(config["url"]) s = proxy.metaWeblog.newMediaObject('', config['username'], config['password'],file) print(f"✨ 上传成功!新URL: {s['url']}") return s["url"] except Exception as e: print(f"❌ 图片上传到博客园失败: {e}") return None
if __name__ == '__main__': if len(sys.argv) <= 1: print("请提供要上传的 Markdown 文件路径作为命令行参数。") else: uploadArticle(sys.argv[1:]) deployHexo()
|