-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
406 lines (361 loc) · 13.7 KB
/
main.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
//GroupMe object: takes a client ID and an optional groupId, used to make all calls to the GroupMe API
function GroupMe(client_id, groupId) {
var dest = window.localStorage.getItem("GroupMe_destUrl");
if (dest !== null) {
window.localStorage.removeItem("GroupMe_destUrl");
window.location = dest;
}
this.auth = new URL(window.location).searchParams.get("access_token");
if (typeof this.auth != "string") {
console.log("Couldn't find access token in URL");
var token = window.localStorage.getItem("GroupMe_accessToken")
if (token !== null && token != "null") {
console.log("Found token in localStorage: " + token);
this.auth = token;
}
else {
window.localStorage.setItem("GroupMe_destUrl", window.location.href);
window.location = "https://oauth.groupme.com/oauth/authorize?client_id=" + client_id;
}
}
window.history.replaceState({}, document.title, window.location.href.split("?")[0]);
window.localStorage.setItem("GroupMe_accessToken", this.auth)
this.clearAuth = function () {
window.localStorage.removeItem("GroupMe_accessToken");
window.location = "https://oauth.groupme.com/oauth/authorize?client_id=" + client_id;
}
this.authToken = "?token=" + this.auth;
this.apiLink = "https://api.groupme.com/v3/";
this.makeRequest = function (method, reqtype, params) {
var xhr = new XMLHttpRequest();
var fullUrl = this.apiLink + reqtype + this.authToken + params;
xhr.open(method, fullUrl, false);
xhr.send();
if (method == "POST") {
return xhr.status;
}
return JSON.parse(xhr.response).response;
};
this.user = this.makeRequest("GET", "users/me", "");
this.userId = this.user.id;
this.userName = this.user.name;
this.groupList = function () {
var groups = [], cont = true, page = 1, start = Date.now();
while(cont) {
var resp = this.makeRequest("GET", "groups", "&page="+page+"&omit=members");
if (resp.length == 0) {
cont = false;
}
else {
for (var i = 0; i < resp.length; i++) {
groups.push(resp[i]);
}
}
page++;
}
console.log("Time to fetch groups: " + (Date.now() - start) + " ms.");
return groups;
}
if (typeof groupId != "undefined") {
this.groupId = groupId;
this.groupMembers = this.makeRequest("GET", "groups/" + this.groupId, "").members;
}
this.fetchMessages = function (quotebook, earliestMessage, second) {
var start = Date.now();
quotebook = typeof quotebook != 'undefined' ? quotebook : [];
var loaded = loaded || false;
var before = typeof earliestMessage !== 'undefined' ? "&before_id=" + earliestMessage : "";
var url = before + "&limit=" + NUM_MESSAGES_PER_REQ;
var msgResp = this.makeRequest("GET", "groups/" + this.groupId + "/messages", url);
console.log(msgResp);
//test if book is updated
if (!second && msgResp.count == window.localStorage.getItem("GroupMe_msgCount") && this.groupId.toString() == window.localStorage.getItem("GroupMe_groupId")) {
quotebook = JSON.parse(window.localStorage.getItem('GroupMe_currGroupMsgs'));
console.log("Updated quote book found!");
loaded = true;
}
//if not, add all messages to quotebook
else {
var k = quotebook.length;
var l = msgResp.messages.length;
for(var j = 0; j < l; j++) {
console.log(j+k);
quotebook[j+k] = msgResp.messages[j];
}
//i++;
earliestMessage = msgResp.messages[l - 1].id;
if (l < NUM_MESSAGES_PER_REQ) {
loaded = true;
}
}
// evaluate if the quotebook is loaded
if (loaded) {
window.localStorage.setItem('GroupMe_groupId', this.groupId);
window.localStorage.setItem('GroupMe_msgCount', msgResp.count);
window.localStorage.setItem('GroupMe_currGroupMsgs', JSON.stringify(quotebook));
console.log("All quotes loaded");
console.log("Time to fetch messages: " + (Date.now() - start) + " ms.");
return quotebook;
}
else {
console.log("Time to fetch messages: " + (Date.now() - start) + " ms.");
return this.fetchMessages(quotebook, earliestMessage, true);
}
}
this.likeMessage = function (msg) {
return 200 == this.makeRequest("POST", "messages/" + this.groupId + "/" + msg.id + "/like");
};
this.unlikeMessage = function (msg) {
return 200 == this.makeRequest("POST", "messages/" + this.groupId + "/" + msg.id + "/unlike");
};
}
//Quote object
function Quote (quote, user) {
this.id = quote.id;
this.rawText = quote.text;
this.poster = quote.name;
this.numLikes = quote.favorited_by.length;
this.time = new Date(quote.created_at * 1000).toDateString();
if (typeof user != "undefined") {
this.liked = false;
for (var i = 0; i < this.numLikes; i++) {
if (this.id == quote.favorited_by[i])
{
this.liked = true;
}
}
}
this.process = function() {
if (this.rawText === null) {
return false;
}
message = this.rawText.split('-');
if (message.length == 2 && message[0].length > 0 && this.numLikes >= 2) {
this.text = message[0];
this.author = message[1];
return true;
} else {
return false;
}
}
}
//QuoteGenerator object: takes an array of messages, used to generate Quote objects
function QuoteGenerator(quotebook, user) {
this.quotebook = quotebook;
this.user = user;
this.lastRandMsgNum = -1;
this.getQuote = function () {
var randMsgNum = Math.floor(Math.random() * this.quotebook.length);
var quote = new Quote(quotebook[randMsgNum], this.user);
if(this.lastRandMsgNum == randMsgNum) {
return this.getQuote();
} else {
this.lastRandMsgNum = randMsgNum;
return quote;
}
}
}
// Begin QuoteGame specific code
var storage, messagesViewed, gm;
var settingsShowing = false;
var NUM_MESSAGES_PER_REQ = 100, NUM_GUESS_OPTIONS = 4;
function init() {
var client_id = "Ev579DJHgZMDSLeqNWQufy2l6bA2BDJPuK2XXcJ64jLsxXJb"; // this one is for gtq.alexlucky.me
storage = window.localStorage;
messagesViewed = parseInt(storage.getItem("QuoteGame_msgsViewed")) || 0;
var params = new URL(window.location).searchParams;
var groupId = storage.getItem("QuoteGame_groupId");
if (typeof params.get("group") == "string" && typeof params.get("msg") == "string") {
gm = new GroupMe(client_id, params.get("group"));
loadQuotes(params.get("msg"));
}
else if (groupId !== null) {
gm = new GroupMe(client_id, groupId);
loadQuotes();
}
else {
gm = new GroupMe(client_id);
displayGroups();
}
}
function displayGroups() {
var groups = gm.groupList();
var groupDiv = document.getElementById("groups");
while(groupDiv.firstChild) {
groupDiv.removeChild(groupDiv.firstChild);
}
var heading = document.createElement("h2");
var headingText = document.createTextNode("Select which group you'd like to pull quotes from");
heading.appendChild(headingText);
groupDiv.appendChild(heading);
for(i = 0, j = groups.length; i < j; i++) {
var element = document.createElement("p");
var textNode = document.createTextNode(groups[i].name);
element.appendChild(textNode);
element.id = "group" + i;
groupDiv.appendChild(element);
}
groupDiv.addEventListener("click", function(e) {
gm.groupId = groups[parseInt(e.target.id.substring(5))].id;
storage.setItem("QuoteGame_groupId", gm.groupId);
groupDiv.style.display = "none";
loadQuotes();
});
groupDiv.style.display = "block";
/*var prev = document.createElement("button");
prev.value = "Prev"
var next = document.createElement("button");
next.value = "Next";
prev.addEventListener("click", function(e) {
gm.groupId = groups[parseInt(e.target.id.substring(5))].id;
storage.setItem("QuoteGame_groupId", gm.groupId);
groupDiv.style.display = "none";
loadQuotes();
});*/
}
function loadQuotes(msg) {
var settings = JSON.parse(storage.getItem("QuoteGame_settings"));
loadSettings(settings);
var quotebook = gm.fetchMessages();
var user = gm.userId;
var qg = new QuoteGenerator(quotebook, user);
if (msg !== undefined) {
for (var i = 0; i < quotebook.length; i++) {
var message = quotebook[i]
if (message.id == msg) {
renderQuote(qg, message);
}
}
} else {
renderQuote(qg);
}
document.onkeypress = function(e) {
e = e || window.event;
if (e.key == "n") {
renderQuote(qg);
} else if (e.key == "r") {
revealAnswer();
} else if (e.key == "g") {
displayGroups(gm);
} else if (e.key == "s") {
revealShareLink();
} else if (e.key == "v") {
console.log(gm);
console.log(quotebook);
console.log(qg);
}
};
document.getElementById("revealButton").addEventListener("click", revealAnswer);
document.getElementById("newQuoteButton").addEventListener("click", function() { renderQuote(qg); });
document.getElementById("shareButton").addEventListener("click", revealShareLink)
document.getElementsByClassName("settings-toggle")[0].addEventListener("click", toggleSettings);
document.getElementsByClassName("settings-toggle")[1].addEventListener("click", toggleSettings);
document.getElementById("app").style.display = "block";
window.onunload = function() {
window.localStorage.setItem("QuoteGame_msgsViewed", messagesViewed);
};
}
function revealAnswer() {
document.getElementById("reveal").style.display = "inline";
}
function revealShareLink() {
var shareUrl = document.getElementById("shareUrl");
shareUrl.style.display = "inline";
shareUrl.select();
}
function renderQuote(qg, msg) {
var message;
if (msg !== undefined) {
message = new Quote(msg, qg.user);
} else {
message = qg.getQuote();
}
while (!message.process()) {
message = qg.getQuote();
}
var quote = document.getElementById("quote");
var author = document.getElementById("author");
var poster = document.getElementById("poster");
var reveal = document.getElementById("reveal");
var time = document.getElementById("time");
var likes = document.getElementById("likes");
var shareUrl = document.getElementById("shareUrl");
reveal.style.display = "none";
shareUrl.style.display = "none";
quote.innerHTML = message.text;
author.innerHTML = message.author;
poster.innerHTML = message.poster;
time.innerHTML = message.time;
likes.innerHTML = message.numLikes;
shareUrl.value = window.location.protocol + "//" + window.location.host + window.location.pathname + "?group=" + gm.groupId + "&msg=" + message.id;
messagesViewed++;
}
function toggleLike() {
if (curQuoteLiked === true) {
//unlike
}
else {
//like
}
}
function toggleSettings() {
var settingsDiv = document.getElementsByClassName("settings")[0];
var settings = JSON.parse(storage.getItem("QuoteGame_settings")) || {};
var savegroup = document.getElementsByName("savegroup")[0];
var gamemode = document.getElementsByName("gamemode");
var numoptions = document.getElementsByName("numoptions")[0];
if (settingsShowing) {
// save all settings currently in the system
settings.saveGroup = savegroup.checked;
for(var i = 0, j = gamemode.length; i < j; i++) {
if(gamemode[i].checked) {
settings.gamemode = i;
}
}
settings.numoptions = numoptions.value;
storage.setItem("QuoteGame_settings", JSON.stringify(settings));
// apply settings changes
loadSettings(settings);
// hide the settings dialog
settingsDiv.style.display = "none";
}
else {
// load current settings into the settings div
// show default options if none are stored
if(typeof settings.gamemode == "undefined") {
settings = {
saveGroup:true,
gamemode:2
}
}
savegroup.checked = settings.saveGroup;
gamemode[settings.gamemode].checked = true;
numoptions.value = settings.numoptions;
numoptions.max = gm.groupMembers.length;
document.getElementById("numviewed").innerHTML = messagesViewed;
document.getElementById("user").innerHTML = gm.userName;
// show the settings div
settingsDiv.style.display = "block";
}
// toggle the settingsShowing var
settingsShowing = !settingsShowing;
}
function loadSettings(settings) {
console.log(settings);
var defaultSettings = {
saveGroup:true,
gamemode:2
}
settings = settings || defaultSettings;
}
function clearGroup() {
storage.removeItem("QuoteGame_groupId");
toggleSettings();
document.getElementById("app").style.display = "none";
displayGroups();
}
function clearUser() {
gm.clearAuth();
}
function processGuess() {
}