From d0d3b6b8701f0d4a3fc8e5a62eaaa06103df7765 Mon Sep 17 00:00:00 2001 From: Hower He Date: Mon, 15 May 2023 10:14:55 -0400 Subject: [PATCH] =?UTF-8?q?feat(route):=20=E5=B0=8F=E7=BA=A2=E4=B9=A6=20?= =?UTF-8?q?=E7=94=A8=E6=88=B7=E7=AC=94=E8=AE=B0=20=E5=85=A8=E6=96=87=20(#1?= =?UTF-8?q?2330)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(route): 小红书 用户笔记(全文抓取) * fixed package.json's semver prefix character * fixed conditions for user page response * fixed timed out issue when getting full text * removed the capability to get full text * added full text feature for notes * added filter for unnecessary resources requested * Switched to a concise way to get JSON from HTML * to bypass the null checked warning from DeepScan * added note full text to cache * added more readable error messages * moved full text feature under a new parameter * Update maintainer format * Refactor the error message typing * Refactor the error message typing * Refactor error message typing * Refactor the usage of `tryGet` for expire time * Close the user page earlier to release resouces --------- --- docs/social-media.md | 6 +- lib/v2/xiaohongshu/maintainer.js | 2 +- lib/v2/xiaohongshu/notes.js | 16 ++++ lib/v2/xiaohongshu/router.js | 1 + lib/v2/xiaohongshu/util.js | 125 +++++++++++++++++++++++++++++++ 5 files changed, 148 insertions(+), 2 deletions(-) create mode 100644 lib/v2/xiaohongshu/notes.js diff --git a/docs/social-media.md b/docs/social-media.md index 79a98c0ff..e0c98f3d7 100644 --- a/docs/social-media.md +++ b/docs/social-media.md @@ -1600,7 +1600,11 @@ rule ### 用户笔记 - + + +::: tip 提示 +笔记全文不支持显示视频 +::: ### 用户收藏 diff --git a/lib/v2/xiaohongshu/maintainer.js b/lib/v2/xiaohongshu/maintainer.js index a06db40ce..45d764a86 100644 --- a/lib/v2/xiaohongshu/maintainer.js +++ b/lib/v2/xiaohongshu/maintainer.js @@ -1,5 +1,5 @@ module.exports = { '/board/:board_id': ['lotosbin'], '/user/:user_id/collect': ['lotosbin'], - '/user/:user_id/notes': ['lotosbin'], + '/user/:user_id/notes/:fulltext?': ['lotosbin', 'howerhe'], }; diff --git a/lib/v2/xiaohongshu/notes.js b/lib/v2/xiaohongshu/notes.js new file mode 100644 index 000000000..1ac7c8071 --- /dev/null +++ b/lib/v2/xiaohongshu/notes.js @@ -0,0 +1,16 @@ +const { getNotes, formatText, formatNote } = require('./util'); + +module.exports = async (ctx) => { + const userId = ctx.params.user_id; + const url = `https://www.xiaohongshu.com/user/profile/${userId}`; + + const { user, notes } = await getNotes(url, ctx.cache); + + ctx.state.data = { + title: `${user.nickname} - 笔记 • 小红书 / RED`, + description: formatText(user.desc), + image: user.imageb || user.images, + link: url, + item: notes.map((item) => formatNote(url, item)), + }; +}; diff --git a/lib/v2/xiaohongshu/router.js b/lib/v2/xiaohongshu/router.js index 9c829b57a..c0a8a3ce8 100644 --- a/lib/v2/xiaohongshu/router.js +++ b/lib/v2/xiaohongshu/router.js @@ -1,4 +1,5 @@ module.exports = (router) => { router.get('/board/:board_id', require('./board')); + router.get('/user/:user_id/notes/fulltext', require('./notes')); router.get('/user/:user_id/:category', require('./user')); }; diff --git a/lib/v2/xiaohongshu/util.js b/lib/v2/xiaohongshu/util.js index 798b31058..8ebf8dd6d 100644 --- a/lib/v2/xiaohongshu/util.js +++ b/lib/v2/xiaohongshu/util.js @@ -1,5 +1,6 @@ const config = require('@/config').value; const logger = require('@/utils/logger'); +const { parseDate } = require('@/utils/parse-date'); const getUser = (url, cache) => cache.tryGet( @@ -68,7 +69,131 @@ const getBoard = (url, cache) => false ); +const getNotes = (url, cache) => + cache.tryGet( + url + '/notes', // To avoid mixing with the cache for `user.js` + async () => { + let user = ''; + let notes = []; + + const setPageFilter = async (page) => { + await page.setRequestInterception(true); + page.on('request', (req) => { + req.resourceType() === 'document' || req.resourceType() === 'script' || req.resourceType() === 'xhr' || req.resourceType() === 'other' ? req.continue() : req.abort(); + }); + }; + + const browser = await require('@/utils/puppeteer')({ stealth: true }); + try { + const page = await browser.newPage(); + await setPageFilter(page); + + logger.debug(`Requesting ${url}`); + await page.goto(url); + + let otherInfo = {}; + let userPosted = {}; + try { + [otherInfo, userPosted] = await Promise.all( + ['/api/sns/web/v1/user/otherinfo', '/api/sns/web/v1/user_posted'].map((p) => + page + .waitForResponse((res) => { + const req = res.request(); + return req.url().includes(p) && req.method() === 'GET'; + }) + .then((r) => r.json()) + ) + ); + } catch (e) { + throw Error(`Could not get user information and note list\n${e}`); + } + + await page.close(); + + // Get full text for each note + const notesPromise = userPosted.data.notes.map((n) => { + const noteUrl = url + '/' + n.note_id; + + return cache.tryGet( + noteUrl, + async () => { + const notePage = await browser.newPage(); + await setPageFilter(notePage); + + logger.debug(`Requesting ${noteUrl}`); + await notePage.goto(noteUrl); + + let feed = {}; + try { + feed = await notePage.evaluate(() => window.__INITIAL_STATE__); + + // Sometimes the page is not server-side rendered + if (typeof feed?.note?.note === 'undefined' || JSON.stringify(feed?.note?.note) === '{}') { + const res = await notePage.waitForResponse((res) => { + const req = res.request(); + return req.url().includes('/api/sns/web/v1/feed') && req.method() === 'POST'; + }); + + const json = await res.json(); + const note_card = json.data.items[0].note_card; + feed.note.note = { + title: note_card.title, + noteId: note_card.id, + desc: note_card.desc, + tagList: note_card.tag_list, + imageList: note_card.image_list, + user: note_card.user, + time: note_card.time, + lastUpdateTime: note_card.last_update_time, + }; + } + } catch (e) { + throw Error(`Could not get note ${n.note_id}\n${e}`); + } + + await notePage.close(); + + if (typeof feed?.note?.note !== 'undefined' && JSON.stringify(feed?.note?.note) !== '{}') { + return feed.note.note; + } else { + throw Error(`Could not get note ${n.note_id}`); + } + } + ); + }); + + user = otherInfo.data.basic_info; + notes = await Promise.all(notesPromise); + } finally { + await browser.close(); + } + + return { user, notes }; + }, + config.cache.routeExpire, + false + ); + +const formatText = (text) => text.replace(/(\r\n|\r|\n)/g, '
').replace(/\t/g, ' '); + +// tag_list.id has nothing to do with its url +const formatTagList = (tagList) => tagList.reduce((acc, item) => acc + `#${item.name} `, ``); + +const formatImageList = (imageList) => imageList.reduce((acc, item) => acc + `
`, ``); + +const formatNote = (url, note) => ({ + title: note.title, + link: url + '/' + note.noteId, + description: formatText(note.desc) + '

' + formatTagList(note.tagList) + '

' + formatImageList(note.imageList), + author: note.user.nickname, + pubDate: parseDate(note.time, 'x'), + updated: parseDate(note.lastUpdateTime, 'x'), +}); + module.exports = { getUser, getBoard, + getNotes, + formatText, + formatNote, };