GitHub Action commited on
Commit
a2201b3
·
1 Parent(s): 95f9f51

Sync from GitHub with Git LFS

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