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
|
/**
* Filter Storage to assist in storing the filter to localStorage
* and retrieving to populate back
*
* @returns {{persistFilters: persistFilters, populateFilters: populateFilters}}
* @constructor
*/
function HubStorage() {
/**
* Returns the storage object if available, otherwise
* a polyfill
* @returns {*}
*/
var getStorage = function () {
if (window.localStorage) {
return window.localStorage;
}
return {
setItem: function () {
},
getItem: function () {
}
}
};
/**
* Persists the values of the provided input input selector
* @param selector`
*/
var persistFilters = function (selector) {
var storage = getStorage();
$(selector).each(function (index, input) {
var $input = $(input),
name = $input.attr('name');
storage.setItem(name, $input.val());
});
};
/**
* Retrieves the values for the provided selector from localstorage
* and populates the fields back
* @param selector
*/
var populateFilters = function (selector) {
var storage = getStorage();
$(selector).each(function (index, input) {
var $input = $(input),
name = $input.attr('name'),
value = storage.getItem(name);
if (value) {
$input.val(value);
}
});
};
return {
/**
* Persist the fields matching the provided selector to local storage
* @param selector
*/
persistFilters: function (selector) {
persistFilters(selector);
},
/**
* Populates the filters using the values stored in the localstorage
* @param selector
*/
populateFilters: function (selector) {
return populateFilters(selector);
},
/**
* Returns the localStorageObject
* @returns {{setItem, getItem}}
*/
getStorage: function () {
return getStorage();
}
};
}
/**
* @returns {{init: init, refresh: refresh}}
* @constructor
*/
function HubTab() {
var trendingRequest = false, // To make sure that there are no parallel requests
repoGroupSelector = '.content-batch', // Batch of repositories
filterSelector = '.repos-filter', // Selector that matches every repo filter on page
mainContainer = '.main-content', // Main container div
dateHead = '.date-head', // Heading item for the batch of repositories
dateAttribute = 'date', // Date attribute on the date head of batch
// token = 'a1a420cbad0a4d3eccda', // API token. Don't grin, it's a dummy
languageFilter = '#language', // Filter for repositories language
dateFilter = '#date-jump', // Date jump filter i.e. weekly, monthly or yearly
tokenStorageKey = 'githunt_token', // Storage key for the github token
requestCount = 0, // Track the count of how many times the refresh was tried
reposApiUrl = 'https://api.github.com/search/repositories', // URL for the repos
// All the content from last hunt will be cached in localstorage for some time to avoid
// requests on each tab change
lastHuntResult = 'last_hunt_result',
// Minutes for which upon the first request, we won't refresh and just return the cached result
refreshDuration = '45',
// The time for last hunt
lastHuntTime = 'last_hunt_time';
var filterStorage = new HubStorage();
/**
* Generates the HTML for batch of repositories
* @param repositories
* @param lowerDate
* @param upperDate
* @returns {string}
*/
function generateReposHtml(repositories, lowerDate, upperDate) {
var html = '';
$(repositories).each(function (index, repository) {
html += '<div class="content-item">' +
'<div class="header"><a href="' + repository.html_url + '">' + repository.full_name + '</a></div>' +
'<p class="tagline">' + repository.description + '</p>' +
'<div class="footer">' +
'<span class="footer-stat">' +
'<i class="fa fa-code-fork"></i>' +
repository.forks_count +
'</span>' +
'<span class="footer-stat">' +
'<i class="fa fa-commenting-o"></i>' +
repository.open_issues +
'</span>' +
'<span class="footer-stat">' +
'<i class="fa fa-star-o"></i>' +
repository.stargazers_count +
'</span>' +
'</div>' +
'</div>';
});
var humanDate = moment(lowerDate).fromNow(),
formattedLower = moment(lowerDate).format('ll'),
formattedUpper = moment(upperDate).format('ll');
var finalHtml = '<div class="content-batch"><h1 class="date-head" data-date="' + lowerDate + '">' + humanDate + ' - ' + formattedLower + ' – ' + formattedUpper + '</h1>' + html + '<div class="clearfix"></div></div></div>';
return finalHtml;
}
/**
* Gets the next date range for which repositories need to be fetched
* @returns {{}}
*/
var getNextDateRange = function () {
// Lower limit for when the last repos batch was fetched
var lastFetched = $(repoGroupSelector).last().find(dateHead).data(dateAttribute),
dateRange = {},
dateJump = $(dateFilter).val();
if (lastFetched) {
dateRange.upper = lastFetched;
dateRange.lower = moment(lastFetched).subtract(1, dateJump).format('YYYY-MM-DD');
} else {
dateRange.upper = moment().format('YYYY-MM-DD');
dateRange.lower = moment().add(1, 'day').subtract(1, dateJump).format('YYYY-MM-DD');
}
return dateRange;
};
/**
* Gets the filters to be passed to API
* @returns {{queryParams: string, dateRange: {}}}
*/
var getApiFilters = function () {
var dateRange = getNextDateRange(),
language = $(languageFilter).val(),
langCondition = '';
// If language filter is applied, populate the language
// chunk to put in URL
if (language) {
langCondition = 'language:' + language + ' ';
}
// If user has set the github token in storage pass that
// alongside the request.
var token = $.trim(filterStorage.getStorage().getItem(tokenStorageKey)),
apiToken = '';
if (token) {
apiToken = '&access_token=' + token;
}
return {
queryParams: '?sort=stars&order=desc&q=' + langCondition + 'created:"' + dateRange.lower + ' .. ' + dateRange.upper + '"' + apiToken,
dateRange: dateRange
};
};
/**
* Saves the hunt result in localstorage to avoid requests on each tab change
*/
var saveHuntResult = function () {
// Save the hunt results to storage.
filterStorage.getStorage().setItem(lastHuntResult, $('.main-content').html());
filterStorage.getStorage().setItem(lastHuntTime, moment().format('YYYY-MM-DD HH:mm:ss'));
};
/**
* Checks whether the refresh
* @returns {boolean}
*/
var shouldRefresh = function () {
// Allow refresh if..
// ..It is not first request
if (requestCount !== 0) {
return true;
}
// ..we do not have any hunt results
var lastHuntResult = filterStorage.getStorage().getItem(lastHuntResult),
lastHuntTime = filterStorage.getStorage().getItem(lastHuntTime);
if (!lastHuntResult || !lastHuntTime) {
return true;
}
// ..cache is stale
var now = moment();
var then = moment('2016-03-25 19:10:41', 'YYYY-MM-DD HH:mm:ss');
if (now.diff(then, 'minutes') >= refreshDuration) {
return true;
}
// Take the content from cache and put it in place
// Reset the requestCount
// .......
return false;
};
/**
* Fetches the trending repositories based upon the filters applied
* @returns {boolean}
*/
var fetchTrendingRepos = function () {
// If there is some request, already in progress or there was
// an error, do not allow further requests.
if ((trendingRequest !== false) || ($('.error-quote').length !== 0)) {
return false;
}
if(shouldRefresh() === false) {
return false;
}
var filters = getApiFilters(),
url = reposApiUrl + filters.queryParams;
trendingRequest = $.ajax({
url: url,
method: 'get',
beforeSend: function () {
$('.loading-more').removeClass('hide');
},
success: function (data) {
var finalHtml = generateReposHtml(data.items, filters.dateRange.lower, filters.dateRange.upper);
$(mainContainer).append(finalHtml);
},
error: function(xhr, status, error) {
var error = JSON.parse(xhr.responseText),
message = error.message || '';
if (message && message.toLowerCase() == 'bad credentials') {
$('.main-content').replaceWith('<h3 class="quote-item error-quote">Oops! Seems to be a problem with your API token. Could you verify the API token you entered in extension options.</h3>');
// Reset the token
filterStorage.getStorage().removeItem(tokenStorageKey);
} else if (message && (message.indexOf('rate limit') !== -1)) {
$('.main-content').replaceWith('<h3 class="quote-item error-quote">Oops! Seems like you did not set the API token. Wait another hour for github to refresh your rate limit or better add a token in `Githunt Options` to hunt more.</h3>');
} else {
$('.main-content').replaceWith('Oops! Could you please refresh the page.');
}
},
complete: function () {
trendingRequest = false;
$('.loading-more').addClass('hide');
saveHuntResult();
}
});
};
/**
* Perform all the UI bindings
*/
var bindUI = function () {
// Bind the scroll to fetch repositories when bottom reached
$(window).on('scroll', function () {
if ($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
fetchTrendingRepos();
}
});
// On change of repository filters
$(document).on('change', filterSelector, function () {
// Remove the existing fetches repositories
$(repoGroupSelector).remove();
// Persist the filters
filterStorage.persistFilters(filterSelector);
// Refresh the repositories
fetchTrendingRepos();
});
};
return {
/**
* initialize the hub page
*/
init: function () {
bindUI();
this.refresh();
},
/**
* Refresh the listing and filters
*/
refresh: function () {
filterStorage.populateFilters(filterSelector);
fetchTrendingRepos();
}
};
}
$(function () {
var hubTab = new HubTab();
hubTab.init();
particlesJS.load('particles-js', 'js/particles.json', function () {
});
});
|