forked from killedbymemory/cinemascrape
/
grab-image.js
82 lines (66 loc) · 1.75 KB
/
grab-image.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
var fs = require('fs'),
path = require('path'),
request = require('request'),
qs = require('qs');
/**
* example: http://m.21cineplex.com/image_preview.php?type=movie&images=12AVES.jpg&width=100&height=147
* extract width, height, and file extension
*/
function extractImageInformation(url) {
var image = {
width: 0,
height: 0,
ext: 'jpg'
};
var params = qs.parse(url);
try {
image.width = parseInt(params.width);
image.height = parseInt(params.height);
image.ext = params.images.toLowerCase().match(/\.(?:jpg|jpeg|png)/)[0];
} catch (e) {
console.log(e.stack);
}
return image;
}
/**
* @param object movie movie detail (movie id is mandatory)
* @param object image image detail (resolution, name, extension)
*/
function storeMovieImage(movie) {
var createFile = false;
// create path
var file_path = ['images', 'movie', movie.id].join('/');
fs.mkdir(file_path, 0755, function(err){
console.log('create direktori. path: ' + file_path);
if (err) {
console.log(err);
switch (err.code) {
case 'EEXIST':
console.log('direktori sudah ada');
createFile = true;
break;
default:
console.log(err.toString());
console.log('error on mkdir');
break;
}
} else {
createFile = true;
}
if (createFile) {
file_path += '/' + [movie.id, image.width, image.height].join('_') + '.' + image.ext;
console.log('create file. path: ', file_path);
path.exists(file_path, function(exists){
if (!exists) {
console.log('file created.');
request(movie.url).pipe(fs.createWriteStream(path, {mode: 0755}));
} else {
console.log('file already exist.');
}
});
}
});
}
module.exports = storeMovieImage;
console.log(extractImageInformation(movie.url));
storeMovieImage(movie);