format.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. import { Tweet } from './twitter.ts';
  2. class SafeString {
  3. constructor(readonly raw: string) {}
  4. get length(): number {
  5. return this.raw.length;
  6. }
  7. toString(): string {
  8. return this.raw;
  9. }
  10. toJSON(): string {
  11. return this.raw;
  12. }
  13. }
  14. type StringLike = string | SafeString;
  15. function escapeHTML(unsafe: string): StringLike {
  16. return new SafeString(
  17. unsafe
  18. .replace(/&/g, "&")
  19. .replace(/</g, "&lt;")
  20. .replace(/>/g, "&gt;")
  21. .replace(/"/g, "&quot;")
  22. .replace(/'/g, "&#039;")
  23. );
  24. }
  25. function joinChildren(children: StringLike[]): SafeString {
  26. return new SafeString(children
  27. .map(child => typeof child === 'string' ? escapeHTML(child) : child)
  28. .join('')
  29. );
  30. }
  31. function tag(tag: string, attributes: Record<string, string> = {}, children: StringLike | StringLike[] = []): SafeString {
  32. const attrs = Object.entries(attributes).map(([ key, value ]) => {
  33. return ` ${key}="${escapeHTML(value)}"`;
  34. }).join('');
  35. if (children.length === 0) {
  36. return new SafeString(`<${tag}${attrs} />`);
  37. } else {
  38. const childrenArray = Array.isArray(children) ? children : [children];
  39. const normalizedChildren = joinChildren(childrenArray);
  40. return new SafeString(`<${tag}${attrs}>${normalizedChildren}</${tag}>`);
  41. }
  42. }
  43. function buildTwitterUrl(url: string): string {
  44. return new URL(url, 'https://twitter.com').toString();
  45. }
  46. function buildProxyUrl(url: string): string {
  47. const search = new URLSearchParams({ target: url }).toString();
  48. return `/__proxy?${search}`;
  49. }
  50. function formatPlainText(text: string): SafeString {
  51. // apparently twitter already escapes the text for you
  52. return new SafeString(text.replace(/\n/g, "<br />"));
  53. }
  54. class TextFormatter {
  55. private splices: { text: StringLike, indices: [number, number] }[];
  56. private media: { type: 'video' | 'img', url: string, link?: string }[];
  57. private characters: string[];
  58. constructor(readonly tweet: Tweet, readonly useProxy: boolean) {
  59. this.characters = [...tweet.full_text];
  60. this.splices = [];
  61. this.media = [];
  62. for (const { indices, text } of tweet.entities.hashtags) {
  63. const url = buildTwitterUrl(`/hashtag/${text}`);
  64. this.splices.push({
  65. indices,
  66. text: tag('a', { href: url }, `#${text}`),
  67. });
  68. }
  69. for (const link of tweet.entities.urls) {
  70. const url = new URL(link.expanded_url).toString();
  71. this.splices.push({
  72. indices: link.indices,
  73. text: tag('a', { href: url }, link.display_url),
  74. });
  75. }
  76. for (const { indices, name, screen_name } of tweet.entities.user_mentions) {
  77. const url = buildTwitterUrl(`/${screen_name}`);
  78. this.splices.push({
  79. indices: indices,
  80. text: tag('a', { href: url, title: name }, `@${screen_name}`),
  81. });
  82. }
  83. const media = tweet.extended_entities?.media ?? [];
  84. for (const item of media) {
  85. if (item.type === 'photo') {
  86. const url = new URL(item.media_url_https).toString();
  87. this.media.push({ type: 'img', url });
  88. } else if (item.video_info !== undefined) {
  89. let max = -1;
  90. let maxUrl: string | undefined = undefined;
  91. for (const variant of item.video_info.variants) {
  92. if (variant.bitrate === undefined) {
  93. continue;
  94. }
  95. if (variant.bitrate > max) {
  96. max = variant.bitrate;
  97. maxUrl = variant.url;
  98. }
  99. }
  100. if (maxUrl !== undefined) {
  101. const url = new URL(maxUrl).toString();
  102. this.media.push({ type: 'video', url });
  103. } else {
  104. const url = new URL(item.media_url_https).toString();
  105. this.media.push({ type: 'img', url, link: item.expanded_url });
  106. }
  107. }
  108. }
  109. }
  110. getRange(start: number, end?: number): string {
  111. const max = this.tweet.display_text_range[1];
  112. return this.characters.slice(start, end ?? max).join('');
  113. }
  114. headerHTML(): SafeString {
  115. const date = new Date(this.tweet.created_at);
  116. const dateOptions = {
  117. weekday: 'short',
  118. year: 'numeric',
  119. month: '2-digit',
  120. day: '2-digit',
  121. hour: '2-digit',
  122. minute: '2-digit',
  123. timeZoneName: 'short',
  124. } as const;
  125. const imageUrl = new URL(this.tweet.user.profile_image_url_https).toString();
  126. const imageSrc = this.useProxy ? buildProxyUrl(imageUrl) : imageUrl;
  127. const profileUrl = buildTwitterUrl(`/${this.tweet.user.screen_name}`);
  128. const tweetUrl = buildTwitterUrl(`/${this.tweet.user.screen_name}/status/${this.tweet.id_str}`);
  129. const html = [
  130. tag('img', { loading: 'lazy', src: imageSrc, height: '24px', width: '24px' }),
  131. ' ',
  132. tag('strong', {}, this.tweet.user.name),
  133. ' ',
  134. tag('a', { href: profileUrl }, `@${this.tweet.user.screen_name}`),
  135. tag('br'),
  136. 'Posted ',
  137. tag('a', { href: tweetUrl }, date.toLocaleString(this.tweet.lang, dateOptions)),
  138. ];
  139. return joinChildren(html);
  140. }
  141. bodyHTML(): SafeString {
  142. const max = this.tweet.display_text_range[1];
  143. const splices = this.splices
  144. .filter(({ indices }) => indices[0] < max && indices[1] <= max)
  145. .sort((a, b) => a.indices[0] - b.indices[0]);
  146. let index = 0;
  147. const html: StringLike[] = [];
  148. for (const { text, indices } of splices) {
  149. const start = index;
  150. const end = indices[0];
  151. html.push(formatPlainText(this.getRange(start, end)));
  152. html.push(text);
  153. index = indices[1];
  154. }
  155. html.push(formatPlainText(this.getRange(index)));
  156. for (const { type, url, link } of this.media) {
  157. html.push(tag('br'));
  158. html.push(tag('br'));
  159. const src = this.useProxy ? buildProxyUrl(url) : url;
  160. if (type === 'img') {
  161. html.push(tag('a', { href: link ?? url }, [
  162. tag('img', { loading: 'lazy', src }),
  163. ]));
  164. } else if (type === 'video') {
  165. html.push(tag('video', { controls: '', src }));
  166. }
  167. }
  168. return joinChildren(html);
  169. }
  170. toHTML(): SafeString {
  171. return joinChildren([ this.headerHTML(), tag('br'), this.bodyHTML() ]);
  172. }
  173. }
  174. const STYLES = `
  175. body > div {
  176. margin: 10px;
  177. padding: 10px;
  178. border: solid 1px gray;
  179. border-radius: 10px;
  180. }
  181. blockquote {
  182. padding: 10px;
  183. border: solid 1px lightgray;
  184. border-radius: 10px;
  185. }
  186. div {
  187. max-width: 600px;
  188. }
  189. img {
  190. max-width: 100%;
  191. }
  192. `;
  193. export function timelineAsHTML(tweets: Tweet[]): string {
  194. const body = tweets.map(tweet => {
  195. const displayTweet = tweet.retweeted_status ?? tweet;
  196. const children: StringLike[] = [];
  197. children.push(new TextFormatter(displayTweet, true).toHTML());
  198. const quoteTweet = displayTweet.quoted_status;
  199. if (quoteTweet !== undefined) {
  200. children.push(tag('blockquote', {}, new TextFormatter(quoteTweet, true).toHTML()));
  201. }
  202. return tag('div', {}, children);
  203. }).join('\n');
  204. return `
  205. <html>
  206. <head>
  207. <style>${STYLES}</style>
  208. </head>
  209. <body>${body}</body>
  210. </html>
  211. `;
  212. }
  213. export function timelineAsJSON(username: string, tweets: Tweet[]): string {
  214. const items = tweets.map(tweet => {
  215. const displayTweet = tweet.retweeted_status ?? tweet;
  216. const children: StringLike[] = [];
  217. children.push(new TextFormatter(displayTweet, false).bodyHTML());
  218. const quoteTweet = displayTweet.quoted_status;
  219. if (quoteTweet !== undefined) {
  220. children.push(tag('blockquote', {}, [
  221. new TextFormatter(quoteTweet, false).toHTML(),
  222. ]));
  223. }
  224. const html = joinChildren(children);
  225. return {
  226. id: tweet.id_str,
  227. title: tweet.full_text.split('\n')[0],
  228. url: buildTwitterUrl(`/${tweet.user.screen_name}/status/${tweet.id_str}`),
  229. content_html: html,
  230. date_published: new Date(tweet.created_at).toISOString(),
  231. authors: [{
  232. name: `${displayTweet.user.name} - @${displayTweet.user.screen_name}`,
  233. url: buildTwitterUrl(`/${displayTweet.user.screen_name}`),
  234. avatar: displayTweet.user.profile_image_url_https,
  235. }],
  236. };
  237. });
  238. return JSON.stringify({
  239. version: '1.1',
  240. title: `Twitter @${username}`,
  241. home_page_url: buildTwitterUrl(`/${username}`),
  242. items,
  243. });
  244. }