webshot.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. const fs_1 = require("fs");
  4. const util_1 = require("util");
  5. const axios_1 = require("axios");
  6. const CallableInstance = require("callable-instance");
  7. const html_entities_1 = require("html-entities");
  8. const pngjs_1 = require("pngjs");
  9. const puppeteer = require("playwright");
  10. const sharp = require("sharp");
  11. const temp = require("temp");
  12. const loggers_1 = require("./loggers");
  13. const koishi_1 = require("./koishi");
  14. const utils_1 = require("./utils");
  15. const twitter_1 = require("./twitter");
  16. const xmlEntities = new html_entities_1.XmlEntities();
  17. const ZHType = (type) => new class extends String {
  18. constructor() {
  19. super(...arguments);
  20. this.type = super.toString();
  21. this.toString = () => `[${super.toString()}]`;
  22. }
  23. }(type);
  24. const typeInZH = {
  25. photo: ZHType('图片'),
  26. video: ZHType('视频'),
  27. };
  28. const logger = loggers_1.getLogger('webshot');
  29. class Webshot extends CallableInstance {
  30. constructor(wsUrl, mode, getCookies, onready) {
  31. super('webshot');
  32. this.connect = (onready) => axios_1.default.get(this.wsUrl)
  33. .then(res => {
  34. logger.info(`received websocket endpoint: ${JSON.stringify(res.data)}`);
  35. const browserType = Object.keys(res.data)[0];
  36. return puppeteer[browserType]
  37. .connect({ wsEndpoint: res.data[browserType] });
  38. })
  39. .then(browser => this.browser = browser)
  40. .then(() => {
  41. logger.info('launched puppeteer browser');
  42. if (onready)
  43. return onready();
  44. })
  45. .catch(error => this.reconnect(error, onready));
  46. this.reconnect = (error, onready) => {
  47. logger.error(`connection error, reason: ${error}`);
  48. logger.warn('trying to reconnect in 2.5s...');
  49. return util_1.promisify(setTimeout)(2500)
  50. .then(() => this.connect(onready));
  51. };
  52. this.performOnNewPage = (action, zoomFactor = 2, reconnectOnError = true) => this.browser.newPage({
  53. bypassCSP: true,
  54. deviceScaleFactor: zoomFactor,
  55. locale: 'ja-JP',
  56. timezoneId: 'Asia/Tokyo',
  57. userAgent: 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
  58. }).then(action)
  59. .catch(error => {
  60. if (reconnectOnError) {
  61. return this.reconnect(error)
  62. .then(() => this.performOnNewPage(action, zoomFactor, reconnectOnError));
  63. }
  64. throw error;
  65. });
  66. this.renderWebshot = (url, height, webshotDelay) => {
  67. temp.track();
  68. const jpeg = (data) => data.pipe(sharp()).jpeg({ quality: 90, trellisQuantisation: true });
  69. const sharpToFile = (pic) => new Promise(resolve => {
  70. const webshotTempFilePath = temp.path({ suffix: '.jpg' });
  71. pic.toFile(webshotTempFilePath).then(() => resolve(`file://${webshotTempFilePath}`));
  72. });
  73. const promise = new Promise((resolve, reject) => {
  74. const width = 720;
  75. const zoomFactor = 2;
  76. logger.info(`shooting ${width}*${height} webshot for ${url}`);
  77. this.performOnNewPage(page => {
  78. const startTime = new Date().getTime();
  79. const getTimerTime = () => new Date().getTime() - startTime;
  80. const getTimeout = () => Math.max(500, webshotDelay - getTimerTime());
  81. page.setViewportSize({
  82. width: width / zoomFactor,
  83. height: height / zoomFactor,
  84. }).then(() => page.context().addCookies(this.getCookies()))
  85. .then(() => page.goto(url, { waitUntil: 'load', timeout: getTimeout() }))
  86. .then(() => twitter_1.WebshotHelpers.handleCookieConsent(page))
  87. .then(() => ((next) => Promise.race([
  88. twitter_1.WebshotHelpers.handleLogin(page)
  89. .then(() => page.goto(url, { waitUntil: 'load', timeout: getTimeout() }))
  90. .then(next),
  91. next(),
  92. ]))(() => page.waitForSelector('article', { timeout: getTimeout() })))
  93. .catch((err) => {
  94. if (err.name !== 'TimeoutError')
  95. throw err;
  96. logger.warn(`navigation timed out at ${getTimerTime()} ms`);
  97. return null;
  98. })
  99. .then(() => page.addStyleTag({ content: 'nav,footer,header+div,header+div+div>div>div+div,header div div div+div,' +
  100. 'article section,article section+div>ul>:not(div),article button,canvas{display:none!important} ' +
  101. 'section+div{overflow:hidden} section+*>*{position:relative!important} article{border-bottom:1px solid!important}',
  102. }))
  103. .then(() => page.addStyleTag({
  104. content: '*{font-family:-apple-system,".Helvetica Neue DeskInterface",Hiragino Sans,Hiragino Sans GB,sans-serif!important}',
  105. }))
  106. .then(() => page.evaluate(() => {
  107. let time;
  108. time = document.querySelector('div>div>time');
  109. if (time)
  110. time.parentElement.parentElement.style.display = 'none';
  111. time = document.querySelector('article section~div>a>time');
  112. if (time) {
  113. time.innerHTML = time.title + ' ' + new Date(time.dateTime).toLocaleTimeString().slice(0, -3);
  114. time.parentElement.parentElement.style.margin = '-24px 0 12px';
  115. }
  116. }))
  117. .then(() => page.screenshot())
  118. .then(screenshot => {
  119. new pngjs_1.PNG({
  120. filterType: 4,
  121. deflateLevel: 0,
  122. }).on('parsed', function () {
  123. const idx = (x, y) => (this.width * y + x) << 2;
  124. let boundary = null;
  125. for (let y = this.height - 1; y > this.height - 1920; y -= zoomFactor) {
  126. if (this.data[idx(zoomFactor, y)] <= 38 &&
  127. this.data[idx(zoomFactor, y)] === this.data[idx(this.width - zoomFactor, y)] &&
  128. this.data[idx(zoomFactor, y + zoomFactor)] === this.data[idx(zoomFactor, y - 2 * zoomFactor)]) {
  129. boundary = y - 1;
  130. break;
  131. }
  132. }
  133. if (boundary !== null) {
  134. logger.info(`found boundary at ${boundary}, cropping image`);
  135. this.data = this.data.slice(0, idx(this.width, boundary));
  136. this.height = boundary;
  137. sharpToFile(jpeg(this.pack())).then(path => {
  138. logger.info(`finished webshot for ${url}`);
  139. resolve({ path, boundary });
  140. });
  141. }
  142. else if (height >= 8 * 1920) {
  143. logger.warn('too large, consider as a bug, returning');
  144. sharpToFile(jpeg(this.pack())).then(path => {
  145. resolve({ path, boundary: 0 });
  146. });
  147. }
  148. else {
  149. logger.info('unable to find boundary, try shooting a larger image');
  150. resolve({ path: '', boundary });
  151. }
  152. }).parse(screenshot);
  153. })
  154. .catch(err => {
  155. if (err instanceof Error && err.name !== 'TimeoutError')
  156. throw err;
  157. logger.error(`error shooting webshot for ${url}, could not load web page of tweet`);
  158. resolve({ path: '', boundary: 0 });
  159. })
  160. .finally(() => { page.close(); });
  161. }, zoomFactor, false)
  162. .catch(reject);
  163. });
  164. return promise.then(data => {
  165. if (data.boundary === null)
  166. return this.renderWebshot(url, height + 1920, webshotDelay);
  167. else
  168. return data.path;
  169. }).catch(error => this.reconnect(error)
  170. .then(() => this.renderWebshot(url, height, webshotDelay)));
  171. };
  172. this.fetchMedia = (url) => new Promise((resolve, reject) => {
  173. logger.info(`fetching ${url}`);
  174. axios_1.default({
  175. method: 'get',
  176. url,
  177. responseType: 'arraybuffer',
  178. timeout: 150000,
  179. }).then(res => {
  180. if (res.status === 200) {
  181. logger.info(`successfully fetched ${url}`);
  182. resolve(res.data);
  183. }
  184. else {
  185. logger.error(`failed to fetch ${url}: ${res.status}`);
  186. reject();
  187. }
  188. }).catch(err => {
  189. logger.error(`failed to fetch ${url}: ${err instanceof Error ? err.message : err}`);
  190. reject();
  191. });
  192. }).then(data => (ext => {
  193. const mediaTempFilePath = temp.path({ suffix: `.${ext}` });
  194. fs_1.writeFileSync(mediaTempFilePath, Buffer.from(data));
  195. const path = `file://${mediaTempFilePath}`;
  196. switch (ext) {
  197. case 'jpg':
  198. case 'png':
  199. return koishi_1.Message.Image(path);
  200. case 'mp4':
  201. return koishi_1.Message.Video(path);
  202. }
  203. logger.warn('unable to find MIME type of fetched media, failing this fetch');
  204. throw Error();
  205. })(/\/.*\.(.+?)\?/.exec(url)[1]));
  206. if (this.mode = mode) {
  207. onready();
  208. }
  209. else {
  210. this.getCookies = getCookies;
  211. this.wsUrl = wsUrl;
  212. this.connect(() => onready(this.performOnNewPage));
  213. }
  214. }
  215. webshot(lazyMediaItems, callback, webshotDelay) {
  216. let grandPromise = Promise.resolve();
  217. lazyMediaItems.forEach(lazyItem => grandPromise = grandPromise.then(lazyItem.item).then(item => {
  218. var _a;
  219. let promise = Promise.resolve();
  220. promise = promise.then(() => {
  221. logger.info(`working on ${item.user.username}/${item.code}`);
  222. });
  223. let messageChain = '';
  224. const author = `${item.user.full_name} (@${item.user.username}):\n`;
  225. const text = ((_a = item.caption) === null || _a === void 0 ? void 0 : _a.text) || '';
  226. if (this.mode > 0)
  227. messageChain += (author + xmlEntities.decode(text));
  228. if (this.mode === 0) {
  229. const url = twitter_1.linkBuilder({ postUrlSegment: item.code });
  230. promise = promise.then(() => this.renderWebshot(url, 1920, webshotDelay))
  231. .then(fileurl => {
  232. if (fileurl)
  233. return koishi_1.Message.Image(fileurl);
  234. return author + text;
  235. })
  236. .then(msg => {
  237. if (msg)
  238. messageChain += msg;
  239. });
  240. }
  241. const type = (mediaItem) => mediaItem.video_versions ? 'video' : 'photo';
  242. const fetchBestCandidate = (candidates, mediaType) => {
  243. const url = candidates
  244. .sort((var1, var2) => var2.width + ((var2 === null || var2 === void 0 ? void 0 : var2.type) || 0) - var1.width - ((var1 === null || var1 === void 0 ? void 0 : var1.type) || 0))
  245. .map(variant => variant.url)[0];
  246. const altMessage = `\n[失败的${typeInZH[mediaType].type}:${url}]`;
  247. return this.fetchMedia(url)
  248. .catch(error => {
  249. logger.warn('unable to fetch media, sending plain text instead...');
  250. return altMessage;
  251. })
  252. .then(msg => { messageChain += msg; });
  253. };
  254. if (1 - this.mode % 2)
  255. promise = promise.then(() => {
  256. if (item.carousel_media) {
  257. return utils_1.chainPromises(item.carousel_media.map(carouselItem => fetchBestCandidate(carouselItem.video_versions ||
  258. carouselItem.image_versions2.candidates, type(carouselItem))));
  259. }
  260. else if (item.video_versions) {
  261. return fetchBestCandidate(item.video_versions, type(item));
  262. }
  263. else if (item.image_versions2) {
  264. return fetchBestCandidate(item.image_versions2.candidates, type(item));
  265. }
  266. });
  267. promise.then(() => {
  268. logger.info(`done working on ${item.user.username}/${item.code}, message chain:`);
  269. logger.info(JSON.stringify(koishi_1.Message.ellipseBase64(messageChain)));
  270. callback(messageChain, xmlEntities.decode(text), author);
  271. });
  272. return promise;
  273. }));
  274. return grandPromise;
  275. }
  276. }
  277. exports.default = Webshot;