File size: 2,669 Bytes
02f8da8 | 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 | import sys; sys.path.insert(0, __import__('os').path.dirname(__file__))
from common import *
import html as _html
from concurrent.futures import ThreadPoolExecutor
H = "https://forums.factorio.com"
def search(prefix):
topics, start, total = [], 0, None
while True:
b = get(f"{H}/search.php?keywords={prefix}%2A&sr=topics&sk=t&sd=d&start={start}")
if not b: break
s = b.decode("utf-8", "replace")
if total is None:
m = re.search(r"Search found (\d+) match", s); total = int(m.group(1)) if m else 0
ts = re.findall(r"viewtopic\.php\?t=(\d+)", s)
if not ts: break
topics += ts; start += 25
if start >= total: break
time.sleep(1)
print(prefix, total, len(set(topics)), flush=True)
return topics
TP = os.environ.get("CACHE", "cache") + "/forum_topics.json"
if os.path.exists(TP): topics = json.load(open(TP))
else:
topics = list(dict.fromkeys(t for p in ["0eN", "0eJ", "0eF", "0eA"] for t in search(p)))
json.dump(topics, open(TP, "w"))
w = Writer("factorio-forums")
done_topics = {i.split("-")[0] for i in w.seen}
todo = [t for t in topics if t not in done_topics]
print(len(topics), "topics", len(todo), "todo", flush=True)
POST_RE = re.compile(r'<div id="p(\d+)" class="post (.*?)(?=<div id="p\d+" class="post |<div class="action-bar bar-bottom)', re.S)
def one(t):
start, seen_posts, n = 0, set(), 0
title = None
while start < 5000:
b = get(f"{H}/viewtopic.php?t={t}&start={start}")
if not b: break
s = b.decode("utf-8", "replace")
if title is None:
m = re.search(r'<h2 class="topic-title"><a [^>]*>(.*?)</a>', s); title = _html.unescape(m.group(1)) if m else None
posts = [(pid, body) for pid, body in POST_RE.findall(s) if pid not in seen_posts]
if not posts: break
for pid, body in posts:
seen_posts.add(pid)
au = re.search(r'class="username(?:-coloured)?"[^>]*>([^<]+)', body)
tm = re.search(r'<time datetime="([^"]+)"', body)
for k, bp in enumerate(extract_bps(body)):
n += w.write({"id": f"{t}-{pid}-{k}", "url": f"{H}/viewtopic.php?p={pid}#p{pid}", "title": title,
"author": au and au.group(1), "tags": [], "created": tm and tm.group(1), "string": bp})
start += 20
return n
t0 = time.time(); done = 0
with ThreadPoolExecutor(6) as ex:
for r in ex.map(one, todo):
done += 1
if done % 100 == 0: print(done, w.n, round(time.time() - t0), flush=True)
w.close(); print("DONE", w.n, "new;", len(w.seen), "total", round(time.time() - t0), "s", flush=True)
|