Repository navigation
Expand file tree
/
Copy pathsync-forum
More file actions
executable file
·176 lines (139 loc) · 4.57 KB
/
Copy pathsync-forum
File metadata and controls
executable file
·176 lines (139 loc) · 4.57 KB
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
#!/usr/bin/python3
from bs4 import BeautifulSoup as BS
import datetime
import dateutil.parser
import glob
import json
import os
from urllib.parse import urlencode
from urllib.request import urlopen, Request
import ruamel.yaml
import time
API_URL = "https://discuss.linuxcontainers.org"
API_USERNAME = "system"
API_KEY = os.environ["API_KEY"]
NEWS_CATEGORY = "/c/news/13"
PROJECTS = ("incus", "lxc", "lxcfs", "distrobuilder")
SCAN_DAYS = 31
def load_json(url, params=None):
time.sleep(1)
url = url.split(API_URL)[-1]
url = "%s/%s.json" % (API_URL, url)
if params:
url = "%s?%s" % (url, urlencode(params))
headers = {}
headers["Api-Key"] = API_KEY
headers["Api-Username"] = API_USERNAME
headers["Content-Type"] = "application/json"
req = Request(url, headers=headers)
return json.loads(urlopen(req).read().decode())
def topic_tags(topic):
# Newer Discourse returns tag objects rather than plain names.
tags = []
for tag in topic.get("tags", []):
if isinstance(tag, dict):
tags.append(tag["name"])
else:
tags.append(tag)
return tags
def topic_project(topic):
tags = topic_tags(topic)
if "release" not in tags:
return None
for project in PROJECTS:
if project in tags:
return project
return None
def load_topic(url):
dis_topic = load_json(url)
dis_post = load_json("/posts/%s" % dis_topic["post_stream"]["posts"][0]["id"])
return dis_topic, dis_post
def build_entry(dis_topic, dis_post):
yaml = ruamel.yaml.YAML()
entry = yaml.load("""
title: foo
date: bar
origin: baz
content: |-
blah""")
entry["content"] = dis_post["raw"]
soup = BS(dis_post["cooked"], features="html.parser")
for imgtag in soup.find_all("img"):
try:
img_hash = imgtag["data-base62-sha1"]
img_src = imgtag["src"]
entry["content"] = entry["content"].replace(
"upload://%s.png" % img_hash, img_src
)
entry["content"] = entry["content"].replace(
"upload://%s.jpeg" % img_hash, img_src
)
except KeyError:
pass
entry["title"] = dis_topic["title"]
date = dateutil.parser.parse(dis_topic["created_at"])
entry["date"] = date.strftime("%Y/%m/%d %H:%M")
entry["origin"] = "%s/t/%s/%s" % (API_URL, dis_topic["slug"], dis_topic["id"])
return entry
def write_entry(path, entry):
yaml = ruamel.yaml.YAML()
with open(path, "w+") as fd:
yaml.dump(entry, fd)
# Update all existing posts
updated = []
for project in PROJECTS:
for post in glob.glob("content/%s/news/*.yaml" % project):
yaml = ruamel.yaml.YAML()
with open(post, "r") as fd:
old_entry = yaml.load(fd)
if "origin" not in old_entry:
continue
try:
dis_topic, dis_post = load_topic(old_entry["origin"])
except Exception:
print("Failed to load: %s" % old_entry["origin"])
continue
entry = build_entry(dis_topic, dis_post)
if entry != old_entry:
write_entry(post, entry)
print("%s => updated" % dis_topic["title"])
else:
print("%s => skipping (up to date)" % dis_topic["title"])
updated.append(dis_topic["id"])
# Import new posts from the past month, newest first
cutoff = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(
days=SCAN_DAYS
)
page = 0
done = False
while not done:
params = {"order": "created", "page": page}
news = load_json("%s/l/latest" % NEWS_CATEGORY, params)
topics = news["topic_list"]["topics"]
if not topics:
break
for topic in topics:
if dateutil.parser.parse(topic["created_at"]) < cutoff:
done = True
break
if topic["id"] in updated:
print("%s => skipping (already exists)" % topic["title"])
continue
project = topic_project(topic)
if not project:
print(
"%s => skipping (not a project release: %s)"
% (topic["title"], topic_tags(topic))
)
continue
try:
dis_topic, dis_post = load_topic("/t/%s" % topic["id"])
except Exception:
print("Failed to load: %s" % topic["id"])
continue
path = "content/%s/news/%s.yaml" % (project, dis_topic["slug"])
write_entry(path, build_entry(dis_topic, dis_post))
print("%s => imported" % dis_topic["title"])
if not news["topic_list"].get("more_topics_url"):
break
page += 1