/ clis / linux-do / user-posts.js
user-posts.js
 1  import { cli, Strategy } from '@jackwener/opencli/registry';
 2  import { fetchLinuxDoJson } from './feed.js';
 3  function toLocalTime(utcStr) {
 4      if (!utcStr)
 5          return '';
 6      const date = new Date(utcStr);
 7      return Number.isNaN(date.getTime()) ? utcStr : date.toLocaleString();
 8  }
 9  function strip(html) {
10      return (html || '')
11          .replace(/<br\s*\/?>/gi, ' ')
12          .replace(/<\/(p|div|li|blockquote|h[1-6])>/gi, ' ')
13          .replace(/<[^>]+>/g, '')
14          .replace(/&nbsp;/g, ' ')
15          .replace(/&amp;/g, '&')
16          .replace(/&lt;/g, '<')
17          .replace(/&gt;/g, '>')
18          .replace(/&quot;/g, '"')
19          .replace(/&#(?:(\d+)|x([0-9a-fA-F]+));/g, (_, dec, hex) => {
20          try {
21              return String.fromCodePoint(dec !== undefined ? Number(dec) : parseInt(hex, 16));
22          }
23          catch {
24              return '';
25          }
26      })
27          .replace(/\s+/g, ' ')
28          .trim();
29  }
30  cli({
31      site: 'linux-do',
32      name: 'user-posts',
33      description: 'linux.do 用户的帖子',
34      domain: 'linux.do',
35      strategy: Strategy.COOKIE,
36      browser: true,
37      args: [
38          { name: 'username', required: true, positional: true, help: 'Username' },
39          { name: 'limit', type: 'int', default: 20, help: 'Number of posts' },
40      ],
41      columns: ['index', 'topic_user', 'topic', 'reply', 'time', 'url'],
42      func: async (page, kwargs) => {
43          const username = String(kwargs.username);
44          const limit = kwargs.limit;
45          const data = await fetchLinuxDoJson(page, `/user_actions.json?username=${encodeURIComponent(username)}&filter=5&offset=0&limit=${limit}`);
46          const actions = (data?.user_actions || []);
47          return actions.slice(0, limit).map((a, i) => ({
48              index: i + 1,
49              topic_user: a.acting_username || a.username || '',
50              topic: a.title || '',
51              reply: strip(a.excerpt).slice(0, 200),
52              time: toLocalTime(a.created_at),
53              url: 'https://linux.do/t/topic/' + a.topic_id + '/' + a.post_number,
54          }));
55      },
56  });