fix: twitter preview (#4545)

This commit is contained in:
Alex Yang 2023-09-30 01:19:54 -05:00 committed by GitHub
parent f59a35d8d2
commit 19646a97af
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -2,6 +2,7 @@ import { app, BrowserWindow, nativeTheme } from 'electron';
import { getLinkPreview } from 'link-preview-js'; import { getLinkPreview } from 'link-preview-js';
import { isMacOS } from '../../shared/utils'; import { isMacOS } from '../../shared/utils';
import { logger } from '../logger';
import type { NamespaceHandlers } from '../type'; import type { NamespaceHandlers } from '../type';
import { getGoogleOauthCode } from './google-auth'; import { getGoogleOauthCode } from './google-auth';
@ -45,29 +46,59 @@ export const uiHandlers = {
return getGoogleOauthCode(); return getGoogleOauthCode();
}, },
getBookmarkDataByLink: async (_, link: string) => { getBookmarkDataByLink: async (_, link: string) => {
const previewData = (await getLinkPreview(link, { if (
timeout: 6000, (link.startsWith('https://x.com/') ||
headers: { link.startsWith('https://www.x.com/') ||
'user-agent': 'googlebot', link.startsWith('https://www.twitter.com/') ||
}, link.startsWith('https://twitter.com/')) &&
followRedirects: 'follow', link.includes('/status/')
}).catch(() => { ) {
return { // use api.fxtwitter.com
title: '', link =
siteName: '', 'https://api.fxtwitter.com/status/' + /\/status\/(.*)/.exec(link)?.[1];
description: '', try {
images: [], const { tweet } = await fetch(link).then(res => res.json());
videos: [], return {
contentType: `text/html`, title: tweet.author.name,
favicons: [], icon: tweet.author.avatar_url,
}; description: tweet.text,
})) as any; image: tweet.media?.photos[0].url || tweet.author.banner_url,
};
} catch (err) {
logger.error('getBookmarkDataByLink', err);
return {
title: undefined,
description: undefined,
icon: undefined,
image: undefined,
};
}
} else {
const previewData = (await getLinkPreview(link, {
timeout: 6000,
headers: {
'User-Agent':
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36',
},
followRedirects: 'follow',
}).catch(() => {
return {
title: '',
siteName: '',
description: '',
images: [],
videos: [],
contentType: `text/html`,
favicons: [],
};
})) as any;
return { return {
title: previewData.title, title: previewData.title,
description: previewData.description, description: previewData.description,
icon: previewData.favicons[0], icon: previewData.favicons[0],
image: previewData.images[0], image: previewData.images[0],
}; };
}
}, },
} satisfies NamespaceHandlers; } satisfies NamespaceHandlers;