webshot.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. import { createWriteStream } from 'fs';
  2. import { Readable, Stream } from 'stream';
  3. import { promisify } from 'util';
  4. import axios from 'axios';
  5. import * as CallableInstance from 'callable-instance';
  6. import { XmlEntities } from 'html-entities';
  7. import { PNG } from 'pngjs';
  8. import * as puppeteer from 'playwright';
  9. import * as sharp from 'sharp';
  10. import * as temp from 'temp';
  11. import { getLogger } from './loggers';
  12. import { Message } from './koishi';
  13. import { MediaEntity, Tweets } from './twitter';
  14. import { chainPromises } from './utils';
  15. const xmlEntities = new XmlEntities();
  16. const ZHType = (type: string) => new class extends String {
  17. public type = super.toString();
  18. public toString = () => `[${super.toString()}]`;
  19. }(type);
  20. const typeInZH = {
  21. photo: ZHType('图片'),
  22. video: ZHType('视频'),
  23. animated_gif: ZHType('GIF'),
  24. };
  25. const logger = getLogger('webshot');
  26. class Webshot extends CallableInstance<[Tweets, (...args) => void, number], Promise<void>> {
  27. private browser: puppeteer.Browser;
  28. private mode: number;
  29. private wsUrl: string;
  30. constructor(wsUrl: string, mode: number, onready?: (...args) => void) {
  31. super('webshot');
  32. // tslint:disable-next-line: no-conditional-assignment
  33. // eslint-disable-next-line no-cond-assign
  34. if (this.mode = mode) {
  35. onready();
  36. } else {
  37. this.wsUrl = wsUrl;
  38. this.connect(onready);
  39. }
  40. }
  41. private connect = (onready?: (...args) => void): Promise<void> =>
  42. axios.get<{[key in 'chromium' | 'firefox' | 'webkit']?: string}>(this.wsUrl)
  43. .then(res => {
  44. logger.info(`received websocket endpoint: ${JSON.stringify(res.data)}`);
  45. const browserType = Object.keys(res.data)[0] as keyof typeof res.data;
  46. return (puppeteer[browserType] as puppeteer.BrowserType<puppeteer.Browser>)
  47. .connect({wsEndpoint: res.data[browserType]});
  48. })
  49. .then(browser => this.browser = browser)
  50. .then(() => {
  51. logger.info('launched puppeteer browser');
  52. if (onready) return onready();
  53. })
  54. .catch(error => this.reconnect(error, onready));
  55. private reconnect = (error, onready?: (...args) => void) => {
  56. logger.error(`connection error, reason: ${error}`);
  57. logger.warn('trying to reconnect in 2.5s...');
  58. return promisify(setTimeout)(2500)
  59. .then(() => this.connect(onready));
  60. };
  61. private extendEntity = (media: MediaEntity) => {
  62. logger.info('not working on a tweet');
  63. };
  64. private renderWebshot = (url: string, height: number, webshotDelay: number): Promise<string> => {
  65. temp.track();
  66. const jpeg = (data: Readable) => data.pipe(sharp()).jpeg({quality: 90, trellisQuantisation: true});
  67. const sharpToFile = (pic: sharp.Sharp) => new Promise<string>(resolve => {
  68. const webshotTempFilePath = temp.path({suffix: '.jpg'});
  69. pic.toFile(webshotTempFilePath).then(() => resolve(`file://${webshotTempFilePath}`));
  70. });
  71. const promise = new Promise<{ path: string, boundary: null | number }>((resolve, reject) => {
  72. const width = 720;
  73. const zoomFactor = 2;
  74. logger.info(`shooting ${width}*${height} webshot for ${url}`);
  75. this.browser.newPage({
  76. bypassCSP: true,
  77. deviceScaleFactor: zoomFactor,
  78. locale: 'ja-JP',
  79. timezoneId: 'Asia/Tokyo',
  80. userAgent: 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
  81. })
  82. .then(page => {
  83. const startTime = new Date().getTime();
  84. const getTimerTime = () => new Date().getTime() - startTime;
  85. const getTimeout = () => Math.max(500, webshotDelay - getTimerTime());
  86. page.setViewportSize({
  87. width: width / zoomFactor,
  88. height: height / zoomFactor,
  89. })
  90. .then(() => page.goto(url, {waitUntil: 'load', timeout: getTimeout()}))
  91. // hide header, "more options" button, like and retweet count
  92. .then(() => page.addStyleTag({
  93. content: 'header{display:none!important}path[d=\'M20.207 7.043a1 1 0 0 0-1.414 0L12 13.836 5.207 7.043a1 1 0 0 0-1.414 1.414l7.5 7.5a.996.996 0 0 0 1.414 0l7.5-7.5a1 1 0 0 0 0-1.414z\'],div[role=\'button\']{display: none;}',
  94. }))
  95. .then(() => page.addStyleTag({
  96. content: '*{font-family:-apple-system,".Helvetica Neue DeskInterface",Hiragino Sans,Hiragino Sans GB,sans-serif!important}',
  97. }))
  98. // remove listeners
  99. .then(() => page.evaluate(() => {
  100. const poll = setInterval(() => {
  101. document.querySelectorAll('div[data-testid="placementTracking"]').forEach(container => {
  102. if (container) {
  103. container.innerHTML = container.innerHTML;
  104. clearInterval(poll);
  105. }
  106. });
  107. }, 250);
  108. }))
  109. .then(() => page.waitForSelector('article', {timeout: getTimeout()}))
  110. .catch((err: Error): Promise<puppeteer.ElementHandle<Element> | null> => {
  111. if (err.name !== 'TimeoutError') throw err;
  112. logger.warn(`navigation timed out at ${getTimerTime()} seconds`);
  113. return null;
  114. })
  115. .then(handle => {
  116. if (handle === null) throw new puppeteer.errors.TimeoutError();
  117. })
  118. .then(() => page.evaluate(() => {
  119. const cardImg = document.querySelector('div[data-testid^="card.layout"][data-testid$=".media"] img');
  120. if (typeof cardImg?.getAttribute('src') === 'string') {
  121. const match = /^(.*\/card_img\/(\d+)\/.+\?format=.*)&name=/.exec(cardImg?.getAttribute('src'));
  122. if (match) {
  123. // tslint:disable-next-line: variable-name
  124. const [media_url_https, id_str] = match.slice(1);
  125. return {
  126. media_url: media_url_https.replace(/^https/, 'http'),
  127. media_url_https,
  128. url: '',
  129. display_url: '',
  130. expanded_url: '',
  131. type: 'photo',
  132. id: Number(id_str),
  133. id_str,
  134. sizes: undefined,
  135. };
  136. }
  137. }
  138. }))
  139. .then(cardImg => {
  140. if (cardImg) this.extendEntity(cardImg);
  141. })
  142. .then(() => page.addScriptTag({
  143. content: 'document.documentElement.scrollTop=0;',
  144. }))
  145. .then(() => promisify(setTimeout)(getTimeout()))
  146. .then(() => page.screenshot())
  147. .then(screenshot => {
  148. new PNG({
  149. filterType: 4,
  150. deflateLevel: 0,
  151. }).on('parsed', function () {
  152. // remove comment area
  153. // tslint:disable-next-line: no-shadowed-variable
  154. // eslint-disable-next-line @typescript-eslint/no-shadow
  155. const idx = (x: number, y: number) => (this.width * y + x) << 2;
  156. let boundary: number = null;
  157. let x = zoomFactor * 2;
  158. for (let y = 0; y < this.height; y += zoomFactor) {
  159. if (
  160. this.data[idx(x, y)] !== 255 &&
  161. this.data[idx(x, y)] === this.data[idx(x + zoomFactor * 10, y)]
  162. ) {
  163. if (this.data[idx(x, y + 18 * zoomFactor)] !== 255) {
  164. // footer kicks in
  165. boundary = null;
  166. } else {
  167. boundary = y;
  168. }
  169. break;
  170. }
  171. }
  172. if (boundary !== null) {
  173. logger.info(`found boundary at ${boundary}, cropping image`);
  174. this.data = this.data.slice(0, idx(this.width, boundary));
  175. this.height = boundary;
  176. boundary = null;
  177. x = Math.floor(16 * zoomFactor);
  178. let flag = false;
  179. let cnt = 0;
  180. for (let y = this.height - 1 - zoomFactor; y >= 0; y -= zoomFactor) {
  181. if ((this.data[idx(x, y)] === 255) === flag) {
  182. cnt++;
  183. flag = !flag;
  184. } else continue;
  185. // line above the "comment", "retweet", "like", "share" button row
  186. if (cnt === 2) {
  187. boundary = y + 1;
  188. }
  189. // if there are a "retweet" count and "like" count row, this will be the line above it
  190. if (cnt === 4) {
  191. const b = y + 1;
  192. if (Math.abs(this.height - boundary - (boundary - b)) <= 3 * zoomFactor) {
  193. boundary = b;
  194. }
  195. }
  196. // if "retweet" count and "like" count are two rows, this will be the line above the first
  197. if (cnt === 6) {
  198. const c = y + 1;
  199. if (Math.abs(this.height - boundary - 2 * (boundary - c)) <= 3 * zoomFactor) {
  200. boundary = c;
  201. break;
  202. }
  203. }
  204. }
  205. if (boundary !== null) {
  206. logger.info(`found boundary at ${boundary}, trimming image`);
  207. this.data = this.data.slice(0, idx(this.width, boundary));
  208. this.height = boundary;
  209. }
  210. sharpToFile(jpeg(this.pack())).then(path => {
  211. logger.info(`finished webshot for ${url}`);
  212. resolve({path, boundary});
  213. });
  214. } else if (height >= 8 * 1920) {
  215. logger.warn('too large, consider as a bug, returning');
  216. sharpToFile(jpeg(this.pack())).then(path => {
  217. resolve({path, boundary: 0});
  218. });
  219. } else {
  220. logger.info('unable to find boundary, try shooting a larger image');
  221. resolve({path: '', boundary});
  222. }
  223. }).parse(screenshot);
  224. })
  225. .catch(err => {
  226. if (err instanceof Error && err.name !== 'TimeoutError') throw err;
  227. logger.error(`error shooting webshot for ${url}, could not load web page of tweet`);
  228. resolve({path: '', boundary: 0});
  229. })
  230. .finally(() => { page.close(); });
  231. })
  232. .catch(reject);
  233. });
  234. return promise.then(data => {
  235. if (data.boundary === null) return this.renderWebshot(url, height + 1920, webshotDelay);
  236. else return data.path;
  237. }).catch(error => this.reconnect(error)
  238. .then(() => this.renderWebshot(url, height, webshotDelay))
  239. );
  240. };
  241. private fetchMedia = (url: string): Promise<string> => new Promise<Stream>((resolve, reject) => {
  242. logger.info(`fetching ${url}`);
  243. axios({
  244. method: 'get',
  245. url,
  246. responseType: 'stream',
  247. timeout: 150000,
  248. }).then(res => {
  249. if (res.status === 200) {
  250. logger.info(`successfully fetched ${url}`);
  251. resolve(res.data);
  252. } else {
  253. logger.error(`failed to fetch ${url}: ${res.status}`);
  254. reject();
  255. }
  256. }).catch (err => {
  257. logger.error(`failed to fetch ${url}: ${err instanceof Error ? err.message : err}`);
  258. reject();
  259. });
  260. }).then(data =>
  261. (ext => {
  262. const mediaTempFilePath = temp.path({suffix: ext});
  263. data.pipe(createWriteStream(mediaTempFilePath));
  264. const path = `file://${mediaTempFilePath}`;
  265. switch (ext) {
  266. case 'jpg':
  267. case 'png':
  268. return Message.Image(path);
  269. case 'mp4':
  270. return Message.Video(path);
  271. }
  272. logger.warn('unable to find MIME type of fetched media, failing this fetch');
  273. throw Error();
  274. })(((/\?format=([a-z]+)&/.exec(url)) ?? (/.*\/.*\.([^?]+)/.exec(url)))[1])
  275. );
  276. public webshot(
  277. tweets: Tweets,
  278. callback: (msgs: string, text: string, author: string) => void,
  279. webshotDelay: number
  280. ): Promise<void> {
  281. let promise = new Promise<void>(resolve => {
  282. resolve();
  283. });
  284. tweets.forEach(twi => {
  285. promise = promise.then(() => {
  286. logger.info(`working on ${twi.user.screen_name}/${twi.id_str}`);
  287. });
  288. const originTwi = twi.retweeted_status || twi;
  289. let messageChain = '';
  290. // text processing
  291. let author = `${twi.user.name} (@${twi.user.screen_name}):\n`;
  292. if (twi.retweeted_status) author += `RT @${twi.retweeted_status.user.screen_name}: `;
  293. let text = originTwi.full_text;
  294. promise = promise.then(() => {
  295. if (originTwi.entities && originTwi.entities.urls && originTwi.entities.urls.length) {
  296. originTwi.entities.urls.forEach(url => {
  297. text = text.replace(new RegExp(url.url, 'gm'), url.expanded_url);
  298. });
  299. }
  300. if (originTwi.extended_entities) {
  301. originTwi.extended_entities.media.forEach(media => {
  302. text = text.replace(new RegExp(media.url, 'gm'), this.mode === 1 ? typeInZH[media.type] : '');
  303. });
  304. }
  305. if (this.mode > 0) messageChain += (author + xmlEntities.decode(text));
  306. });
  307. // invoke webshot
  308. if (this.mode === 0) {
  309. const url = `https://mobile.twitter.com/${twi.user.screen_name}/status/${twi.id_str}`;
  310. this.extendEntity = (cardImg: MediaEntity) => {
  311. originTwi.extended_entities = {
  312. ...originTwi.extended_entities,
  313. media: [
  314. ...originTwi.extended_entities?.media ?? [],
  315. cardImg,
  316. ],
  317. };
  318. };
  319. promise = promise.then(() => this.renderWebshot(url, 1920, webshotDelay))
  320. .then(fileurl => {
  321. if (fileurl) return Message.Image(fileurl);
  322. return author + text;
  323. })
  324. .then(msg => {
  325. if (msg) messageChain += msg;
  326. });
  327. }
  328. // fetch extra entities
  329. // tslint:disable-next-line: curly
  330. // eslint-disable-next-line curly
  331. if (1 - this.mode % 2) promise = promise.then(() => {
  332. if (originTwi.extended_entities) {
  333. return chainPromises(originTwi.extended_entities.media.map(media => {
  334. let url: string;
  335. if (media.type === 'photo') {
  336. url = media.media_url_https.replace(/\.([a-z]+)$/, '?format=$1') + '&name=orig';
  337. } else {
  338. url = media.video_info.variants
  339. .filter(variant => variant.bitrate !== undefined)
  340. .sort((var1, var2) => var2.bitrate - var1.bitrate)
  341. .map(variant => variant.url)[0]; // largest video
  342. }
  343. const altMessage = `\n[失败的${typeInZH[media.type as keyof typeof typeInZH].type}:${url}]`;
  344. return this.fetchMedia(url)
  345. .catch(error => {
  346. logger.warn('unable to fetch media, sending plain text instead...');
  347. return altMessage;
  348. })
  349. .then(msg => { messageChain += msg; });
  350. }));
  351. }
  352. });
  353. // append URLs, if any
  354. if (this.mode === 0) {
  355. if (originTwi.entities && originTwi.entities.urls && originTwi.entities.urls.length) {
  356. promise = promise.then(() => {
  357. const urls = originTwi.entities.urls
  358. .filter(urlObj => urlObj.indices[0] < originTwi.display_text_range[1])
  359. .map(urlObj => `\n\ud83d\udd17 ${urlObj.expanded_url}`);
  360. if (urls.length) {
  361. messageChain += urls.join('');
  362. }
  363. });
  364. }
  365. }
  366. // refer to quoted tweet, if any
  367. if (originTwi.is_quote_status) {
  368. promise = promise.then(() => {
  369. messageChain += `\n回复此命令查看引用的推文:\n/twitter_view ${originTwi.quoted_status.id_str}`;
  370. });
  371. }
  372. promise.then(() => {
  373. logger.info(`done working on ${twi.user.screen_name}/${twi.id_str}, message chain:`);
  374. logger.info(JSON.stringify(Message.ellipseBase64(messageChain)));
  375. callback(messageChain, xmlEntities.decode(text), author);
  376. });
  377. });
  378. return promise;
  379. }
  380. }
  381. export default Webshot;