forked from silentroach/tweet.md
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
228 lines (179 loc) · 5.32 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
const { parse: parseUrl, format: formatUrl } = require("url");
const TwitterStatusIdRegexp = /\/status\/(\w+)$/;
const TwitterHost = "twitter.com";
const TwitterUrlParsed = parseUrl(`https://${TwitterHost}`);
const getTwitterUrl = (pathname, query) =>
formatUrl({ ...TwitterUrlParsed, pathname, query });
const getTwitterHashUrl = (query, source) => {
const parameters = { q: `#${query}` };
if (undefined !== source) {
parameters.src = source;
}
return getTwitterUrl("search", parameters);
};
const escapeMarkdownPart = input =>
[
// escaping symbols: # * ( ) [ ] _ `
[/([\#\*\(\)\[\]\_\`\\])/g, "\\$1"],
// escaping less and more signs
[/\</g, "<"],
[/\>/g, ">"],
// convert line break into markdown hardbrake
[/\n/g, " \n"]
].reduce(
(input, [replaceFrom, replaceTo]) => input.replace(replaceFrom, replaceTo),
input
);
const escapeMarkdown = input =>
escapeMarkdownPart(input)
// escaping period after number at the string start
.replace(/^(\d+)\./, "$1\\.");
const renderMarkdownLink = (name, url, title) => {
const parts = [url];
if (title) {
parts.push(`"${title}"`);
}
return `[${name}](${parts.join(" ")})`;
};
const renderMarkdownLinkName = (name, prefix) => {
const data = [escapeMarkdownPart(name)];
if (prefix) {
data.unshift(prefix);
}
return data.join("");
};
const renderEntityMedia = data =>
renderMarkdownLink(data.display_url, data.url);
const renderEntityMention = data =>
renderMarkdownLink(
renderMarkdownLinkName(data.screen_name, "@"),
getTwitterUrl(data.screen_name),
data.name
);
const renderEntityHashtag = data =>
renderMarkdownLink(
renderMarkdownLinkName(data.text, "#"),
getTwitterHashUrl(data.text)
);
const renderEntitySymbol = data =>
renderMarkdownLink(
renderMarkdownLinkName(data.text, "$"),
getTwitterHashUrl(data.text, "ctag")
);
const renderEntityUrl = data =>
renderMarkdownLink(
renderMarkdownLinkName(data.display_url),
data.url,
data.expanded_url
);
const renderEntity = (type, data) => {
if (data.skip) return;
switch (type) {
case "user_mentions":
return renderEntityMention(data);
case "media":
return renderEntityMedia(data);
case "hashtags":
return renderEntityHashtag(data);
case "urls":
return renderEntityUrl(data);
case "symbols":
return renderEntitySymbol(data);
default:
return null;
}
};
const unicodeCharAt = (string, index) => {
const first = string.charCodeAt(index);
if (first >= 0xd800 && first <= 0xdbff && string.length > index + 1) {
const second = string.charCodeAt(index + 1);
if (second >= 0xdc00 && second <= 0xdfff) {
return string.substring(index, index + 2);
}
}
return string[index];
};
const unicodeSlice = (string, start, end = string.length) => {
if (start == end) {
return "";
}
const accumulator = [];
let character;
let stringIndex = 0;
let unicodeIndex = 0;
const length = string.length;
while (stringIndex < length) {
character = unicodeCharAt(string, stringIndex);
if (unicodeIndex >= start && unicodeIndex < end) {
accumulator.push(character);
}
stringIndex += character.length;
unicodeIndex += 1;
}
return accumulator.join("");
};
const processText = (text, replacements) => {
let processed = text;
let lastPos = 0;
const parts = replacements
.sort((a, b) => a[1] - b[1])
.reduce((parts, repl) => {
const [replacement, start, end] = repl;
parts.push(
escapeMarkdownPart(unicodeSlice(text, lastPos, start)),
replacement
);
lastPos = end;
return parts;
}, []);
parts.push(escapeMarkdown(unicodeSlice(text, lastPos)));
return parts.join("");
};
const getStatusIdFromUrlEntity = entity => {
const { expanded_url: url } = entity;
if (!url) return;
const parsed = parseUrl(url);
if (!parsed || TwitterHost !== parsed.hostname) return;
const statusMatch = parsed.path.match(TwitterStatusIdRegexp);
return statusMatch && statusMatch[1];
};
const renderTweet = (tweet = {}) => {
const source = tweet.extended_tweet || tweet;
const entities = Object.assign({}, source.entities);
const text = source.full_text || source.text || "";
const { quoted_status: quote } = source;
const replacements = [];
Object.keys(entities).forEach(entityKey => {
const entityList = entities[entityKey];
// we should skip last link if it is a quote link
if (quote && "urls" === entityKey && entityList.length > 0) {
const lastLink = entityList[entityList.length - 1];
if (getStatusIdFromUrlEntity(lastLink) === quote.id_str) {
lastLink.skip = true;
}
}
replacements.push(
...entityList
.map(entity => {
const [start, end] = entity.indices;
return [renderEntity(entityKey, entity), start, end];
})
// do not add anything unknown
.filter(data => null !== data[0])
);
});
const output =
0 === replacements.length
? escapeMarkdown(text)
: processText(text, replacements);
return [output, quote && renderQuote(quote)].filter(Boolean).join("\n");
};
const renderQuote = data => {
const content = renderTweet(data)
.split("\n")
.map(row => `> ${row}`)
.join("\n");
return `
${content}`;
};
module.exports = renderTweet;