-
Notifications
You must be signed in to change notification settings - Fork 1
/
popup.js
424 lines (350 loc) · 14.2 KB
/
popup.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
414
415
416
417
418
419
420
421
422
423
var loginData = {
accessToken: null,
username: null
};
function dataURLToBlob(dataUrl) {
const arr = dataUrl.split(',');
const mime = arr[0].match(/:(.*?);/)[1];
const bstr = atob(arr[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
}
function displayUserFeedback(messageText, isSuccess = true) {
// Create a new message element
let messageElement = document.createElement('div');
// Add classes to the message
messageElement.className = 'message ' + (isSuccess ? 'success' : 'error');
// Set the text content of the message
messageElement.textContent = messageText;
// Append the message to the body
document.body.appendChild(messageElement);
// After 6 seconds, remove the message
setTimeout(() => {
document.body.removeChild(messageElement);
}, 6000);
}
base_url='https://api.myriad.social';
function createMyriadPost(title, textBlocks, platform = 'myriad', visibility = 'public') {
const apiEndpoint = `${base_url}/user/posts`;
fetch(`${base_url}/users/${loginData.username}`, {
headers: {
'Authorization': `Bearer ${loginData.accessToken}`
}
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(user_data => {
const createdBy = user_data.id;
let now = new Date();
let createdAt = now.toISOString();
let text = textBlocks.join('\n');
let post_data = {
"rawText": text,
"text": text,
"status": "published",
"selectedTimelineIds": [],
"createdBy": createdBy,
"createdAt": createdAt,
"platform": platform,
"visibility": visibility
};
return fetch(apiEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${loginData.accessToken}`
},
body: JSON.stringify(post_data)
})
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => {
console.log('Post created successfully!');
displayUserFeedback('Post created successfully!', true);
})
.catch((error) => {
console.error('Error:', error);
});
}
//Alex check below
// When the popup is opened, get the active tab URL.
chrome.tabs.query({active: true, lastFocusedWindow: true}, function(tabs) {
let url = tabs[0].url;
const iframe = document.getElementById('myriad_iframe');
iframe.style.display = 'none';
// If the active page is Twitter
if (url.includes("twitter.com")) {
// Check if the URL is of the format "https://twitter.com/{username}/status/{postid}"
const match = url.match(/https:\/\/twitter\.com\/[^\/]+\/status\/(\d+)/);
processMatch(match);
}
// If the active page is Reddit
if (url.includes("reddit.com")) {
// Check if the URL is of the format "https://www.reddit.com/r/{subreddit}/comments/{alphanumeric}/{title}/"
const match = url.match(/https:\/\/www\.reddit\.com\/r\/[^\/]+\/comments\/(\w+)/);
processMatch(match);
}
function processMatch(match) {
if (match) {
const postId = match[1];
// Perform a GET request to the API
fetch('https://api.myriad.social//user/posts?pageLimit=200')
.then(response => response.json())
.then(data => {
// Find the post with the same "originPostId" as our "postid"
const post = data.data.find(post => post.originPostId === postId);
// Get the iframe and other elements
const emailField = document.getElementById('emailfield');
const magicLink = document.getElementById('magiclink');
const postDiv = document.getElementById('post');
const importDiv = document.getElementById('import');
if (post) {
// Construct the Myriad URL
const myriadUrl = `https://app.myriad.social/post/${post.id}`;
// Set the source of the iframe
iframe.src = myriadUrl;
// Show the iframe and hide the other elements
iframe.style.display = 'block';
emailField.style.display = 'none';
magicLink.style.display = 'none';
postDiv.style.display = 'none';
importDiv.style.display = 'none';
} else {
// Hide the iframe and show the other elements
iframe.style.display = 'none';
console.log('Post not found in API response.');
}
})
.catch(error => console.error('Error:', error));
}
}
});
document.addEventListener('DOMContentLoaded', function () {
var buttons = document.getElementsByTagName('button');
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', function () {
this.style.backgroundColor = '#ffd24d';
});
}
var writePostButton = document.getElementById('write_post_button');
var submitPostButton = document.getElementById('submit_post_button');
var postContent = document.getElementById('post_content');
writePostButton.addEventListener('click', function () {
postContent.style.display = 'block';
submitPostButton.style.display = 'inline-block';
});
submitPostButton.addEventListener('click', function () {
let content = postContent.value;
if (content) {
let title = 'Title';
let textBlocks = content.split('\n');
createMyriadPost(title, textBlocks);
postContent.value = '';
postContent.style.display = 'none';
this.style.display = 'none';
}
});
document.getElementById('send_magic_link').addEventListener('click', function () {
var email = document.getElementById('email').value;
sendMagicLink(email);
});
document.getElementById('submit_magic_link').addEventListener('click', function () {
var magicLink = document.getElementById('magic_link').value;
authenticate(magicLink);
});
document.getElementById('import_post').addEventListener('click', function () {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
var currentUrl = tabs[0].url;
if (currentUrl.includes('twitter.com') || currentUrl.includes('reddit.com')) {
importTwitterPost(currentUrl);
} else if (currentUrl.includes('youtube.com')) {
let text = `<iframe width="100%" height="315" src="${currentUrl}" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>`;
if (text.includes('watch?v=')) {
text = text.replace('watch?v=', 'embed/');
}
let content = postContent.value;
let title = 'Title';
let textBlocks = [text];
if (content) {
textBlocks.unshift(content.split('</p><p>'));
}
// Create Myriad Post
createMyriadPost(title, textBlocks, 'myriad', 'public');
postContent.value = '';
postContent.style.display = 'none';
this.style.display = 'none';
} else if (currentUrl.includes('twitch.tv/')) {
const url = new URL(currentUrl);
let twitchUser = url.pathname.substring(1);
let text = `<iframe src="https://player.twitch.tv/?channel=${twitchUser}&parent=app.myriad.social" frameborder="0" allowfullscreen="true" scrolling="no" height="378" width="100%"></iframe>`
let textBlocks = [text];
let title = 'Title';
let content = postContent.value;
if (content) {
textBlocks.unshift(content.split('</p><p>'));
}
// Create Myriad Post
createMyriadPost(title, textBlocks, 'myriad', 'public');
postContent.value = '';
postContent.style.display = 'none';
this.style.display = 'none';
}
});
});
});
function checkLogin() {
var writepostbuttonElement = document.getElementById('write_post_button');
var importbuttonElement = document.getElementById('import_post');
importbuttonElement.innerText = importbuttonElement.textContent = 'new text';
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var currentUrl = tabs[0].url;
var contextElement = document.getElementById('contextof');
if (currentUrl.includes('twitter.com') || currentUrl.includes('reddit.com')) {
//displayUserFeedback(`The current page is natively importable to Myriad!`, true);
contextElement.innerText = "The current page is natively importable to Myriad! ";
document.getElementById('write_post_button').style.display = 'none';
importbuttonElement.innerText = importbuttonElement.textContent = 'Import Post';
} else if (currentUrl.includes('youtube.com') || currentUrl.includes('twitch.tv')) {
contextElement.innerText = "The current page can be embedded into a Myriad post! ";
writepostbuttonElement.innerText=writepostbuttonElement.textContent = 'Add Caption';
importbuttonElement.innerText = importbuttonElement.textContent = 'Embed Video';
} else {
contextElement.innerText = "Myriad supports imports from Twitter, Reddit, YouTube, and Twitch! You can still write a post below.";
importbuttonElement.innerText = importbuttonElement.textContent = 'Archive Content';
document.getElementById('import_post').style.display = 'none';
}
})
// Retrieve the "accessToken" and "username" from local storage
var accessToken = localStorage.getItem("accessToken");
var username = localStorage.getItem("username");
if (accessToken && username) {
loginData.accessToken = accessToken;
loginData.username = username;
var preloginElement = document.getElementById('prelogin');
if (preloginElement) {
preloginElement.innerText = "Logged in as: " + username;
}
document.getElementById('email').style.display = 'none';
document.getElementById('magic_link').style.display = 'none';
document.getElementById('send_magic_link').style.display = 'none';
document.getElementById('submit_magic_link').style.display = 'none';
document.getElementById('write_post_button').style.display = 'inline-block';
document.getElementById('import_post').style.display = 'inline-block';
} else {
document.getElementById('email').style.display = 'block';
document.getElementById('magic_link').style.display = 'block';
document.getElementById('send_magic_link').style.display = 'block';
document.getElementById('submit_magic_link').style.display = 'block';
document.getElementById('prelogin').style.display = 'block';
document.getElementById('write_post_button').style.display = 'none';
document.getElementById('import_post').style.display = 'none';
}
};
function sendMagicLink(email) {
var apiUrl = "https://api.myriad.social/authentication/otp/email";
fetch(apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
"email": email,
"callbackURL": "https://app.myriad.social/login"
})
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => {
console.log(data);
displayUserFeedback('Magic link has been successfully sent to your email. Please copy that magic link from your email and come back here to paste it!');
})
.catch((error) => {
console.error('Error:', error);
displayUserFeedback('There was an error sending the magic link. Please try again.', false);
});
}
function authenticate(magicLink) {
var callbackUrl = "https://app.myriad.social/login";
var token = magicLink.replace(callbackUrl+"?token=", "");
var apiUrl = "https://api.myriad.social/authentication/login/otp";
fetch(apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
"token": token
})
}).then(response => response.json())
.then(data => {
var accessToken = data.token.accessToken;
var username = data.user.username;
// store accessToken and username in local storage
localStorage.setItem("accessToken", accessToken);
localStorage.setItem("username", username);
displayUserFeedback('Access Token and Username are set in local storage');
checkLogin();
document.getElementById('import_post').style.visibility = 'visible';
var preloginElement = document.getElementById('prelogin');
if (preloginElement) {
preloginElement.innerText = "Logged in as: " + username;
}
})
.catch((error) => {
console.error('Error:', error);
displayUserFeedback('There was an error during authentication. Please try again.', false);
});
}
function importTwitterPost(twitterUrl, selectedTimelineIds = []) {
// retrieve access token and username from local storage
var at = localStorage.getItem("accessToken");
var un = localStorage.getItem("username");
var apiUrl = "https://api.myriad.social/user/posts/import";
var headers = {
'accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + at,
};
var data = {
"url": twitterUrl,
"importer": un,
"selectedTimelineIds": selectedTimelineIds,
};
fetch(apiUrl, {
method: 'POST',
headers: headers,
body: JSON.stringify(data)
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => {
console.log(data);
displayUserFeedback('The post has been successfully imported.');
})
.catch((error) => {
console.error('Error:', error);
displayUserFeedback('There was an error during the import. Please try again.', false);
});
};
document.addEventListener('DOMContentLoaded', checkLogin);