|
| 1 | +import { ArgumentError, AuthRequiredError, CommandExecutionError, EmptyResultError } from '@jackwener/opencli/errors'; |
| 2 | +import { cli, Strategy } from '@jackwener/opencli/registry'; |
| 3 | + |
| 4 | +export const REDDIT_SUBSCRIBED_MAX_LIMIT = 1000; |
| 5 | + |
| 6 | +export function parseRedditSubscribedLimit(raw) { |
| 7 | + if (raw === undefined || raw === null || raw === '') return 100; |
| 8 | + const n = Number(raw); |
| 9 | + if (!Number.isFinite(n) || !Number.isInteger(n) || n < 1 || n > REDDIT_SUBSCRIBED_MAX_LIMIT) { |
| 10 | + throw new ArgumentError( |
| 11 | + `limit must be an integer in [1, ${REDDIT_SUBSCRIBED_MAX_LIMIT}].`, |
| 12 | + `Got: ${raw}`, |
| 13 | + ); |
| 14 | + } |
| 15 | + return n; |
| 16 | +} |
| 17 | + |
| 18 | +export function unwrapEvaluateResult(payload) { |
| 19 | + if (payload && typeof payload === 'object' && !Array.isArray(payload) && 'session' in payload && 'data' in payload) { |
| 20 | + return payload.data; |
| 21 | + } |
| 22 | + return payload; |
| 23 | +} |
| 24 | + |
| 25 | +function mapSubredditRow(entry, index) { |
| 26 | + const data = entry?.data; |
| 27 | + if (!data || typeof data !== 'object') { |
| 28 | + throw new CommandExecutionError(`Reddit subscriptions row ${index + 1} was missing data.`); |
| 29 | + } |
| 30 | + const fullname = typeof data.name === 'string' ? data.name : ''; |
| 31 | + const id = fullname.startsWith('t5_') |
| 32 | + ? fullname |
| 33 | + : (entry?.kind === 't5' && typeof data.id === 'string' && data.id ? `t5_${data.id}` : ''); |
| 34 | + const displayName = typeof data.display_name === 'string' && data.display_name |
| 35 | + ? data.display_name |
| 36 | + : ''; |
| 37 | + const subreddit = typeof data.display_name_prefixed === 'string' && data.display_name_prefixed |
| 38 | + ? data.display_name_prefixed |
| 39 | + : (displayName ? `r/${displayName}` : ''); |
| 40 | + const path = typeof data.url === 'string' && data.url.startsWith('/r/') ? data.url : ''; |
| 41 | + if (!id || !displayName || !subreddit || !path) { |
| 42 | + throw new CommandExecutionError(`Reddit subscriptions row ${index + 1} was missing subreddit identity.`); |
| 43 | + } |
| 44 | + return { |
| 45 | + id, |
| 46 | + subreddit, |
| 47 | + title: typeof data.title === 'string' ? data.title : '', |
| 48 | + subscribers: typeof data.subscribers === 'number' ? data.subscribers : null, |
| 49 | + description: typeof data.public_description === 'string' ? data.public_description.slice(0, 200) : '', |
| 50 | + url: 'https://www.reddit.com' + path, |
| 51 | + }; |
| 52 | +} |
| 53 | + |
| 54 | +cli({ |
| 55 | + site: 'reddit', |
| 56 | + name: 'subscribed', |
| 57 | + description: 'List subreddits you are subscribed to', |
| 58 | + access: 'read', |
| 59 | + domain: 'reddit.com', |
| 60 | + strategy: Strategy.COOKIE, |
| 61 | + browser: true, |
| 62 | + args: [ |
| 63 | + { name: 'limit', type: 'int', default: 100, help: `Max subreddits to return (1-${REDDIT_SUBSCRIBED_MAX_LIMIT}, auto-paginates)` }, |
| 64 | + ], |
| 65 | + columns: ['id', 'subreddit', 'title', 'subscribers', 'description', 'url'], |
| 66 | + func: async (page, kwargs) => { |
| 67 | + const limit = parseRedditSubscribedLimit(kwargs.limit); |
| 68 | + if (!page) |
| 69 | + throw new CommandExecutionError('Browser session required'); |
| 70 | + await page.goto('https://www.reddit.com'); |
| 71 | + const result = unwrapEvaluateResult(await page.evaluate(`(async () => { |
| 72 | + try { |
| 73 | + const meRes = await fetch('/api/me.json?raw_json=1', { credentials: 'include' }); |
| 74 | + if (meRes.status === 401 || meRes.status === 403) { |
| 75 | + return { kind: 'auth', detail: 'Reddit /api/me.json returned HTTP ' + meRes.status }; |
| 76 | + } |
| 77 | + if (!meRes.ok) { |
| 78 | + return { kind: 'http', httpStatus: meRes.status, where: '/api/me.json' }; |
| 79 | + } |
| 80 | + const me = await meRes.json(); |
| 81 | + const username = me?.data?.name || me?.name; |
| 82 | + if (!username) return { kind: 'auth', detail: 'Not logged in to reddit.com (no identity in /api/me.json)' }; |
| 83 | +
|
| 84 | + const target = ${JSON.stringify(limit)}; |
| 85 | + const PAGE_SIZE = 100; |
| 86 | + const out = []; |
| 87 | + let after = null; |
| 88 | + const seenCursors = new Set(); |
| 89 | + for (let pageIndex = 0; pageIndex < 20 && out.length < target; pageIndex++) { |
| 90 | + const remaining = target - out.length; |
| 91 | + const pageLimit = Math.min(PAGE_SIZE, remaining); |
| 92 | + const url = '/subreddits/mine/subscriptions.json?limit=' + pageLimit |
| 93 | + + '&raw_json=1' |
| 94 | + + (after ? '&after=' + encodeURIComponent(after) : ''); |
| 95 | + const res = await fetch(url, { credentials: 'include' }); |
| 96 | + if (res.status === 401 || res.status === 403) { |
| 97 | + return { kind: 'auth', detail: 'Reddit subscriptions endpoint returned HTTP ' + res.status }; |
| 98 | + } |
| 99 | + if (!res.ok) return { kind: 'http', httpStatus: res.status, where: url }; |
| 100 | + const d = await res.json(); |
| 101 | + const children = d?.data?.children; |
| 102 | + if (!Array.isArray(children)) { |
| 103 | + return { kind: 'malformed', detail: 'Reddit subscriptions payload was missing data.children.' }; |
| 104 | + } |
| 105 | + for (const child of children) { |
| 106 | + if (out.length >= target) break; |
| 107 | + out.push(child); |
| 108 | + } |
| 109 | + const next = d?.data?.after ?? null; |
| 110 | + if (next !== null && typeof next !== 'string') { |
| 111 | + return { kind: 'malformed', detail: 'Reddit subscriptions payload had a malformed after cursor.' }; |
| 112 | + } |
| 113 | + if (out.length >= target || !next) break; |
| 114 | + if (children.length === 0) { |
| 115 | + return { kind: 'malformed', detail: 'Reddit subscriptions page was empty but returned an after cursor.' }; |
| 116 | + } |
| 117 | + if (seenCursors.has(next)) { |
| 118 | + return { kind: 'malformed', detail: 'Reddit subscriptions repeated pagination cursor ' + next + '.' }; |
| 119 | + } |
| 120 | + seenCursors.add(next); |
| 121 | + after = next; |
| 122 | + } |
| 123 | + if (out.length < target && after) { |
| 124 | + return { kind: 'malformed', detail: 'Reddit subscriptions pagination exceeded the safety cap before satisfying the requested limit.' }; |
| 125 | + } |
| 126 | + return { kind: 'ok', entries: out }; |
| 127 | + } catch (e) { |
| 128 | + return { kind: 'exception', detail: String(e && e.message || e) }; |
| 129 | + } |
| 130 | + })()`)); |
| 131 | + if (result?.kind === 'auth') { |
| 132 | + throw new AuthRequiredError('reddit.com', result.detail); |
| 133 | + } |
| 134 | + if (result?.kind === 'http') { |
| 135 | + throw new CommandExecutionError(`HTTP ${result.httpStatus} from ${result.where}`); |
| 136 | + } |
| 137 | + if (result?.kind === 'malformed') { |
| 138 | + throw new CommandExecutionError(result.detail); |
| 139 | + } |
| 140 | + if (result?.kind === 'exception') { |
| 141 | + throw new CommandExecutionError(`subscribed failed: ${result.detail}`); |
| 142 | + } |
| 143 | + if (result?.kind !== 'ok' || !Array.isArray(result.entries)) { |
| 144 | + throw new CommandExecutionError(`Unexpected result from reddit subscribed: ${JSON.stringify(result)}`); |
| 145 | + } |
| 146 | + const rows = result.entries.slice(0, limit).map((entry, index) => mapSubredditRow(entry, index)); |
| 147 | + if (rows.length === 0) { |
| 148 | + throw new EmptyResultError('Reddit returned no subscribed subreddits for the logged-in account.'); |
| 149 | + } |
| 150 | + return rows; |
| 151 | + } |
| 152 | +}); |
0 commit comments