const got = require('@/utils/got');
const config = require('@/config').value;
module.exports = async (ctx) => {
const uid = ctx.params.uid;
const feature = ctx.params.feature || 0;
const token = await ctx.cache.get('weibotimelineuid' + uid, false);
if (token) {
const response = await got.get(`https://api.weibo.com/2/statuses/home_timeline.json?access_token=${token}&count=100&feature=${feature}`);
// 检查token失效
if (response.data.error !== undefined) {
const { app_key = '', redirect_url = ctx.request.origin + '/weibo/timeline/0' } = config.weibo;
ctx.status = 302;
ctx.set({
'Cache-Control': 'no-cache',
});
ctx.redirect(`https://api.weibo.com/oauth2/authorize?client_id=${app_key}&redirect_uri=${redirect_url}`);
}
// 获取所有表情
const weiboEmotion = await ctx.cache.tryGet('weiboEmotion', async () => {
const tmpEmotionList = {};
await Promise.all(
['face', 'ani', 'cartoon'].map(async (type) => {
try {
const rep = await got.get(`https://api.weibo.com/2/emotions.json?access_token=${token}&type=${type}`);
rep.data.forEach(function(item) {
tmpEmotionList[item.phrase] = item.url;
});
return Promise.resolve(rep);
} catch (err) {
// pass
}
})
);
return tmpEmotionList;
});
const data = await Promise.all(
response.data.statuses.map(async (item) => {
const realContent = await ctx.cache.tryGet('weibotimelineurl' + item.user.id + item.id, async () => {
const res = [];
const videoList = [];
let picUrlList = [];
picUrlList = picUrlList.concat(item.pic_urls);
try {
const rep = await got.get(`https://m.weibo.cn/${item.user.id}/${item.id}`);
rep.body.replace(/"text": "([\s\S]*?)",/g, function(s, value) {
res.push(value.replace(/\\"/g, "'"));
});
rep.body.replace(/"mp4_720p_mp4": "([\s\S]*?)",/, function(s, value) {
videoList.push(value);
});
if (res.length > 1) {
const sub_rep = await got.get(`https://m.weibo.cn/${item.retweeted_status.user.id}/${item.retweeted_status.id}`);
sub_rep.body.replace(/"text": "([\s\S]*?)",/g, function(s, value) {
res[1] = value.replace(/\\"/g, "'");
});
sub_rep.body.replace(/"mp4_720p_mp4": "([\s\S]*?)",/, function(s, value) {
videoList.push(value);
});
picUrlList = picUrlList.concat(item.retweeted_status.pic_urls);
}
} catch (err) {
res.push(item.text);
if (item.retweeted_status) {
res.push(item.retweeted_status.text);
picUrlList = picUrlList.concat(item.retweeted_status.pic_urls);
}
// 非全文获取的微博内容需要替换表情
res.forEach(function(content, index) {
const emotion = [];
content.replace(/(\[.*?\])/g, function(s, value) {
emotion.push(`${value}`);
});
if (content.length > 0) {
emotion.forEach(function(item) {
res[index] = content.replace(new RegExp(`\\${item}`, 'g'), ``);
});
}
});
}
let content = '';
try {
if (res.length >= 2) {
content = `${res[0]}