-
Notifications
You must be signed in to change notification settings - Fork 31
/
like-on-github.js
441 lines (361 loc) · 13.1 KB
/
like-on-github.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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
/**
* LikeOnGitHub
*
* This file is part of the LikeOnGitHub; an opensource Google Chrome extension
* http://github.com/idnan/like-on-github
*
* MIT (c) Adnan Ahmed <[email protected]>
*/
(function () {
var Helper = {
/**
* Hides the log on github popup
*/
closePopup: function () {
let $container = $(Config.EX_COTAINER);
if ($container.length === 0) {
return false;
}
Helper.resetPopupHtml();
$(Config.EX_COTAINER).hide();
$(Config.EX_INPUT_TITLE).val('');
$(Config.EX_INPUT_URL).val('');
$(Config.EX_INPUT_COMMENT).val('');
return true;
},
/**
* Gets the tab switcher element and makes it visible. If it cannot find the element creates it.
*/
showPopup: function () {
let $container = $(Config.EX_COTAINER);
// Some pages remove the tab switcher HTML by chance
// so we check if the tab switcher was found and we re append if it is not found
if ($container.length === 0) {
appendLikeOnGithubHtml(Config.EX_CONTAINER_BODY);
$container = $(Config.EX_COTAINER);
}
$container.show();
},
/**
* Reset the html of the popup
*/
resetPopupHtml: function () {
$(Config.EX_BTN_SAVE).text('Save');
$(Config.EX_ERROR_CONTAINER).hide();
$(Config.EX_ERROR_LINE).html('');
},
/**
* Validate the form fields
*/
isFormValid: function () {
let title = $(Config.EX_INPUT_TITLE).val().trim(),
comment = $(Config.EX_INPUT_COMMENT).val().trim();
return !!(title && comment);
},
};
var Storage = {
/**
* Get value from storage
*
* @returns {string}
* @param callback
*/
getRepoUrl: function (callback) {
chrome.extension.sendMessage({
type: 'getStorage',
params: {
keys: ['owner', 'repo', 'path', 'token', 'committer_name', 'committer_email']
}
}, function (res) {
callback(res);
});
},
};
/**
* Configuration constants for the extension
*
* @type {Object}
*/
var Config = {
// Templates
MAIN_TEMPLATE: '<div class="logh">' +
'<h3>Like On GitHub</h3>' +
'<div class="clogl">' +
'<div class="lbllogh"><span class="reqlogh">*</span>Title (label for the link)</div>' +
'<input type="text" name="title">' +
'</div>' +
'<div class="clogl">' +
'<input type="hidden" name="url">' +
'</div>' +
'<div class="clogl">' +
'<div class="lbllogh"><span class="reqlogh">*</span>Comment (commit message)</div>' +
'<textarea name="comment"></textarea>' +
'</div>' +
'<div id="action-btns">' +
'<div class="btn btn-primary" id="logh_btn_save">Save</div>' +
'<div class="btn" id="logh_btn_cancel">Cancel</div>' +
'</div>' +
'<div class="elogh hlogh">' +
'<p></p>' +
'</div>' +
'</div>',
// References to DOM elements
EX_COTAINER: '.logh',
EX_INPUT_TITLE: '.logh input[name="title"]',
EX_INPUT_URL: '.logh input[name="url"]',
EX_INPUT_COMMENT: '.logh textarea[name="comment"]',
EX_CONTAINER_BODY: 'body',
EX_BTN_SAVE: '.logh #logh_btn_save',
EX_BTN_CANCEL: '.logh #logh_btn_cancel',
EX_ERROR_CONTAINER: '.logh .elogh',
EX_ERROR_LINE: '.logh .elogh p',
// Shortcut for activation
MASTER_KEY: '⌘+⇧+l, ⌃+⇧+l',
// Key codes for certain actions
ESCAPE_KEY: 27,
// REPO
BASE_URL: 'https://api.github.com/repos',
};
/**
* Houses all the browser related actions
*
* @type {Object}
*/
var ActiveTab = {
activeTab: false,
/**
* Return current selected tab
*
* @returns {*}
*/
get: function (callback) {
let activeTab = ActiveTab.activeTab;
if (activeTab) {
callback(activeTab);
}
chrome.extension.sendMessage({type: 'getActiveTab'}, function (tab) {
if (!tab) {
return false;
}
ActiveTab.activeTab = tab;
callback(ActiveTab.activeTab);
});
}
};
var Repo = {
commitLike: function (items) {
let repoUrl = `${Config.BASE_URL}/${items['owner']}/${items['repo']}/contents/${items['path']}`;
let auth = { Authorization: `token ${ items['token'] }` }
if (!repoUrl) {
return false;
}
let activeTabTitle = $(Config.EX_INPUT_TITLE).val(),
activeTabUrl = $(Config.EX_INPUT_URL).val(),
commitMessage = $(Config.EX_INPUT_COMMENT).val();
fetch(repoUrl, { headers: auth })
.then(response => response.json())
.then(response => {
let sha = response.sha,
encodedContent = response.content,
decodedContent = decodeURIComponent(escape(window.atob(encodedContent)));
const dataToAppend = `- [${activeTabTitle}](${activeTabUrl}) \n`;
// append data in the front
decodedContent = Repo.appendDataBefore(dataToAppend, decodedContent);
// decode content
encodedContent = window.btoa(unescape(encodeURIComponent(decodedContent)));
// prepare commit
return {
sha: sha,
content: encodedContent,
message: commitMessage,
committer: {
'name': items['committer_name'],
'email': items['committer_email']
}
}
})
.then(commit => fetch(repoUrl, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
...auth
},
body: JSON.stringify(commit)
}))
.then(success => {
$(Config.EX_BTN_SAVE).text('Save');
success.json().then((res) => {
$(Config.EX_ERROR_CONTAINER).show();
let message = '';
if (success.status && success.status === 200) {
message = 'Link pushed: <a href="' + res.commit.html_url + '" target="_blank">Click</a> (Popup will auto close after 5 secs)';
// close the popup after 5 secs
setTimeout(function () {
Helper.closePopup();
}, 5000);
} else {
message = res.message;
}
$(Config.EX_ERROR_LINE).html(message);
$(Config.EX_BTN_SAVE).removeClass('saving');
});
})
.catch(error => {
$(Config.EX_BTN_SAVE).removeClass('saving').text('Save');
});
},
/**
* Append data in the front
* @param dataToAppend
* @param content
* @returns {String}
*/
appendDataBefore: function (dataToAppend, content) {
// If the file is empty
if (content.trim().length === 0) {
content += '# today-i-liked \nContent that I liked. Saved using https://goo.gl/Wj595G \n';
}
const arr = content.split('###');
// if the length of arr is 1, then it is the first time to append data
if (arr.length === 1) {
arr[0] += Repo.getDateHeader();
arr[0] += dataToAppend;
content = arr.join('');
} else {
// if has not append data of currentDate, then append DateHeader
if (!Repo.isCurrentDateExists(content)) {
arr[0] += Repo.getDateHeader();
arr[0] += dataToAppend;
} else { // if already have date then append to that
arr[1] += dataToAppend;
}
content = arr.join('###');
}
return content;
},
/**
* Return date header
*
* @returns {string}
*/
getDateHeader: function () {
return `\n### ${Repo.getCurrentDate()} \n`;
},
/**
* Check if current date already exists in the content
*
* @param content
* @returns {boolean}
*/
isCurrentDateExists: function (content) {
return (content.indexOf(Repo.getCurrentDate()) !== -1);
},
/**
* Return current
*
* @returns {string}
*/
getCurrentDate: function () {
const date = new Date();
return `${Repo.monthNames()[date.getMonth()]} ${date.getDate()}, ${date.getFullYear()}`;
},
/**
* Return month names
*
* @returns {string[]}
*/
monthNames: function () {
return [
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'
];
},
};
/**
* Main extension class
*
* @returns {{loadExtension: loadExtension, bindUI: bindUI}}
* @constructor
*/
function LikeOnGithub() {
/**
* Appends the tab switcher HTML to the $container
*
* @param $container
* @returns {*}
*/
function appendLikeOnGithubHtml($container) {
if (!($container instanceof jQuery)) {
$container = $($container);
}
$container.append(Config.MAIN_TEMPLATE);
return $container;
}
return {
/**
* Loads the extension in specified container
*
* @param $container
*/
loadExtension: function ($container) {
appendLikeOnGithubHtml($container);
this.bindUI();
},
/**
* Binds the UI elements for the extension
*/
bindUI: function () {
// close on escape key
$(document).on('keyup', function (e) {
if (e.keyCode === Config.ESCAPE_KEY) {
Helper.closePopup();
}
});
// if clicked outside the popup
$(document).on('mouseup', function (e) {
let container = $(Config.EX_COTAINER);
if (!container.is(e.target) && container.has(e.target).length === 0) {
Helper.closePopup();
}
});
// hide the switcher on blurring of input
$(document).on('click', Config.EX_BTN_CANCEL, function () {
Helper.closePopup();
});
// hide the switcher on blurring of input
$(document).on('click', Config.EX_BTN_SAVE, function () {
let saveBtn = $(Config.EX_BTN_SAVE);
if (saveBtn.hasClass('saving') || !Helper.isFormValid()) {
return false;
}
Helper.resetPopupHtml();
saveBtn.addClass('saving').text('Saving...');
Storage.getRepoUrl(function (items) {
// commit the like
if (items) {
Repo.commitLike(items);
}
});
});
// master key binding for which extension will be enabled
key(Config.MASTER_KEY, function () {
Helper.showPopup();
$(Config.EX_INPUT_TITLE).focus();
// get the active tab
ActiveTab.get(function (activeTab) {
if (!activeTab) {
return false;
}
$(Config.EX_INPUT_TITLE).val(activeTab.title);
$(Config.EX_INPUT_URL).val(activeTab.url);
$(Config.EX_INPUT_COMMENT).val('New Link: ' + activeTab.title);
});
});
}
};
}
$(document).ready(function () {
var likeOnGithub = new LikeOnGithub();
likeOnGithub.loadExtension(Config.EX_CONTAINER_BODY);
});
})();