-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
114 lines (92 loc) · 2.66 KB
/
index.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
'use strict';
var request = require('request');
var dataURI = require('data-uri-to-buffer');
var RevisitValidator = function (options) {
this.url = false;
this.content = {};
this.imgBuffer = false;
if (!options) {
options = {};
}
this.maxSize = parseInt(options.maxSize, 10) || 1000000; // 1 MB
this.errors = {};
var self = this;
var validateSize = function (next) {
try {
self.imgBuffer = dataURI(self.content.data);
if (['image/jpeg', 'image/png', 'image/gif'].indexOf(self.imgBuffer.type) === -1) {
self.errors.InvalidFileType = 'This can only be a PNG, JPEG or GIF';
next();
return;
}
if (self.imgBuffer.length > self.maxSize) {
self.errors.FileTooLarge = 'This image is greater than ' +
Math.floor(self.maxSize / 1000000) + ' MB';
next();
return;
}
} catch (e) {
self.errors.InvalidDataURI = "This image isn't a valid data URI";
next();
return;
}
next();
};
var checkPost = function (next) {
request({
method: 'POST',
json: true,
url: self.url + '/service',
body: self.content
}, function (err, response, body) {
if (!body || (body && !body.content)) {
self.errors.InvalidServicePost = 'Your POST request must point to /service';
next();
return;
}
self.content = body.content;
if (!body.meta) {
self.errors.InvalidServiceMeta = 'You need to carry the `meta` object in the request';
next();
return;
} else if (!body.meta.audio) {
self.errors.InvalidServiceMetaEmtpy = 'You should not destroy incoming data from `meta`';
next();
return;
}
validateSize(next);
});
};
var checkHead = function (next) {
request({
method: 'HEAD',
url: self.url,
followAllRedirects: false,
timeout: 2000
}, function (err, response) {
if (err || !response.statusCode || response.statusCode !== 200) {
self.errors.InvalidHeadRequest = 'Cannot make a HEAD request to /';
next();
return;
}
checkPost(next);
});
};
var checkURL = function () {
if (!self.url) {
self.errors.InvalidURL = 'URL must not be empty';
} else if (self.url[self.url.length - 1] === '/') {
self.errors.InvalidTrailingSlash = 'URL cannot contain a trailing slash';
}
};
this.validate = function (next) {
this.errors = {};
checkURL();
if (!this.errors.InvalidURL && !this.errors.InvalidTrailingSlash) {
checkHead(next);
return;
}
next();
};
};
module.exports = RevisitValidator;