-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtwitter.js
317 lines (242 loc) · 8.42 KB
/
twitter.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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
require('dotenv').config()
const request = require('request-promise')
const { promises: fs } = require("fs");
const syncFs = require('fs')
module.exports = {
getTweet,
getStyles,
autoEmbedTweets
}
async function getTweet(tweetId, options) {
// if we using cache and not cache busting, check there first
if (options.cacheDirectory && !process.env.CACHE_BUST) {
let cachedTweets = await getCachedTweets(options);
let cachedTweet = cachedTweets[tweetId]
// if we have a cached tweet, use that
if (cachedTweet) {
return formatTweet(cachedTweet, options)
}
// else continue on
}
// if we have env variables, go get tweet
if (hasAuth()) {
let liveTweet = await fetchTweet(tweetId)
let tweetViewModel = processTweet(liveTweet)
tweetViewModel.html = renderTweet(tweetViewModel)
// cache tweet
if (options.cacheDirectory) {
await addTweetToCache(tweetViewModel, options)
}
// build
return formatTweet(tweetViewModel, options)
} else {
console.warn("Remeber to add your twitter credentials as environement variables")
console.warn("Read More at https://github.com/KyleMit/eleventy-plugin-embed-tweet#setting-env-variables")
// else continue on
}
// finally fallback to client-side injection
var htmlTweet =
`<blockquote class="twitter-tweet"><a href="https://twitter.com/user/status/${tweetId}"></a></blockquote>` +
`<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>`
return htmlTweet
}
/* Twitter API Call */
function hasAuth() {
return process.env.TOKEN &&
process.env.TOKEN_SECRET &&
process.env.CONSUMER_KEY &&
process.env.CONSUMER_SECRET
}
function getAuth() {
let oAuth = {
token: process.env.TOKEN,
token_secret: process.env.TOKEN_SECRET,
consumer_key: process.env.CONSUMER_KEY,
consumer_secret: process.env.CONSUMER_SECRET,
}
return oAuth;
}
async function fetchTweet(tweetId) {
// fetch tweet
let apiURI = `https://api.twitter.com/1.1/statuses/show/${tweetId}.json?tweet_mode=extended`
let auth = getAuth()
try {
let response = await request.get(apiURI, { oauth: auth });
let tweet = JSON.parse(response)
return tweet
} catch (error) {
// unhappy path - continue to other fallbacks
console.log(error)
return {}
}
}
/* transform tweets */
function processTweet(tweet) {
// parse complicated stuff
let images = getTweetImages(tweet)
let created_at = getTweetDates(tweet)
let htmlText = getTweetTextHtml(tweet)
// destructure only properties we care about
let { id_str, favorite_count } = tweet
let { name, screen_name, profile_image_url_https } = tweet.user
let user = { name, screen_name, profile_image_url_https }
// build tweet with properties we want
let tweetViewModel = {
id_str,
htmlText,
images,
favorite_count,
created_at,
user
}
return tweetViewModel
}
function getTweetImages(tweet) {
let images = []
for (media of tweet.entities.media || []) {
images.push(media.media_url_https)
}
return images
}
function getTweetDates(tweet) {
let moment = require("moment");
// parse
let dateMoment = moment(tweet.created_at, "ddd MMM D hh:mm:ss Z YYYY");
// format
let display = dateMoment.format("hh:mm A · MMM D, YYYY")
let meta = dateMoment.utc().format("MMM D, YYYY hh:mm:ss (z)")
return { display, meta }
}
function getTweetTextHtml(tweet) {
let replacements = []
// hashtags
for (hashtag of tweet.entities.hashtags || []) {
let oldText = getOldText(tweet.full_text, hashtag.indices)
let newText = `<a href="https://twitter.com/hashtag/${oldText.substr(1)}">${oldText}</a>`
replacements.push({ oldText, newText })
}
// users
for (user of tweet.entities.user_mentions || []) {
let oldText = getOldText(tweet.full_text, user.indices)
let newText = `<a href="https://twitter.com/${oldText.substr(1)}">${oldText}</a>`
replacements.push({ oldText, newText })
}
// urls
for (url of tweet.entities.urls || []) {
let oldText = getOldText(tweet.full_text, url.indices)
let newText = `<a href="${url.expanded_url}">${url.expanded_url.replace(/https?:\/\//,"")}</a>`
replacements.push({ oldText, newText })
}
// media
for (media of tweet.entities.media || []) {
let oldText = getOldText(tweet.full_text, media.indices)
let newText = `` // get rid of img url in tweet text
replacements.push({ oldText, newText })
}
// make updates at the end
let htmlText = tweet.full_text
for (rep of replacements) {
htmlText = htmlText.replace(rep.oldText, rep.newText)
}
// preserve line breaks to survive minification
htmlText = htmlText.replace(/(?:\r\n|\r|\n)/g, '<br/>');
return htmlText
}
function getOldText(text, indices) {
let startPos = indices[0];
let endPos = indices[1];
let len = endPos - startPos
let oldText = text.substr(startPos, len)
return oldText
}
/* render tweets */
function renderTweet(tweet) {
// get module directory
let path = require("path")
let moduleDir = path.parse(__filename).dir
// configure nunjucks
let nunjucks = require("nunjucks")
nunjucks.configure(moduleDir, { autoescape: true });
// render with nunjucks
let htmlTweet = nunjucks.render("tweet.njk", tweet);
// minify before returning
// important when injected into markdown to prevent injection of `<p>` tags due to whitespace
let htmlMin = minifyHtml(htmlTweet)
return htmlMin
}
async function formatTweet(tweet, options) {
// add css if requested
if (options.useInlineStyles) {
let styles = await getStyles()
let stylesHtml = `<style type='text/css'>${styles}</style>`
let stylesMin = minifyHtml(stylesHtml)
return stylesMin + tweet.html
}
return tweet.html
}
function minifyHtml(htmlSource) {
var minify = require('html-minifier').minify;
var result = minify(htmlSource, {
minifyCSS: true,
collapseWhitespace: true
});
return result;
}
/* caching / file access */
async function getCachedTweets(options) {
let cachePath = getCachedTweetPath(options)
try {
let file = await fs.readFile(cachePath, "utf8")
cachedTweets = JSON.parse(file) || {}
return cachedTweets
} catch (error) {
// otherwise, empty array is fine
console.log(error)
return {}
}
}
async function addTweetToCache(tweet, options) {
try {
// get cache
let cachedTweets = await getCachedTweets(options)
// add new tweet
cachedTweets[tweet.id_str] = tweet
// build new cache string
let tweetsJSON = JSON.stringify(cachedTweets, 2, 2)
let cachePath = getCachedTweetPath(options)
let cacheDir = require("path").dirname(cachePath)
// makre sure directory exists
await fs.mkdir(cacheDir, { recursive: true })
syncFs.writeFileSync(cachePath, tweetsJSON)
console.log(`Writing ${cachePath}`)
} catch (error) {
console.log(error)
}
}
function getCachedTweetPath(options) {
let path = require("path")
// get directory for main thread
let appPath = require.main.filename // C:\user\github\app\node_modules\@11ty\eleventy\cmd.js
let pos = appPath.indexOf("node_modules")
let appRoot = appPath.substr(0, pos) // C:\user\github\app\
// build cache file path
let cachePath = path.join(appRoot, options.cacheDirectory, "tweets.json")
return cachePath
}
async function getStyles() {
// get module directory
let path = require("path")
let moduleDir = path.parse(__filename).dir
let stylePath = path.join(moduleDir, "/tweet.css")
let styles = await fs.readFile(stylePath, "utf8")
return styles
}
// Auto embed tweets
const asyncReplace = require('string-replace-async')
async function autoEmbedTweets(content, outputPath, options) {
// https://regexr.com/6v8ih
let findTweets = /<p ?.*>(<a href=")?(https:\/\/twitter.com\/[^/]+\/status\/([0-9]+))(">\2<\/a>)?<\/p>/g
return await asyncReplace(content, findTweets, async(match, p1, p2, p3) => {
return await getTweet(p3, options)
})
}