-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathscript.js
More file actions
418 lines (365 loc) · 13.9 KB
/
Copy pathscript.js
File metadata and controls
418 lines (365 loc) · 13.9 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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
const http = new XMLHttpRequest();
let data;
let output = '';
let style = 0;
let escapeNewLine = false;
let spaceComment = false;
let postLoadAdditionalComments = false
var selectedProxy = 'auto';
// CORS Proxy configurations
const PROXY_CONFIG = {
codetabs: {
name: "CodeTabs",
url: (redditUrl) => `https://api.codetabs.com/v1/proxy?quest=${encodeURIComponent(redditUrl)}`,
parseResponse: (response) => response
},
corslol: {
name: 'CORS.lol',
url: (redditUrl) => `https://api.cors.lol/?url=${encodeURIComponent(redditUrl)}`,
parseResponse: (response) => response
},
direct: {
name: 'Direct',
url: (redditUrl) => redditUrl,
parseResponse: (response) => response
}
};
// Auto mode proxy order (try these in sequence)
const AUTO_PROXY_ORDER = ['codetabs', 'corslol', 'direct'];
const onDocumentReady = () => {
document.getElementById('url-field').value = getQueryParamUrl();
toggleJsonInput();
if (getFieldUrl()) {
startExport();
}
};
function toggleJsonInput() {
const isJsonMode = document.getElementById('proxySelection').value === 'json';
document.getElementById('jsonInputSection').style.display = isJsonMode ? 'block' : 'none';
}
const getQueryParamUrl = () => new URLSearchParams(window.location.search).get(
'url') ?? null;
const getFieldUrl = () => document.getElementById('url-field').value;
function formatRedditJsonUrl(url) {
// Check if URL already has .json extension
if (url.includes('.json')) {
return url;
}
// Find the position of query parameters (?) and fragments (#)
const queryIndex = url.indexOf('?');
const fragmentIndex = url.indexOf('#');
// Determine the earliest special character position
let insertIndex = url.length;
if (queryIndex !== -1) insertIndex = Math.min(insertIndex, queryIndex);
if (fragmentIndex !== -1) insertIndex = Math.min(insertIndex, fragmentIndex);
// Extract base URL and remainder
let baseUrl = url.substring(0, insertIndex);
const remainder = url.substring(insertIndex);
// Remove trailing slash from baseUrl if present
if (baseUrl.endsWith('/')) {
baseUrl = baseUrl.slice(0, -1);
}
// Insert .json at the appropriate position
return `${baseUrl}.json${remainder}`;
}
function updateProxyStatus(message) {
const statusElement = document.getElementById('proxyStatus');
if (message) {
statusElement.textContent = message;
statusElement.style.display = 'block';
} else {
statusElement.style.display = 'none';
}
}
async function fetchWithProxy(redditUrl, proxyKey) {
const config = PROXY_CONFIG[proxyKey];
const requestUrl = config.url(redditUrl);
updateProxyStatus(`Trying ${config.name}...`);
console.log(`Attempting with ${config.name}: ${requestUrl}`);
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', requestUrl);
xhr.responseType = 'json';
xhr.onload = function() {
if (xhr.status === 200) {
try {
let responseData;
// Handle different response formats
if (xhr.response) {
responseData = config.parseResponse(xhr.response);
} else if (xhr.responseText) {
// Try parsing as JSON if we got text
try {
responseData = JSON.parse(xhr.responseText);
} catch (parseError) {
reject(new Error(`Failed to parse JSON response from ${config.name}: ${parseError.message}`));
return;
}
} else {
reject(new Error(`Empty response from ${config.name}`));
return;
}
console.log(`Response from ${config.name}:`, responseData);
// Validate Reddit data structure
if (responseData && Array.isArray(responseData) && responseData.length >= 2 &&
responseData[0] && responseData[0].data && responseData[0].data.children &&
responseData[1] && responseData[1].data && responseData[1].data.children) {
updateProxyStatus(`✅ Success with ${config.name}`);
resolve(responseData);
} else {
reject(new Error(`Invalid Reddit data structure from ${config.name}`));
}
} catch (e) {
reject(new Error(`Parse error with ${config.name}: ${e.message}`));
}
} else {
reject(new Error(`HTTP ${xhr.status} from ${config.name}`));
}
};
xhr.onerror = function() {
// Check for common CORS errors
if (window.location.protocol === 'file:') {
reject(new Error(`CORS error with ${config.name} - Try serving from HTTP server instead of opening file directly`));
} else {
reject(new Error(`Network error with ${config.name}`));
}
};
xhr.ontimeout = function() {
reject(new Error(`Timeout with ${config.name}`));
};
xhr.timeout = 10000; // 10 second timeout
xhr.send();
});
}
function processRedditData(responseData, filename = 'output.md') {
output = '';
data = responseData;
const post = data[0].data.children[0].data;
const comments = data[1].data.children;
displayTitle(post);
output += '\n\n## Comments\n\n';
comments.forEach((comment) => displayComment(comment, null));
console.log('Done');
let output_display = document.getElementById('output-display');
let output_block = document.getElementById('output-block');
output_block.removeAttribute('hidden');
output_display.innerHTML = output;
download(output_display.textContent, filename, 'text/plain');
}
async function fetchData(url) {
const redditUrl = formatRedditJsonUrl(url);
try {
let responseData = null;
if (selectedProxy === 'auto') {
// Try each proxy in sequence until one works
for (const proxyKey of AUTO_PROXY_ORDER) {
try {
responseData = await fetchWithProxy(redditUrl, proxyKey);
break; // Success! Exit the loop
} catch (error) {
console.warn(`${PROXY_CONFIG[proxyKey].name} failed:`, error.message);
// Continue to next proxy
}
}
if (!responseData) {
updateProxyStatus('❌ All proxies failed');
let errorMessage = 'Unable to fetch data with any proxy service. ';
if (window.location.protocol === 'file:') {
errorMessage += 'Try serving this page from an HTTP server (e.g., python -m http.server 8000) instead of opening the HTML file directly.';
} else {
errorMessage += 'Please check the Reddit URL or try again later.';
}
alert(errorMessage);
return;
}
} else {
// Use specific proxy
responseData = await fetchWithProxy(redditUrl, selectedProxy);
}
// Process the data
// Get last part of URL without query params
let filename = redditUrl.split(/\?|#|&/)[0].split('/').pop().replace('.json', '') + '.reddit.md';
processRedditData(responseData, filename);
} catch (error) {
console.error('Fetch error:', error);
updateProxyStatus(`❌ Error: ${error.message}`);
let errorMessage = `Failed to fetch Reddit data: ${error.message}`;
// Add helpful suggestions based on error type
if (error.message.includes('CORS error')) {
errorMessage += '\n\nSuggestion: Try serving this page from an HTTP server instead of opening the HTML file directly.';
} else if (error.message.includes('Invalid Reddit data structure')) {
errorMessage += '\n\nSuggestion: Please verify the Reddit URL is correct and includes the full post URL.';
} else if (error.message.includes('Network error') && selectedProxy === 'direct') {
errorMessage += '\n\nSuggestion: Try enabling a CORS proxy from the dropdown above.';
}
alert(errorMessage);
}
}
function loadMoreComments(url, parentid, depthInd) {
const h2 = new XMLHttpRequest()
//to allow the newly loaded comments to appear in the correct place, this call has to be synchronous
h2.open('GET', `${url}/${parentid}.json`, false);
//setting a desired response type is not supported for non-async calls
//h2.responseType = 'json';
h2.send();
//as a response type cannot be set, the result needs to be parsed to JSON manually.
const d2 = JSON.parse(h2.responseText)
const comments = d2[1].data.children[0].data.replies.data.children;
comments.forEach((comment) => displayComment(comment, depthInd));
}
function setStyle() {
if (document.getElementById('treeOption').checked) {
style = 0;
} else if (document.getElementById('listOption').checked) {
style = 1;
} else {
style = 2
}
if (document.getElementById('escapeNewLine').checked) {
escapeNewLine = true;
} else {
escapeNewLine = false;
}
if (document.getElementById('spaceComment').checked) {
spaceComment = true;
} else {
spaceComment = false;
}
if (document.getElementById('postLoadComments').checked) {
postLoadAdditionalComments = true;
} else {
postLoadAdditionalComments = false;
}
selectedProxy = document.getElementById('proxySelection').value;
}
function startExport() {
console.log('Start exporting');
setStyle();
if (selectedProxy === 'json') {
exportFromJson();
return;
}
let url = getFieldUrl();
if (url) {
fetchData(url);
} else {
console.log('No url provided');
}
}
function exportFromJson() {
const jsonText = document.getElementById('jsonInput').value.trim();
if (!jsonText) {
alert('Paste Reddit JSON data into the text area.');
return;
}
let responseData;
try {
responseData = JSON.parse(jsonText);
} catch (error) {
alert(`That's not valid JSON data. Please review the instructions and try again.`);
return;
}
processRedditData(responseData);
}
async function copyExport() {
/*according to https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/writeText
this should only work in 'Secure Contexts' (https or localhost/loopback addresses)
Since GitHub Pages supports https and getting a certificate for any other host is a 10 minute job
I believe it is acceptable to use this despite its restrictions*/
try {
await navigator.clipboard.writeText(document.getElementById('output-display').textContent);
} catch (error) {
console.error('Failed to copy to clipboard:', error.message);
}
}
function download(text, name, type) {
document.getElementById('copyButton').removeAttribute('disabled');
let download_button = document.getElementById('downloadButton');
download_button.removeAttribute('disabled');
let file = new Blob([text], { type: type });
download_button.href = URL.createObjectURL(file);
download_button.download = name;
}
function displayTitle(post) {
output += `# ${post.title}\n`;
if (post.selftext) {
output += `\n${post.selftext}\n`;
}
output += `\n[permalink](http://reddit.com${post.permalink})`;
output += `\nby *${post.author}* (↑ ${post.ups}/ ↓ ${post.downs})`;
}
function formatComment(text) {
if (escapeNewLine) {
return text.replace(/(\r\n|\n|\r)/gm, '');
} else {
return text;
}
}
function displayComment(comment, preexistingDepth = null) {
let currentDepth = preexistingDepth != null ? preexistingDepth : comment.data.depth;
let depthTag
if (style == 0) {
if (currentDepth > 0) {
depthTag = `├${'─'.repeat(currentDepth)} `;
} else {
depthTag = `##### `;
}
} else if (style == 1) {
if (currentDepth > 0) {
depthTag = `${'\t'.repeat(currentDepth)}- `;
} else {
depthTag = `- `;
}
}
else {
depthTag = '>'.repeat(currentDepth + 1);
}
if (comment.data.body) {
console.log(formatComment(comment.data.body));
if (style < 2) {
output += `${depthTag}${formatComment(
comment.data.body)} ⏤ by *${comment.data.author}* (↑ ${comment.data.ups
}/ ↓ ${comment.data.downs})\n`;
}
else {
if (currentDepth == 0) {
/*to make it unambiguous if two block quotes should be seperate or one and the same
they need to be seperated by at least one character not part of either (I chose NBSP)*/
output += '&nbsp;\n\n'
}
output += `${depthTag}\n${depthTag}#### [**${comment.data.author}** ${comment.data.author_flair_text ? `'***${comment.data.author_flair_text}***' ` : ''}(↑ ${comment.data.ups}/ ↓ ${comment.data.downs}) @${new Date(comment.data.created_utc * 1000).toISOString()}${comment.data.edited ? ` (edited @${new Date(comment.data.edited * 1000).toISOString()})` : ''}](${getFieldUrl()}/${comment.data.id})\n${depthTag}\n${depthTag}${formatComment(comment.data.body).trimEnd().replace(/!</g, '!&lt;').replace(/>!/g, '&gt;!').replace(/\n/g, `\n${depthTag}`)}\n`;
//the !</>! replacement is to force retain the escaping of </> in spoiler tags to avoid confusion between blockquotes and spoilers
}
} else if (comment.kind === "more") {
let parentID = comment.data.parent_id.substring(3);
if (postLoadAdditionalComments) {
loadMoreComments(getFieldUrl(), parentID, currentDepth); ""
}
else {
output += `${depthTag}${style == 2 ? `\n${depthTag}#### ` : ''}comment depth-limit (${currentDepth}) reached. [view on reddit](${getFieldUrl()}/${parentID})\n`;
}
} else {
output += `${depthTag}${style == 2 ? `\n${depthTag}#### ` : ''}deleted\n`;
}
if (comment.data.replies) {
const subComments = comment.data.replies.data.children;
subComments.forEach((subComment) => displayComment(subComment, preexistingDepth != null ? preexistingDepth + 1 : null));
}
if (style == 2) {
/*do note, this is NOT depthTag, it has one fewer symbol
this is required forcibly split the block-quotes for two comments on the same level.
It technically generates more markers than strictly necessary,
but those extra ones are not harmful, and depending on your interpretation,
can even more sematically correct than if they were absent*/
output += '>'.repeat(currentDepth);
output += '\n'
}
if (currentDepth == 0 && comment.data.replies) {
if (style == 0) {
output += '└────\n\n';
}
if (spaceComment) {
output += '\n';
}
}
}