fix(route/picuki): stories and videos (#12757)

* fix(route/picuki): stories

Signed-off-by: Rongrong <i@rong.moe>

* fix(route/picuki): video

Signed-off-by: Rongrong <i@rong.moe>

---------

Signed-off-by: Rongrong <i@rong.moe>
This commit is contained in:
Rongrong
2023-07-08 00:38:55 +08:00
committed by GitHub
parent 4ecae47d2e
commit b6e1cf22ac
3 changed files with 106 additions and 119 deletions
+96 -116
View File
@@ -1,4 +1,3 @@
const got = require('@/utils/got');
const cheerio = require('cheerio');
const chrono = require('chrono-node');
const { art } = require('@/utils/render');
@@ -6,6 +5,19 @@ const path = require('path');
const config = require('@/config').value;
const { puppeteerGet } = require('./utils');
function deVideo(media) {
const $ = cheerio.load(media);
let media_deVideo = '';
$('img,video').each((_, medium) => {
const tag = medium.name;
medium = $(medium);
const poster = medium.attr('poster');
// 如果有 poster 属性,表明它是视频,将它替换为它的 poster;如果不是,就原样返回
media_deVideo += poster ? `<img src='${poster}' alt='video poster'>` : tag === 'img' ? medium.toString() : '';
});
return media_deVideo;
}
module.exports = async (ctx) => {
// use Puppeteer due to the obstacle by cloudflare challenge
const browser = await require('@/utils/puppeteer')();
@@ -17,9 +29,9 @@ module.exports = async (ctx) => {
const profileUrl = `https://www.picuki.com/profile/${id}`;
const data = await ctx.cache.tryGet(
profileUrl,
`picuki-${id}-profile-${includeStories}`,
async () => {
const _r = await puppeteerGet(profileUrl, browser);
const _r = await puppeteerGet(profileUrl, browser, includeStories);
return _r;
},
config.cache.routeExpire,
@@ -33,11 +45,53 @@ module.exports = async (ctx) => {
const list = $('ul.box-photos [data-s="media"]').get();
let items = [];
if (includeStories) {
const stories_wrapper = $('.stories_wrapper');
if (stories_wrapper.length) {
const storyItems = $(stories_wrapper)
.find('.item')
.get()
.map((item) => {
const $item = $(item);
let title = $item.find('.stories_count');
title = title.length ? title.text() : '';
const pubDate = title ? chrono.parseDate(title) : new Date();
const postBox = $item.find('.launchLightbox');
const poster = postBox.attr('data-video-poster');
const href = postBox.attr('href');
const type = postBox.attr('data-post-type'); // video / image
const origin = postBox.attr('data-origin');
const storiesBackground = $item.find('.stories_background');
const storiesBackgroundUrl = storiesBackground && storiesBackground.css('background-image').match(/url\('?(.*)'?\)/);
const storiesBackgroundUrlSrc = storiesBackgroundUrl && storiesBackgroundUrl[1];
let description;
if (type === 'video') {
description = art(path.join(__dirname, 'templates/video.art'), {
videoSrcs: [href, origin].filter(Boolean),
videoPoster: poster || storiesBackgroundUrlSrc || '',
});
} else if (type === 'image') {
description = `<img src="${href || poster || storiesBackgroundUrlSrc || ''}" alt="Instagram Story">`;
}
return {
title: 'Instagram Story' + (pubDate ? '' : `: ${title}`),
author: `@${id}`,
description,
link: href,
pubDate,
};
});
if (storyItems.length) {
items = storyItems;
}
}
}
async function getMedia(url) {
const getPost = async () => {
const response = await puppeteerGet(url, browser);
return response;
};
const getPost = () => puppeteerGet(url, browser);
let data = await ctx.cache.tryGet(url, getPost);
if (Object.prototype.toString.call(data) === '[object Object]') {
// oops, it's a json, maybe it's an old cache from the old version of this route!
@@ -58,125 +112,51 @@ module.exports = async (ctx) => {
videoSrc = item.children().attr('src');
}
const videoPoster = item.attr('poster');
let origin = item.parent().attr('onclick');
if (origin) {
origin = origin.match(/window\.open\('([^']*)'/);
origin = origin && origin[1];
}
html += art(path.join(__dirname, 'templates/video.art'), {
videoSrc,
videoSrcs: [videoSrc, origin].filter(Boolean),
videoPoster,
});
});
return html;
}
function deVideo(media) {
const $ = cheerio.load(media);
let media_deVideo = '';
$('img,video').each((_, medium) => {
const tag = medium.name;
medium = $(medium);
const poster = medium.attr('poster');
// 如果有 poster 属性,表明它是视频,将它替换为它的 poster;如果不是,就原样返回
media_deVideo += poster ? `<img src='${poster}' alt='video poster'>` : tag === 'img' ? medium.toString() : '';
});
return media_deVideo;
}
items = items.concat(
await Promise.all(
list.map(async (post) => {
post = $(post);
let items = await Promise.all(
list.map(async (post) => {
post = $(post);
const postLink = post.find('.photo > a').attr('href');
const postTime = post.find('.time');
const pubDate = postTime ? chrono.parseDate(postTime.text()) : new Date();
const media_displayVideo = await getMedia(postLink);
const postText = post
.find('.photo-description')
.text()
.trim()
.replace(/[^\S\n]+/g, ' ')
.replace(/((?<=\n|^)[^\S\n])|([^\S\n](?=\n|$))/g, '');
const title = postText.replace(/\n/g, ' ') || 'Untitled';
const description = art(path.join(__dirname, 'templates/post.art'), {
media: displayVideo ? media_displayVideo : deVideo(media_displayVideo),
desc: postText,
locationLink: post.find('.photo-location .icon-globe-alt a'),
});
return {
title,
author: `@${id}`,
description,
link: postLink,
pubDate,
};
})
);
const getStories = async (queryId) => {
const apiUrl = `https://www.picuki.com/app/controllers/ajax.php`;
const key = `${apiUrl}?query=${queryId}&type=story`;
const data = await ctx.cache.tryGet(key, async () => {
const response = await got.post(apiUrl, {
form: {
query: queryId,
type: 'story',
},
headers: {
Referer: profileUrl,
Origin: 'https://www.picuki.com',
'X-Requested-With': 'XMLHttpRequest',
},
});
return response.data;
});
if (data && data.stories_container) {
const $ = cheerio.load(data.stories_container);
const storyItems = $('.item')
.get()
.map((item) => {
const $item = $(item);
const postTime = $item.find('.stories_count');
const pubDate = postTime.length ? chrono.parseDate(postTime.text()) : new Date();
const postBox = $item.find('.launchLightbox');
const poster = postBox.attr('data-video-poster');
const href = postBox.attr('href');
const type = postBox.attr('data-post-type'); // video / image
const storiesBackground = $item.find('.stories_background');
const storiesBackgroundUrl = storiesBackground && storiesBackground.css('background-image').match(/url\('?(.*)'?\)/);
const storiesBackgroundUrlSrc = storiesBackgroundUrl && storiesBackgroundUrl[1];
let description;
if (type === 'video') {
description = `<video controls src="${href}" poster="${poster || storiesBackgroundUrlSrc || ''}">`;
} else if (type === 'image') {
description = `<img src="${href || poster || storiesBackgroundUrlSrc || ''}" alt="Instagram Story">`;
}
return {
title: 'Instagram Story',
author: `@${id}`,
description,
link: href,
pubDate,
};
const postLink = post.find('.photo > a').attr('href');
const postTime = post.find('.time');
const pubDate = postTime ? chrono.parseDate(postTime.text()) : new Date();
const media_displayVideo = await getMedia(postLink);
const postText = post
.find('.photo-description')
.text()
.trim()
.replace(/[^\S\n]+/g, ' ')
.replace(/((?<=\n|^)[^\S\n])|([^\S\n](?=\n|$))/g, '');
const title = postText.replace(/\n/g, ' ') || 'Untitled';
const description = art(path.join(__dirname, 'templates/post.art'), {
media: displayVideo ? media_displayVideo : deVideo(media_displayVideo),
desc: postText,
locationLink: post.find('.photo-location .icon-globe-alt a'),
});
if (storyItems.length) {
items = items.concat(storyItems);
}
}
};
if (includeStories) {
let profileQueryId;
$('script:not([src])').each((_, script) => {
const queryMatch = $(script)
.html()
.match(/let query ?= ?['"](\d+)['"]/);
if (queryMatch) {
profileQueryId = queryMatch[1];
}
});
if (profileQueryId) {
await getStories(profileQueryId);
}
}
return {
title,
author: `@${id}`,
description,
link: postLink,
pubDate,
};
})
)
);
await browser.close();
+3 -1
View File
@@ -1,3 +1,5 @@
<video poster="{{ videoPoster }}" controls>
<source src="{{ videoSrc }}" type="video/mp4">
<% for (let src of videoSrcs) { %>
<source src="{{ src }}" type="video/mp4">
<% } %>
</video>
+7 -2
View File
@@ -1,15 +1,20 @@
const puppeteerGet = async (url, browser) => {
const puppeteerGet = async (url, browser, includeStories = false) => {
const page = await browser.newPage();
const expectResourceTypes = includeStories ? ['document', 'script', 'xhr'] : ['document'];
// await page.setExtraHTTPHeaders({ referer: host });
await page.setRequestInterception(true);
page.on('request', (request) => {
request.resourceType() === 'document' ? request.continue() : request.abort();
expectResourceTypes.includes(request.resourceType()) ? request.continue() : request.abort();
});
await page.goto(url, {
waitUntil: 'domcontentloaded',
});
await page.waitForSelector('.wrapper');
if (includeStories) {
await page.$eval('.show_stories_button', (btn) => btn.click());
await page.waitForSelector('.stories_container .content');
}
const html = await page.evaluate(() => document.documentElement.innerHTML);
await page.close();