File size: 3,864 Bytes
5f0ea8d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Reddit threads and subreddit listings from Arctic Shift (arctic-shift.photon-reddit.com), a public archive of Reddit that is
// key-less and sends CORS headers, so the visitor's own browser can read it directly. Reddit itself blocks datacenter IPs, readers
// and anonymous API access (its logged-out RSS ended in November 2026). The archive lags live Reddit by minutes to hours, so very
// fresh threads can show fewer comments and older scores; the output says so.
const API = 'https://arctic-shift.photon-reddit.com/api';
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

export function redditTarget(url) {
  let u; try { u = new URL(url); } catch { return null; }
  if (!/(^|\.)reddit\.com$/.test(u.hostname) && u.hostname !== 'redd.it') return null;
  const t = u.pathname.match(/^\/r\/([^/]+)\/comments\/([a-z0-9]+)/i);
  if (t) return { kind: 'thread', sub: t[1], id: t[2].toLowerCase() };
  if (u.hostname === 'redd.it') { const m = u.pathname.match(/^\/([a-z0-9]+)/i); if (m) return { kind: 'thread', sub: '', id: m[1].toLowerCase() }; }
  const s = u.pathname.match(/^\/r\/([^/]+)\/?(?:hot|new|top|rising|best)?\/?$/i);
  if (s) return { kind: 'sub', sub: s[1] };
  return null;
}

async function api(path, signal) {
  for (let attempt = 0; attempt < 3; attempt++) {
    if (signal?.aborted) throw new DOMException('Stopped', 'AbortError');
    const r = await fetch(API + path, { signal });
    if (r.status === 429) { await sleep(Math.min(20, Math.max(2, +r.headers.get('x-ratelimit-reset') || 5)) * 1000); continue; }   // the API tells us how long to wait
    if (!r.ok) throw new Error(`archive HTTP ${r.status}`);
    return (await r.json()).data;
  }
  throw new Error('archive rate limit');
}

const when = (s) => (s ? new Date(s * 1000).toISOString().slice(0, 10) : '');
const oneLine = (s) => String(s || '').replace(/\s+/g, ' ').trim();
const NOTE = '(From the Arctic Shift archive of Reddit; it can lag live Reddit, so recent comments and scores may be missing.)';

function comments(list, depth, out) {
  for (const n of list || []) {
    if (n.kind !== 't1') continue;
    const c = n.data;
    out.push(`${'  '.repeat(depth)}- u/${c.author} (${c.score ?? '?'}): ${oneLine(c.body)}`);
    const kids = c.replies?.data?.children;
    if (kids && depth < 8) comments(kids, depth + 1, out);
  }
}

export async function redditArchive(url, signal) {
  const t = redditTarget(url);
  if (!t) return '';
  if (t.kind === 'thread') {
    const posts = await api(`/posts/ids?ids=${t.id}`, signal);
    const p = posts?.[0];
    if (!p) return '';
    await sleep(1200);                                   // the archive's rate limit is tight: space the two calls
    let tree = []; try { tree = await api(`/comments/tree?link_id=t3_${t.id}&limit=200`, signal) || []; } catch (e) { if (e.name === 'AbortError') throw e; }
    const lines = [];
    comments(tree, 0, lines);
    return [`Title: ${p.title}`, `URL Source: ${url}`, '', 'Markdown Content:', `# ${p.title}`,
      `r/${p.subreddit} 路 u/${p.author} 路 ${when(p.created_utc)} 路 score ${p.score} 路 ${p.num_comments} comments`, NOTE, '',
      oneLine(p.selftext) || (p.url && !/reddit\.com/.test(p.url) ? `Link: ${p.url}` : ''), '',
      `## Comments (${lines.length} shown)`, ...(lines.length ? lines : ['(no comments in the archive yet)'])].join('\n');
  }
  const posts = await api(`/posts/search?subreddit=${encodeURIComponent(t.sub)}&sort=desc&limit=25&fields=id,title,score,num_comments,created_utc,author,url`, signal);
  if (!posts?.length) return '';
  return [`Title: r/${t.sub} (newest posts)`, `URL Source: ${url}`, '', 'Markdown Content:', `# r/${t.sub}: newest posts`, NOTE, '',
    ...posts.map((p) => `- ${p.title} (${when(p.created_utc)}, score ${p.score}, ${p.num_comments} comments) https://www.reddit.com/r/${t.sub}/comments/${p.id}/`)].join('\n');
}