This repository has been archived by the owner on Nov 14, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathserver.js
766 lines (727 loc) · 23.7 KB
/
server.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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
var camp = require('camp').start({
documentRoot: __dirname,
port: +process.env.PORT||+process.argv[2]||80
});
var https = require('https');
var http = require('http');
var badge = require('./badge.js');
var svg2img = require('./svg-to-img.js');
var serverStartTime = new Date((new Date()).toGMTString());
// Analytics
var lastDay = (new Date()).getDate();
function resetMonthlyAnalytics(monthlyAnalytics) {
for (var i = 0; i < monthlyAnalytics.length; i++) {
monthlyAnalytics[i] = 0;
}
}
function incrMonthlyAnalytics(monthlyAnalytics) {
var currentDay = (new Date()).getDate();
// If we changed month, reset empty days.
while (lastDay !== currentDay) {
// Assumption: at least a hit a month.
lastDay = (lastDay + 1) % monthlyAnalytics.length;
monthlyAnalytics[lastDay] = 0;
}
monthlyAnalytics[currentDay]++;
}
// In case something happens on the 36th.
var vendorMonthlyAnalytics = new Array(36);
var rawMonthlyAnalytics = new Array(36);
resetMonthlyAnalytics(vendorMonthlyAnalytics);
resetMonthlyAnalytics(rawMonthlyAnalytics);
camp.ajax.on('analytics/v1', function(json, end) {
end({ vendorMonthly: vendorMonthlyAnalytics,
rawMonthly: rawMonthlyAnalytics });
});
// Cache
var cacheTimeout = 60000; // 1 minute.
var cacheFromIndex = Object.create(null);
function cache(f) {
return function getRequest(data, match, end, ask) {
// Cache management - no cache, so it won't be cached by GitHub's CDN.
ask.res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
incrMonthlyAnalytics(vendorMonthlyAnalytics);
var cacheIndex = match[0] + '?label=' + data.label;
// Should we return the data right away?
var cached = cacheFromIndex[cacheIndex];
if (cached != null) {
badge(cached.badgeData, makeSend(cached.format, ask.res, end));
return;
}
f(data, match, function sendBadge(format, badgeData) {
cacheFromIndex[cacheIndex] = { format: format, badgeData: badgeData };
setTimeout(function clearCache() {
delete cacheFromIndex[cacheIndex];
}, cacheTimeout);
badge(badgeData, makeSend(format, ask.res, end));
});
};
}
// Vendors.
// Travis integration
camp.route(/^\/travis(-ci)?\/([^\/]+\/[^\/]+)(?:\/(.+))?\.(svg|png|gif|jpg)$/,
cache(function(data, match, sendBadge) {
var userRepo = match[2];
var branch = match[3];
var format = match[4];
var options = {
method: 'HEAD',
hostname: 'api.travis-ci.org',
path: '/' + userRepo + '.png'
};
if (branch) {
options.path += '?branch=' + branch;
}
var label = getLabel('build', data);
var badgeData = {text:[label, 'n/a'], colorscheme:'lightgrey'};
var req = https.request(options, function(res) {
try {
var statusMatch = res.headers['content-disposition']
.match(/filename="(.+)\.png"/);
} catch(e) {
badgeData.text[1] = 'not found';
sendBadge(format, badgeData);
return;
}
if (!statusMatch) {
badgeData.text[1] = 'unknown';
sendBadge(format, badgeData);
return;
}
var state = statusMatch[1];
badgeData.text[1] = state;
if (state === 'passing') {
badgeData.colorscheme = 'brightgreen';
} else if (state === 'failing') {
badgeData.colorscheme = 'red';
}
sendBadge(format, badgeData);
});
req.on('error', function(e) {
badgeData.text[1] = 'inaccessible';
sendBadge(format, badgeData);
});
req.end();
}));
// Gittip integration.
camp.route(/^\/gittip\/(.*)\.(svg|png|gif|jpg)$/,
cache(function(data, match, sendBadge) {
var user = match[1]; // eg, `JSFiddle`.
var format = match[2];
var apiUrl = 'https://www.gittip.com/' + user + '/public.json';
var label = getLabel('tips', data);
var badgeData = {text:[label, 'n/a'], colorscheme:'lightgrey'};
var redirectCount = 0;
https.get(apiUrl, function dealWithData(res) {
// Is it a redirection?
if (res.statusCode === 302 && res.headers.location && redirectCount++ < 1) {
https.get('https://www.gittip.com/' + res.headers.location, dealWithData);
return;
}
var buffer = '';
res.on('data', function(chunk) { buffer += ''+chunk; });
res.on('end', function(chunk) {
if (chunk) { buffer += ''+chunk; }
try {
var data = JSON.parse(buffer);
var money = parseInt(data.receiving);
} catch(e) {
badgeData.text[1] = 'invalid';
sendBadge(format, badgeData);
return;
}
badgeData.text[1] = '$' + metric(money) + '/week';
if (money === 0) {
badgeData.colorscheme = 'red';
} else if (money < 10) {
badgeData.colorscheme = 'yellow';
} else if (money < 100) {
badgeData.colorscheme = 'green';
} else {
badgeData.colorscheme = 'brightgreen';
}
sendBadge(format, badgeData);
});
}).on('error', function(e) {
badgeData.text[1] = 'inaccessible';
sendBadge(format, badgeData);
});
}));
// Packagist integration.
camp.route(/^\/packagist\/dm\/(.*)\.(svg|png|gif|jpg)$/,
cache(function(data, match, sendBadge) {
var userRepo = match[1]; // eg, `doctrine/orm`.
var format = match[2];
var apiUrl = 'https://packagist.org/packages/' + userRepo + '.json';
var label = getLabel('downloads', data);
var badgeData = {text:[label, 'n/a'], colorscheme:'lightgrey'};
https.get(apiUrl, function(res) {
var buffer = '';
res.on('data', function(chunk) { buffer += ''+chunk; });
res.on('end', function(chunk) {
if (chunk) { buffer += ''+chunk; }
try {
var data = JSON.parse(buffer);
var monthly = data.package.downloads.monthly;
} catch(e) {
badgeData.text[1] = 'invalid';
sendBadge(format, badgeData);
return;
}
badgeData.text[1] = metric(monthly) + '/month';
if (monthly === 0) {
badgeData.colorscheme = 'red';
} else if (monthly < 10) {
badgeData.colorscheme = 'yellow';
} else if (monthly < 100) {
badgeData.colorscheme = 'yellowgreen';
} else if (monthly < 1000) {
badgeData.colorscheme = 'green';
} else {
badgeData.colorscheme = 'brightgreen';
}
sendBadge(format, badgeData);
});
}).on('error', function(e) {
badgeData.text[1] = 'inaccessible';
sendBadge(format, badgeData);
});
}));
// Packagist version integration.
camp.route(/^\/packagist\/v\/(.*)\.(svg|png|gif|jpg)$/,
cache(function(data, match, sendBadge) {
var userRepo = match[1];
var format = match[2];
var apiUrl = 'https://packagist.org/packages/' + userRepo + '.json';
var label = getLabel('packagist', data);
var badgeData = {text:[label, 'n/a'], colorscheme:'lightgrey'};
https.get(apiUrl, function(res) {
var buffer = '';
res.on('data', function(chunk) { buffer += ''+chunk; });
res.on('end', function(chunk) {
if (chunk) { buffer += ''+chunk; }
try {
var data = JSON.parse(buffer);
var version;
var unstable = function(ver) {
return /dev/.test(ver);
};
// Grab the latest stable version, or an unstable
for (var v in data.package.versions) {
v = data.package.versions[v];
if (version) {
if (/dev/.test(version.version) && !/dev/.test(v.version)) {
version = v;
} else if (version.version_normalized < v.version_normalized) {
version = v;
}
} else {
version = v;
}
}
version = version.version.replace(/^v/, "");
} catch(e) {
badgeData.text[1] = 'invalid';
sendBadge(format, badgeData);
return;
}
badgeData.text[1] = version;
if (/^\d/.test(badgeData.text[1])) {
badgeData.text[1] = 'v' + version;
}
if (version[0] === '0' || /dev/.test(version)) {
badgeData.colorscheme = 'orange';
} else {
badgeData.colorscheme = 'blue';
}
sendBadge(format, badgeData);
});
}).on('error', function(e) {
badgeData.text[1] = 'inaccessible';
sendBadge(format, badgeData);
});
}));
// NPM integration.
camp.route(/^\/npm\/dm\/(.*)\.(svg|png|gif|jpg)$/,
cache(function(data, match, sendBadge) {
var user = match[1]; // eg, `localeval`.
var format = match[2];
var apiUrl = 'http://isaacs.iriscouch.com/downloads/_design/app/_view/pkg?group_level=2&start_key=["' + user + '"]&end_key=["' + user + '",{}]';
var label = getLabel('downloads', data);
var badgeData = {text:[label, 'n/a'], colorscheme:'lightgrey'};
http.get(apiUrl, function(res) {
var buffer = '';
res.on('data', function(chunk) { buffer += ''+chunk; });
res.on('end', function(chunk) {
if (chunk) { buffer += ''+chunk; }
try {
var data = JSON.parse(buffer);
var monthly = 0;
// getMonth() returns a 0-indexed month, ie, last month.
var now = new Date();
var lastMonth = now.getMonth();
var year = now.getFullYear();
if (lastMonth === 0) { lastMonth = 12; year--; }
for (var i = 0; i < data.rows.length; i++) {
// date contains ['year', 'month', 'day'].
var date = data.rows[i].key[1].split('-');
if (+date[0] === year && +date[1] === lastMonth) {
monthly += data.rows[i].value;
}
}
} catch(e) {
badgeData.text[1] = 'invalid';
sendBadge(format, badgeData);
return;
}
badgeData.text[1] = metric(monthly) + '/month';
if (monthly === 0) {
badgeData.colorscheme = 'red';
} else if (monthly < 10) {
badgeData.colorscheme = 'yellow';
} else if (monthly < 100) {
badgeData.colorscheme = 'yellowgreen';
} else if (monthly < 1000) {
badgeData.colorscheme = 'green';
} else {
badgeData.colorscheme = 'brightgreen';
}
sendBadge(format, badgeData);
});
}).on('error', function(e) {
badgeData.text[1] = 'inaccessible';
sendBadge(format, badgeData);
});
}));
// NPM version integration.
camp.route(/^\/npm\/v\/(.*)\.(svg|png|gif|jpg)$/,
cache(function(data, match, sendBadge) {
var repo = match[1]; // eg, `localeval`.
var format = match[2];
var apiUrl = 'https://registry.npmjs.org/' + repo + '/latest';
var label = getLabel('npm', data);
var badgeData = {text:[label, 'n/a'], colorscheme:'lightgrey'};
https.get(apiUrl, function(res) {
var buffer = '';
res.on('data', function(chunk) { buffer += ''+chunk; });
res.on('end', function(chunk) {
if (chunk) { buffer += ''+chunk; }
try {
var data = JSON.parse(buffer);
var version = data.version;
} catch(e) {
badgeData.text[1] = 'invalid';
sendBadge(format, badgeData);
return;
}
badgeData.text[1] = 'v' + version;
if (version[0] === '0' || /dev/.test(version)) {
badgeData.colorscheme = 'orange';
} else {
badgeData.colorscheme = 'blue';
}
sendBadge(format, badgeData);
});
}).on('error', function(e) {
badgeData.text[1] = 'inaccessible';
sendBadge(format, badgeData);
});
}));
// Gem version integration.
camp.route(/^\/gem\/v\/(.*)\.(svg|png|gif|jpg)$/,
cache(function(data, match, sendBadge) {
var repo = match[1]; // eg, `localeval`.
var format = match[2];
var apiUrl = 'https://rubygems.org/api/v1/gems/' + repo + '.json';
var label = getLabel('gem', data);
var badgeData = {text:[label, 'n/a'], colorscheme:'lightgrey'};
https.get(apiUrl, function(res) {
var buffer = '';
res.on('data', function(chunk) { buffer += ''+chunk; });
res.on('end', function(chunk) {
if (chunk) { buffer += ''+chunk; }
try {
var data = JSON.parse(buffer);
var version = data.version;
} catch(e) {
badgeData.text[1] = 'invalid';
sendBadge(format, badgeData);
return;
}
badgeData.text[1] = 'v' + version;
if (version[0] === '0' || /dev/.test(version)) {
badgeData.colorscheme = 'orange';
} else {
badgeData.colorscheme = 'blue';
}
sendBadge(format, badgeData);
});
}).on('error', function(e) {
badgeData.text[1] = 'inaccessible';
sendBadge(format, badgeData);
});
}));
// PyPI integration.
camp.route(/^\/pypi\/([^\/]+)\/(.*)\.(svg|png|gif|jpg)$/,
cache(function(data, match, sendBadge) {
var info = match[1];
var egg = match[2]; // eg, `gevent`.
var format = match[3];
var apiUrl = 'https://pypi.python.org/pypi/' + egg + '/json';
var label = getLabel('pypi', data);
var badgeData = {text:[label, 'n/a'], colorscheme:'lightgrey'};
https.get(apiUrl, function(res) {
var buffer = '';
res.on('data', function(chunk) { buffer += ''+chunk; });
res.on('end', function(chunk) {
if (chunk) { buffer += ''+chunk; }
try {
var data = JSON.parse(buffer);
} catch(e) {
badgeData.text[1] = 'invalid';
sendBadge(format, badgeData);
return;
}
if (info === 'dm') {
badgeData.text[0] = getLabel('downloads', data);
try {
var monthly = data.info.downloads.last_month;
} catch(e) {
badgeData.text[1] = 'invalid';
sendBadge(format, badgeData);
return;
}
badgeData.text[1] = metric(monthly) + '/month';
if (monthly === 0) {
badgeData.colorscheme = 'red';
} else if (monthly < 10) {
badgeData.colorscheme = 'yellow';
} else if (monthly < 100) {
badgeData.colorscheme = 'yellowgreen';
} else if (monthly < 1000) {
badgeData.colorscheme = 'green';
} else {
badgeData.colorscheme = 'brightgreen';
}
sendBadge(format, badgeData);
} else if (info === 'v') {
try {
var version = data.info.version;
} catch(e) {
badgeData.text[1] = 'invalid';
sendBadge(format, badgeData);
return;
}
badgeData.text[1] = 'v' + version;
if (version[0] === '0' || /dev/.test(version)) {
badgeData.colorscheme = 'orange';
} else {
badgeData.colorscheme = 'blue';
}
sendBadge(format, badgeData);
}
});
}).on('error', function(e) {
badgeData.text[1] = 'inaccessible';
sendBadge(format, badgeData);
});
}));
// Coveralls integration.
camp.route(/^\/coveralls\/([^\/]+\/[^\/]+)(?:\/(.+))?\.(svg|png|gif|jpg)$/,
cache(function(data, match, sendBadge) {
var userRepo = match[1]; // eg, `jekyll/jekyll`.
var branch = match[2];
var format = match[3];
var apiUrl = 'https://coveralls.io/repos/' + userRepo + '/badge.png';
if (branch) {
apiUrl += '?branch=' + branch;
}
var label = getLabel('coverage', data);
var badgeData = {text:[label, 'n/a'], colorscheme:'lightgrey'};
https.get(apiUrl, function(res) {
// We should get a 302. Look inside the Location header.
var buffer = res.headers.location;
if (!buffer) {
badgeData.text[1] = 'invalid';
sendBadge(format, badgeData);
return;
}
try {
var score = buffer.split('_')[1].split('.')[0];
var percentage = parseInt(score);
if (percentage !== percentage) {
// It is NaN, treat it as unknown.
badgeData.text[1] = 'unknown';
sendBadge(format, badgeData);
return;
}
} catch(e) {
badgeData.text[1] = 'malformed';
sendBadge(format, badgeData);
return;
}
badgeData.text[1] = score + '%';
if (percentage < 80) {
badgeData.colorscheme = 'red';
} else if (percentage < 90) {
badgeData.colorscheme = 'yellow';
} else if (percentage < 95) {
badgeData.colorscheme = 'green';
} else {
badgeData.colorscheme = 'brightgreen';
}
sendBadge(format, badgeData);
}).on('error', function(e) {
badgeData.text[1] = 'inaccessible';
sendBadge(format, badgeData);
});
}));
// Code Climate integration
camp.route(/^\/codeclimate\/(.+)\.(svg|png|gif|jpg)$/,
cache(function(data, match, sendBadge) {
var userRepo = match[1]; // eg, `github/kabisaict/flow`.
var format = match[2];
var options = {
method: 'HEAD',
hostname: 'codeclimate.com',
path: '/' + userRepo + '.png'
};
var label = getLabel('code climate', data);
var badgeData = {text:[label, 'n/a'], colorscheme:'lightgrey'};
var req = https.request(options, function(res) {
try {
var statusMatch = res.headers['content-disposition']
.match(/filename="code_climate-(.+)\.png"/);
} catch(e) {
badgeData.text[1] = 'not found';
sendBadge(format, badgeData);
return;
}
if (!statusMatch) {
badgeData.text[1] = 'unknown';
sendBadge(format, badgeData);
return;
}
var state = statusMatch[1].replace('-', '.');
var score = +state;
badgeData.text[1] = state;
if (score == 4) {
badgeData.colorscheme = 'brightgreen';
} else if (score > 3) {
badgeData.colorscheme = 'green';
} else if (score > 2) {
badgeData.colorscheme = 'yellowgreen';
} else if (score > 1) {
badgeData.colorscheme = 'yellow';
} else {
badgeData.colorscheme = 'red';
}
sendBadge(format, badgeData);
});
req.on('error', function(e) {
badgeData.text[1] = 'inaccessible';
sendBadge(format, badgeData);
});
req.end();
}));
// Code Climate integration
camp.route(/^\/gemnasium\/(.+)\.(svg|png|gif|jpg)$/,
cache(function(data, match, sendBadge) {
var userRepo = match[1]; // eg, `jekyll/jekyll`.
var format = match[2];
var options = {
method: 'HEAD',
hostname: 'gemnasium.com',
path: '/' + userRepo + '.png'
};
var label = getLabel('dependencies', data);
var badgeData = {text:[label, 'n/a'], colorscheme:'lightgrey'};
var req = https.request(options, function(res) {
try {
var statusMatch = res.headers['content-disposition']
.match(/filename="(.+)\.png"/);
} catch(e) {
badgeData.text[1] = 'not found';
sendBadge(format, badgeData);
return;
}
if (!statusMatch) {
badgeData.text[1] = 'unknown';
sendBadge(format, badgeData);
return;
}
// Either `dev-yellow` or `yellow`.
var state = statusMatch[1].split('-'); //
var color = state.pop();
if (state[0] === 'dev') { badgeData.text[0] = 'devDependencies'; }
if (color === 'green') {
badgeData.text[1] = 'up-to-date';
badgeData.colorscheme = 'brightgreen';
} else if (color === 'yellow') {
badgeData.text[1] = 'out-of-date';
badgeData.colorscheme = 'yellow';
} else if (color === 'red') {
badgeData.text[1] = 'update!';
badgeData.colorscheme = 'red';
} else if (color === 'none') {
badgeData.text[1] = 'none';
badgeData.colorscheme = 'brightgreen';
} else {
badgeData.text[1] = 'undefined';
}
sendBadge(format, badgeData);
});
req.on('error', function(e) {
badgeData.text[1] = 'inaccessible';
sendBadge(format, badgeData);
});
req.end();
}));
// Hackage version integration.
camp.route(/^\/hackage\/v\/(.*)\.(svg|png|gif|jpg)$/,
cache(function(data, match, sendBadge) {
var repo = match[1]; // eg, `lens`.
var format = match[2];
var apiUrl = 'https://hackage.haskell.org/package/' + repo + '/' + repo + '.cabal';
var label = getLabel('hackage', data);
var badgeData = {text:[label, 'n/a'], colorscheme:'lightgrey'};
https.get(apiUrl, function(res) {
var buffer = '';
res.on('data', function(chunk) { buffer += ''+chunk; });
res.on('end', function(chunk) {
if (chunk) { buffer += ''+chunk; }
try {
var lines = buffer.split("\n");
var versionLines = lines.filter(function(e) {
return (/^version:/i).test(e) === true;
});
// We don't have to check length of versionLines, because if we throw,
// we'll render the 'invalid' badge below, which is the correct thing
// to do.
var version = versionLines[0].replace(/\s+/, '').split(/:/)[1];
} catch(e) {
badgeData.text[1] = 'invalid';
sendBadge(format, badgeData);
return;
}
badgeData.text[1] = 'v' + version;
if (version[0] === '0') {
badgeData.colorscheme = 'orange';
} else {
badgeData.colorscheme = 'blue';
}
sendBadge(format, badgeData);
});
}).on('error', function(e) {
badgeData.text[1] = 'inaccessible';
sendBadge(format, badgeData);
});
}));
// Any badge.
camp.route(/^\/(:|badge\/)(([^-]|--)+)-(([^-]|--)+)-(([^-]|--)+)\.(svg|png|gif|jpg)$/,
function(data, match, end, ask) {
var subject = escapeFormat(match[2]);
var status = escapeFormat(match[4]);
var color = escapeFormat(match[6]);
var format = match[8];
incrMonthlyAnalytics(rawMonthlyAnalytics);
// Cache management - the badge is constant.
var cacheDuration = (3600*24*1)|0; // 1 day.
ask.res.setHeader('Cache-Control', 'public, max-age=' + cacheDuration);
if (+(new Date(ask.req.headers['if-modified-since'])) >= +serverStartTime) {
ask.res.statusCode = 304;
ask.res.end(); // not modified.
return;
}
ask.res.setHeader('Last-Modified', serverStartTime.toGMTString());
// Badge creation.
try {
var badgeData = {text: [subject, status]};
if (sixHex(color)) {
badgeData.colorB = '#' + color;
} else {
badgeData.colorscheme = color;
}
badge(badgeData, makeSend(format, ask.res, end));
} catch(e) {
badge({text: ['error', 'bad badge'], colorscheme: 'red'},
makeSend(format, ask.res, end));
}
});
// Any badge, old version.
camp.route(/^\/([^\/]+)\/(.+).png$/,
function(data, match, end, ask) {
var subject = match[1];
var status = match[2];
var color = data.color;
// Cache management - the badge is constant.
var cacheDuration = (3600*24*1)|0; // 1 day.
ask.res.setHeader('Cache-Control', 'public, max-age=' + cacheDuration);
if (+(new Date(ask.req.headers['if-modified-since'])) >= +serverStartTime) {
ask.res.statusCode = 304;
ask.res.end(); // not modified.
return;
}
ask.res.setHeader('Last-Modified', serverStartTime.toGMTString());
// Badge creation.
try {
var badgeData = {text: [subject, status]};
badgeData.colorscheme = color;
badge(badgeData, makeSend('png', ask.res, end));
} catch(e) {
badge({text: ['error', 'bad badge'], colorscheme: 'red'},
makeSend('png', ask.res, end));
}
});
// Redirect the root to the website.
camp.route(/^\/$/, function(data, match, end, ask) {
ask.res.statusCode = 302;
ask.res.setHeader('Location', 'http://shields.io');
ask.res.end();
});
// Escapes `t` using the format specified in
// <https://github.com/espadrine/gh-badges/issues/12#issuecomment-31518129>
function escapeFormat(t) {
return t
// Inline single underscore.
.replace(/([^_])_([^_])/g, '$1 $2')
// Leading or trailing underscore.
.replace(/([^_])_$/, '$1 ').replace(/^_([^_])/, ' $1')
// Double underscore and double dash.
.replace(/__/g, '_').replace(/--/g, '-');
}
function sixHex(s) { return /^[0-9a-fA-F]{6}$/.test(s); }
function getLabel(label, data) {
return data.label || label;
}
function makeSend(format, askres, end) {
if (format === 'svg') {
return function(res) { sendSVG(res, askres, end); };
} else {
return function(res) { sendOther(format, res, askres, end); };
}
}
function sendSVG(res, askres, end) {
askres.setHeader('Content-Type', 'image/svg+xml;charset=utf-8');
end(null, {template: streamFromString(res)});
}
function sendOther(format, res, askres, end) {
askres.setHeader('Content-Type', 'image/' + format);
svg2img(res, format, askres);
}
var stream = require('stream');
function streamFromString(str) {
var newStream = new stream.Readable();
newStream._read = function() { newStream.push(str); newStream.push(null); };
return newStream;
}
// Given a number, string with appropriate unit in the metric system, SI.
function metric(n) {
var limit = 1000;
if (n > limit) {
n = Math.round(n / 1000);
return ''+n + 'k';
} else {
return ''+n;
}
}