-
Notifications
You must be signed in to change notification settings - Fork 785
/
Copy pathTwitter.js
413 lines (381 loc) · 10.7 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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
{
"translatorID": "31659710-d04e-45d0-84ba-8e3f5afc4a54",
"label": "Twitter",
"creator": "Bo An, Dan Stillman",
"target": "^https?://([^/]+\\.)?(twitter|x)\\.com/",
"minVersion": "4.0",
"maxVersion": "",
"priority": 100,
"inRepository": true,
"translatorType": 4,
"browserSupport": "gcsibv",
"lastUpdated": "2024-05-24 17:08:12"
}
/*
***** BEGIN LICENSE BLOCK *****
Twitter Translator
Copyright © 2020-2021 Bo An, Dan Stillman
This file is part of Zotero.
Zotero is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Zotero is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Zotero. If not, see <http://www.gnu.org/licenses/>.
***** END LICENSE BLOCK *****
*/
let titleRe = /^(?:\(\d+\) )?(.+) .* (?:Twitter|X): .([\S\s]+). \/ (?:Twitter|X)/;
let domainRe = /https?:\/\/(?:www\.)?([^/]+)+/;
function detectWeb(doc, url) {
if (url.includes('/status/')) {
return "forumPost";
}
return false;
}
function unshortenURLs(doc, str) {
var matches = str.match(/https?:\/\/t\.co\/[a-z0-9]+/gi);
if (matches) {
for (let match of matches) {
let url = unshortenURL(doc, match);
// Replace t.co URLs (with optional query string, such as "?amp=1")
// in text with real URLs
str = str.replace(new RegExp(ZU.quotemeta(match) + '(\\?\\w+)?'), url);
}
}
return str;
}
function unshortenURL(doc, tCoURL) {
var a = doc.querySelector('a[href*="' + tCoURL + '"]');
if (!a || !domainRe.test(a.textContent)) {
return tCoURL;
}
return a.textContent.replace(/…$/, '');
}
function extractURLs(doc, str) {
var urls = [];
var matches = str.match(/https?:\/\/t\.co\/[a-z0-9]+/gi);
if (matches) {
for (let match of matches) {
urls.push(unshortenURL(doc, match));
}
}
return urls;
}
// Find the link to the permalink (e.g., "8h")
function findPermalinkLink(doc, canonicalURL) {
let path = canonicalURL.match(/https?:\/\/[^/]+(.+)/)[1];
return doc.querySelector(`a[href="${path}" i]`);
}
function doWeb(doc, url) {
scrape(doc, url);
}
function scrape(doc, url) {
var item = new Zotero.Item("forumPost");
var canonicalURL = doc.querySelector('link[rel="canonical"]').href;
// For unclear reasons, in some cases the URL doesn't have capitalization
// but rel="canonical" does, and in other cases it's the other way around,
// so if rel="canonical" doesn't have any caps, use the URL
if (!/[A-Z]/.test(canonicalURL)) {
canonicalURL = url.match(/^([^?#]+)/)[1];
}
var originalTitle = doc.title;
var unshortenedTitle = ZU.unescapeHTML(unshortenURLs(doc, originalTitle));
// Extract tweet from "[optional count] [Display Name] on Twitter: “[tweet]”"
var matches = unshortenedTitle.match(titleRe);
var [, author, tweet] = matches;
// Title is tweet with newlines removed
item.title = tweet.replace(/\s+/g, ' ');
// Don't set short title when tweet contains colon
item.shortTitle = false;
// Identify the tweet block by looking for the client link (e.g, "Tweetbot")
var articleEl;
var clientLink = doc.querySelector('a[href*="source-labels"]');
if (clientLink) {
articleEl = clientLink.closest('article');
}
// If client link not found, use permalink
//
// This is the case on share URLs such as
// https://twitter.com/aerospacecorp/status/1391160460150382598?s=27,
// but that doesn't serve content to the test runner for some reason, so
// we don't have a test for it.
else {
let a = findPermalinkLink(doc, canonicalURL);
articleEl = a.closest('article');
}
var tweetSelector = 'article[role="article"]';
// If the title is modified (e.g., because we stripped newlines), add the
// full tweet in Abstract.
//
// Same if it's a quote tweet, since the quoted tweet isn't included in the
// title. It would be better to just get the tweet URL, but that doesn't
// seem to be available on the page.
//
// DEBUG: 'role*=blockquote' doesn't seem to be used anymore, so there
// doesn't seem to be a good way to get the contents of the quoted tweet
let blockquote = articleEl.querySelector(`${tweetSelector} div[role*=blockquote]`);
if (tweet != item.title || blockquote) {
let note = ZU.text2html('“' + tweet + '”');
if (blockquote) {
note += '<blockquote>'
+ ZU.text2html(blockquote.innerText.replace(/[\s]+/g, ' ').trim())
+ "</blockquote>";
}
item.notes.push({ note });
}
item.language = attr(articleEl, 'div[lang]', 'lang');
item.creators.push({
lastName: `${author} [@${canonicalURL.split('/')[3]}]`,
fieldMode: 1,
creatorType: 'author'
});
// Date and time
var spans = articleEl.querySelectorAll(`${tweetSelector} a span`);
for (let span of spans) {
// Is this used in all locales?
let dotSep = ' · ';
let str = span.textContent;
if (!str.includes(dotSep)) {
// Z.debug("Date separator not found")
// Share URLs don't show the date, so use the <time> in the
// permalink link
//
// E.g., https://twitter.com/aerospacecorp/status/1391160460150382598?s=27
let a = findPermalinkLink(doc, canonicalURL);
if (a) {
let time = a.querySelector('time');
if (time) {
let dt = time.getAttribute('datetime');
item.date = dt.replace(/:\d\d\.000/, '');
}
}
continue;
}
let [time, date] = str.split(dotSep);
item.date = ZU.strToISO(date);
time = time.trim();
let matches = time.match(/^([0-9]{1,2})[:h]([0-9]{2})(?: (.+))?$/);
if (matches) {
let hour = matches[1];
let minute = matches[2];
let ampm = matches[3];
// If "PM", add 12 hours
if (ampm && ampm.toLowerCase() == 'pm' && hour != "12") {
hour = parseInt(hour) + 12;
}
// Convert to UTC and add 'T' and 'Z'
let isoDate = item.date + 'T' + ("" + hour).padStart(2, '0') + ':' + minute;
isoDate = new Date(isoDate).toISOString();
item.date = isoDate.replace(/:00\.000/, '');
}
}
item.forumTitle = "Twitter";
item.postType = "Tweet";
item.url = canonicalURL;
/*
// Add retweets and likes to Extra
let retweets;
let likes;
let str = text(articleEl, 'a[href*="retweets"]');
if (str) {
// Extract from "123 Retweets", "1.2K Retweets"
str = str.match(/^[^ ]+/);
if (str) {
retweets = str[0];
}
}
str = text(articleEl, 'a[href*="likes"]');
if (str) {
str = str.match(/^[^ ]+/);
if (str) {
likes = str[0];
}
}
if (!item.extra) {
item.extra = '';
}
if (retweets) {
item.extra += 'Retweets: ' + retweets;
}
if (likes) {
item.extra += '\n' + 'Likes: ' + likes;
}
*/
item.attachments.push({
document: doc,
title: "Snapshot"
});
// Add links to any URLs
var urls = extractURLs(doc, originalTitle);
for (let i = 0; i < urls.length; i++) {
let url = urls[i];
let title = "Link";
// Number links if more than one
if (urls.length > 1) {
title += " " + (i + 1);
}
// Include domain in parentheses
let domain = url.match(domainRe)[1];
if (domain != 't.co') {
title += ` (${domain})`;
}
item.attachments.push({
url,
title,
mimeType: "text/html",
snapshot: false
});
}
item.complete();
}
/** BEGIN TEST CASES **/
var testCases = [
{
"type": "web",
"url": "https://twitter.com/zotero/status/105608278976905216",
"defer": true,
"items": [
{
"itemType": "forumPost",
"title": "Zotero 3.0 beta is now available with duplicate detection and tons more. Runs outside Firefox with Chrome or Safari! http://zotero.org/blog/announcing-zotero-3-0-beta-release/",
"creators": [
{
"lastName": "Zotero [@zotero]",
"fieldMode": 1,
"creatorType": "author"
}
],
"date": "2011-08-22T11:52Z",
"forumTitle": "Twitter",
"language": "en",
"postType": "Tweet",
"url": "https://twitter.com/zotero/status/105608278976905216",
"attachments": [
{
"title": "Snapshot",
"mimeType": "text/html"
},
{
"title": "Link (zotero.org)",
"mimeType": "text/html",
"snapshot": false
}
],
"tags": [],
"notes": [],
"seeAlso": []
}
]
},
{
"type": "web",
"url": "https://twitter.com/zotero/status/1037407737154596864",
"defer": true,
"items": [
{
"itemType": "forumPost",
"title": "Zotero, Mendeley, EndNote. You have a lot of choices for managing your research. Here’s why we think you should choose Zotero. https://t.co/Qu2g5cGBGu",
"creators": [
{
"lastName": "Zotero [@zotero]",
"fieldMode": 1,
"creatorType": "author"
}
],
"date": "2018-09-05T18:30Z",
"forumTitle": "Twitter",
"language": "en",
"postType": "Tweet",
"url": "https://twitter.com/zotero/status/1037407737154596864",
"attachments": [
{
"title": "Snapshot",
"mimeType": "text/html"
},
{
"title": "Link",
"mimeType": "text/html",
"snapshot": false
}
],
"tags": [],
"notes": [],
"seeAlso": []
}
]
},
{
"type": "web",
"url": "https://twitter.com/zotero/status/1105581965405757440",
"defer": true,
"items": [
{
"itemType": "forumPost",
"title": "You don’t have to send students to a site that will spam them with ads or try to charge them money just to build a bibliography. Instead, tell them about ZoteroBib, the free, open-source, privacy-protecting bibliography generator from Zotero. https://zbib.org",
"creators": [
{
"lastName": "Zotero [@zotero]",
"fieldMode": 1,
"creatorType": "author"
}
],
"date": "2019-03-12T21:30Z",
"forumTitle": "Twitter",
"language": "en",
"postType": "Tweet",
"url": "https://twitter.com/zotero/status/1105581965405757440",
"attachments": [
{
"title": "Snapshot",
"mimeType": "text/html"
},
{
"title": "Link (zbib.org)",
"mimeType": "text/html",
"snapshot": false
}
],
"tags": [],
"notes": [],
"seeAlso": []
}
]
},
{
"type": "web",
"url": "https://twitter.com/DieZeitansage/status/958792005034930176",
"defer": true,
"items": [
{
"itemType": "forumPost",
"title": "Es ist 21:00 Uhr.",
"creators": [
{
"lastName": "Zeitansage [@DieZeitansage]",
"fieldMode": 1,
"creatorType": "author"
}
],
"date": "2018-01-31T20:00Z",
"forumTitle": "Twitter",
"language": "de",
"postType": "Tweet",
"url": "https://twitter.com/DieZeitansage/status/958792005034930176",
"attachments": [
{
"title": "Snapshot",
"mimeType": "text/html"
}
],
"tags": [],
"notes": [],
"seeAlso": []
}
]
}
]
/** END TEST CASES **/