GitHub Action commited on
Commit ·
43fcc2a
1
Parent(s): 20372ef
Sync from GitHub with Git LFS
Browse files12345675 unmodified lines1314151617181920212223244 unmodified lines2930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081import osimport pickleimport jsonimport hashlibfrom googleapiclient.discovery import buildimport markdown25 unmodified linesservice = build('blogger', 'v3', credentials=creds)BLOG_ID = os.environ['BLOG_ID']# published_posts.json лежит рядом со скриптомSCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))JSON_FILE = os.path.join(SCRIPT_DIR, 'published_posts.json')# Безопасная загрузка JSONif os.path.exists(JSON_FILE):try:with open(JSON_FILE, 'r', encoding='utf-8') as f:published = json.load(f)4 unmodified linesprint("Успешно загружен список опубликованных постов:", published)# Загружаем OAuth токенwith open(TOKEN_FILE, 'rb') as f:creds = pickle.load(f)service = build('blogger', 'v3', credentials=creds)# Загружаем JSON с опубликованными постамиif os.path.exists(JSON_FILE):with open(JSON_FILE, 'r', encoding='utf-8') as f:published = json.load(f)else:published = {}def file_hash(path):with open(path, 'rb') as f:return hashlib.sha256(f.read()).hexdigest()for filename in os.listdir(POSTS_DIR):if filename.endswith('.md'):filepath = os.path.join(POSTS_DIR, filename)content_hash = file_hash(filepath)md_content = open(filepath, 'r', encoding='utf-8').read()html_content = markdown2.markdown(md_content)post_info = published.get(filename, {})post_id = post_info.get('postId')old_hash = post_info.get('hash')if old_hash == content_hash and post_id:print(f"Пропускаем {filename}, изменений нет")continuepost = {'title': filename.replace('.md',''), 'content': html_content}try:if post_id:new_post = service.posts().update(blogId=BLOG_ID, postId=post_id, body=post).execute()print(f"Пост обновлён: {new_post['url']}")else:raise KeyErrorexcept Exception:new_post = service.posts().insert(blogId=BLOG_ID, body=post).execute()print(f"Пост опубликован: {new_post['url']}")# Сохраняем новый/обновлённый postId и hashpublished[filename] = {'postId': new_post['id'], 'hash': content_hash}# Сохраняем JSONwith open(JSON_FILE, 'w', encoding='utf-8') as f:json.dump(published, f, indent=2, ensure_ascii=False)1234565 unmodified lines1213141516171819202122234 unmodified lines28293031323334353637383940414243444546474849505152535455565758596061626364656667import osimport jsonimport picklefrom googleapiclient.discovery import buildimport markdown25 unmodified linesservice = build('blogger', 'v3', credentials=creds)BLOG_ID = os.environ['BLOG_ID']# published_posts.json рядом со скриптомSCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))JSON_FILE = os.path.join(SCRIPT_DIR, 'published_posts.json')# Безопасная загрузка JSONif os.path.exists(JSON_FILE) and os.path.getsize(JSON_FILE) > 0:try:with open(JSON_FILE, 'r', encoding='utf-8') as f:published = json.load(f)4 unmodified linesprint("Успешно загружен список опубликованных постов:", published)# Папка с Markdown-файламиPOSTS_DIR = os.path.join(os.path.dirname(SCRIPT_DIR), 'docs')for filename in os.listdir(POSTS_DIR):if filename.endswith('.md'):with open(os.path.join(POSTS_DIR, filename), 'r', encoding='utf-8') as f:md_content = f.read()html_content = markdown2.markdown(md_content)title = filename.replace('.md', '')content_hash = hash(md_content)# если пост уже есть и не изменился → пропускаемif title in published and published[title]['hash'] == content_hash:print(f"Пост без изменений: {title}")continuepost = {'title': title,'content': html_content}if title in published:# обновляем постpost_id = published[title]['id']updated_post = service.posts().update(blogId=BLOG_ID, postId=post_id, body=post).execute()print(f"Пост обновлён: {updated_post['url']}")published[title] = {"id": post_id, "hash": content_hash}else:# создаём новый постnew_post = service.posts().insert(blogId=BLOG_ID, body=post, isDraft=False).execute()print(f"Пост опубликован: {new_post['url']}")published[title] = {"id": new_post['id'], "hash": content_hash}# сохраняем обновлённый список постовwith open(JSON_FILE, 'w', encoding='utf-8') as f:json.dump(published, f, ensure_ascii=False, indent=2)
scripts/publish_to_blogger.py+29-43