save.js
1 import { CommandExecutionError } from '@jackwener/opencli/errors'; 2 import { cli, Strategy } from '@jackwener/opencli/registry'; 3 cli({ 4 site: 'reddit', 5 name: 'save', 6 description: 'Save or unsave a Reddit post', 7 domain: 'reddit.com', 8 strategy: Strategy.COOKIE, 9 browser: true, 10 args: [ 11 { name: 'post-id', type: 'string', required: true, positional: true, help: 'Post ID (e.g. 1abc123) or fullname (t3_xxx)' }, 12 { name: 'undo', type: 'boolean', default: false, help: 'Unsave instead of save' }, 13 ], 14 columns: ['status', 'message'], 15 func: async (page, kwargs) => { 16 if (!page) 17 throw new CommandExecutionError('Browser session required'); 18 await page.goto('https://www.reddit.com'); 19 const result = await page.evaluate(`(async () => { 20 try { 21 let postId = ${JSON.stringify(kwargs['post-id'])}; 22 const urlMatch = postId.match(/comments\\/([a-z0-9]+)/); 23 if (urlMatch) postId = urlMatch[1]; 24 const fullname = postId.startsWith('t3_') || postId.startsWith('t1_') 25 ? postId : 't3_' + postId; 26 27 const undo = ${kwargs.undo ? 'true' : 'false'}; 28 const endpoint = undo ? '/api/unsave' : '/api/save'; 29 30 // Get modhash 31 const meRes = await fetch('/api/me.json', { credentials: 'include' }); 32 const me = await meRes.json(); 33 const modhash = me?.data?.modhash || ''; 34 35 const res = await fetch(endpoint, { 36 method: 'POST', 37 credentials: 'include', 38 headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, 39 body: 'id=' + encodeURIComponent(fullname) 40 + (modhash ? '&uh=' + encodeURIComponent(modhash) : ''), 41 }); 42 43 if (!res.ok) return { ok: false, message: 'HTTP ' + res.status }; 44 return { ok: true, message: (undo ? 'Unsaved' : 'Saved') + ' ' + fullname }; 45 } catch (e) { 46 return { ok: false, message: e.toString() }; 47 } 48 })()`); 49 return [{ status: result.ok ? 'success' : 'failed', message: result.message }]; 50 } 51 });