File size: 4,381 Bytes
9580dce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * Wikipedia MediaWiki API client for source curation.
 *
 * Uses the MediaWiki Action API to search for topics and extract
 * relevant content. Rate-limited to stay well within the 10K req/hr
 * authenticated limit (we don't even need auth for this volume).
 *
 * All content from Wikipedia is licensed under CC BY-SA 4.0.
 */

const WIKIPEDIA_API = "https://en.wikipedia.org/w/api.php";
const USER_AGENT = "RotNot/1.0 (educational app; contact: github.com/CuriosityQuantified/rotnot)";

export interface WikiSearchResult {
  pageId: number;
  title: string;
  snippet: string; // HTML snippet from search
}

export interface WikiExtract {
  pageId: number;
  title: string;
  url: string;
  extract: string; // plain-text extract (first N characters)
}

/**
 * Search Wikipedia for pages matching a query.
 * Returns up to `limit` results (default 3).
 */
export async function searchWikipedia(
  query: string,
  limit: number = 3,
): Promise<WikiSearchResult[]> {
  const params = new URLSearchParams({
    action: "query",
    list: "search",
    srsearch: query,
    srlimit: String(limit),
    srinfo: "totalhits",
    srprop: "snippet",
    format: "json",
    origin: "*",
  });

  const response = await fetch(`${WIKIPEDIA_API}?${params}`, {
    headers: { "User-Agent": USER_AGENT },
  });

  if (!response.ok) {
    throw new Error(`Wikipedia search failed: ${response.status} ${response.statusText}`);
  }

  const data = await response.json();
  const results = data?.query?.search ?? [];

  return results.map((r: { pageid: number; title: string; snippet: string }) => ({
    pageId: r.pageid,
    title: r.title,
    snippet: stripHtml(r.snippet),
  }));
}

/**
 * Fetch a plain-text extract for a Wikipedia page by title.
 * Returns up to `maxChars` characters of the article's introduction.
 */
export async function getWikipediaExtract(
  title: string,
  maxChars: number = 3000,
): Promise<WikiExtract | null> {
  const params = new URLSearchParams({
    action: "query",
    titles: title,
    prop: "extracts|info",
    exintro: "1", // intro section only
    explaintext: "1", // plain text, no HTML
    exchars: String(maxChars),
    inprop: "url",
    format: "json",
    origin: "*",
  });

  const response = await fetch(`${WIKIPEDIA_API}?${params}`, {
    headers: { "User-Agent": USER_AGENT },
  });

  if (!response.ok) {
    throw new Error(`Wikipedia extract failed: ${response.status} ${response.statusText}`);
  }

  const data = await response.json();
  const pages = data?.query?.pages ?? {};
  const pageId = Object.keys(pages)[0];

  if (!pageId || pageId === "-1") {
    return null; // page not found
  }

  const page = pages[pageId];
  if (!page.extract || page.extract.trim().length < 50) {
    return null; // stub or disambiguation page
  }

  return {
    pageId: Number(pageId),
    title: page.title,
    url: page.fullurl || `https://en.wikipedia.org/wiki/${encodeURIComponent(page.title.replace(/ /g, "_"))}`,
    extract: page.extract.trim(),
  };
}

/**
 * Search for a topic and return extracts for the top matching pages.
 * This is the main entry point — combines search + extract in one call.
 *
 * Returns up to `maxResults` extracts with substantive content.
 */
export async function fetchWikipediaSources(
  topic: string,
  maxResults: number = 3,
): Promise<WikiExtract[]> {
  const searchResults = await searchWikipedia(topic, maxResults + 2); // fetch a few extra in case some are stubs

  const extracts: WikiExtract[] = [];
  for (const result of searchResults) {
    if (extracts.length >= maxResults) break;

    const extract = await getWikipediaExtract(result.title);
    if (extract) {
      extracts.push(extract);
    }
  }

  return extracts;
}

/**
 * Verify that a Wikipedia URL is still live (HEAD request).
 */
export async function verifyWikipediaUrl(url: string): Promise<boolean> {
  try {
    const response = await fetch(url, {
      method: "HEAD",
      headers: { "User-Agent": USER_AGENT },
    });
    return response.ok;
  } catch {
    return false;
  }
}

/**
 * Strip HTML tags from a string (used for search snippets).
 */
function stripHtml(html: string): string {
  return html
    .replace(/<[^>]+>/g, "")
    .replace(/&quot;/g, '"')
    .replace(/&amp;/g, "&")
    .replace(/&lt;/g, "<")
    .replace(/&gt;/g, ">")
    .replace(/&#039;/g, "'")
    .replace(/&nbsp;/g, " ");
}