-
Notifications
You must be signed in to change notification settings - Fork 0
/
cartoon.js
85 lines (75 loc) · 2.13 KB
/
cartoon.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
var http = require('http');
var url = require('url');
var fs = require('fs');
var mkdirp = require('mkdirp');
var SCRIPTURL = 'http://www.dagbladet.no/tegneserie/pondusarkiv/serveconfig.php?';
var STRIPROOT = './strips/';
var GUESTFOLDER = STRIPROOT+'gjesteserie/';
var STRIP = process.argv[2];
var STRIPNAME = STRIP;
var isGuestSeries = false;
if (STRIP == null) {
console.log('ERROR: Pass in the name of the strip');
process.exit(0);
} else {
if (STRIP.indexOf('gjesteserie') >= 0) {
isGuestSeries = true;
STRIPNAME = STRIP.substring(STRIP.indexOf('/')+1);
}
}
var date = new Date();
var reqUrl = SCRIPTURL + 'date=' + getTime(date) + '&strip=' + STRIP;
var filename = getFilename(date);
getCartoonLocation(reqUrl);
function getCartoonLocation(url) {
http.get(url, function(res) {
var location = res.headers.location;
if (location) {
getCartoonData(location);
} else {
console.log('ERROR: Could not find location header');
}
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
}
function getCartoonData(rawUrl) {
var urlObj = url.parse(rawUrl);
console.log(urlObj);
http.get(urlObj, function(res) {
if (isGuestSeries) {
mkdirp(GUESTFOLDER+STRIPNAME, function() {
writeData(res, GUESTFOLDER+STRIPNAME);
});
} else {
mkdirp(STRIPROOT+STRIPNAME, function() {
writeData(res, STRIPROOT+STRIP);
});
}
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
}
function writeData(res, filepath) {
var file = fs.createWriteStream(filepath + '/' + filename);
res.on('data', function(data) {
file.write(data);
}).on('end', function() {
file.end();
console.log(filename + ' downloaded');
});
}
function getTime(date) {
date = date.getTime() / 1000;
return Math.floor(date);
}
function getFilename(dateObj) {
var filename = dateObj.getFullYear() + '.';
var month = dateObj.getMonth()+1;
filename += month < 10 ? '0'+month : month;
filename += '.';
var dateInMonth = dateObj.getDate();
filename += dateInMonth < 10 ? '0'+dateInMonth : dateInMonth;
filename += '.png';
return filename;
}