GitHub Action commited on
Commit
43fcc2a
·
1 Parent(s): 20372ef

Sync from GitHub with Git LFS

Browse files
Files changed (1) hide show
  1. scripts/publish_to_blogger.py +29 -43
scripts/publish_to_blogger.py CHANGED
@@ -1,7 +1,6 @@
1
  import os
2
- import pickle
3
  import json
4
- import hashlib
5
  from googleapiclient.discovery import build
6
  import markdown2
7
 
@@ -13,12 +12,12 @@ with open(TOKEN_FILE, 'rb') as f:
13
  service = build('blogger', 'v3', credentials=creds)
14
  BLOG_ID = os.environ['BLOG_ID']
15
 
16
- # published_posts.json лежит рядом со скриптом
17
  SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
18
  JSON_FILE = os.path.join(SCRIPT_DIR, 'published_posts.json')
19
 
20
  # Безопасная загрузка JSON
21
- if os.path.exists(JSON_FILE):
22
  try:
23
  with open(JSON_FILE, 'r', encoding='utf-8') as f:
24
  published = json.load(f)
@@ -29,53 +28,40 @@ else:
29
 
30
  print("Успешно загружен список опубликованных постов:", published)
31
 
32
- # Загружаем OAuth токен
33
- with open(TOKEN_FILE, 'rb') as f:
34
- creds = pickle.load(f)
35
-
36
- service = build('blogger', 'v3', credentials=creds)
37
-
38
- # Загружаем JSON с опубликованными постами
39
- if os.path.exists(JSON_FILE):
40
- with open(JSON_FILE, 'r', encoding='utf-8') as f:
41
- published = json.load(f)
42
- else:
43
- published = {}
44
-
45
- def file_hash(path):
46
- with open(path, 'rb') as f:
47
- return hashlib.sha256(f.read()).hexdigest()
48
 
49
  for filename in os.listdir(POSTS_DIR):
50
  if filename.endswith('.md'):
51
- filepath = os.path.join(POSTS_DIR, filename)
52
- content_hash = file_hash(filepath)
53
- md_content = open(filepath, 'r', encoding='utf-8').read()
54
  html_content = markdown2.markdown(md_content)
55
 
56
- post_info = published.get(filename, {})
57
- post_id = post_info.get('postId')
58
- old_hash = post_info.get('hash')
59
 
60
- if old_hash == content_hash and post_id:
61
- print(f"Пропускаем {filename}, изменений нет")
 
62
  continue
63
 
64
- post = {'title': filename.replace('.md',''), 'content': html_content}
65
-
66
- try:
67
- if post_id:
68
- new_post = service.posts().update(blogId=BLOG_ID, postId=post_id, body=post).execute()
69
- print(f"Пост обновлён: {new_post['url']}")
70
- else:
71
- raise KeyError
72
- except Exception:
73
- new_post = service.posts().insert(blogId=BLOG_ID, body=post).execute()
 
 
 
 
74
  print(f"Пост опубликован: {new_post['url']}")
 
75
 
76
- # Сохраняем новый/обновлённый postId и hash
77
- published[filename] = {'postId': new_post['id'], 'hash': content_hash}
78
-
79
- # Сохраняем JSON
80
  with open(JSON_FILE, 'w', encoding='utf-8') as f:
81
- json.dump(published, f, indent=2, ensure_ascii=False)
 
1
  import os
 
2
  import json
3
+ import pickle
4
  from googleapiclient.discovery import build
5
  import markdown2
6
 
 
12
  service = build('blogger', 'v3', credentials=creds)
13
  BLOG_ID = os.environ['BLOG_ID']
14
 
15
+ # published_posts.json рядом со скриптом
16
  SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
17
  JSON_FILE = os.path.join(SCRIPT_DIR, 'published_posts.json')
18
 
19
  # Безопасная загрузка JSON
20
+ if os.path.exists(JSON_FILE) and os.path.getsize(JSON_FILE) > 0:
21
  try:
22
  with open(JSON_FILE, 'r', encoding='utf-8') as f:
23
  published = json.load(f)
 
28
 
29
  print("Успешно загружен список опубликованных постов:", published)
30
 
31
+ # Папка с Markdown-файлами
32
+ POSTS_DIR = os.path.join(os.path.dirname(SCRIPT_DIR), 'docs')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
  for filename in os.listdir(POSTS_DIR):
35
  if filename.endswith('.md'):
36
+ with open(os.path.join(POSTS_DIR, filename), 'r', encoding='utf-8') as f:
37
+ md_content = f.read()
 
38
  html_content = markdown2.markdown(md_content)
39
 
40
+ title = filename.replace('.md', '')
41
+ content_hash = hash(md_content)
 
42
 
43
+ # если пост уже есть и не изменился → пропускаем
44
+ if title in published and published[title]['hash'] == content_hash:
45
+ print(f"Пост без изменений: {title}")
46
  continue
47
 
48
+ post = {
49
+ 'title': title,
50
+ 'content': html_content
51
+ }
52
+
53
+ if title in published:
54
+ # обновляем пост
55
+ post_id = published[title]['id']
56
+ updated_post = service.posts().update(blogId=BLOG_ID, postId=post_id, body=post).execute()
57
+ print(f"Пост обновлён: {updated_post['url']}")
58
+ published[title] = {"id": post_id, "hash": content_hash}
59
+ else:
60
+ # создаём новый пост
61
+ new_post = service.posts().insert(blogId=BLOG_ID, body=post, isDraft=False).execute()
62
  print(f"Пост опубликован: {new_post['url']}")
63
+ published[title] = {"id": new_post['id'], "hash": content_hash}
64
 
65
+ # сохраняем обновлённый список постов
 
 
 
66
  with open(JSON_FILE, 'w', encoding='utf-8') as f:
67
+ json.dump(published, f, ensure_ascii=False, indent=2)