-
Notifications
You must be signed in to change notification settings - Fork 0
/
google.js
90 lines (79 loc) · 2.62 KB
/
google.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
"use strict";
// Google.js
var Search = require('./search');
var Error = require('./errors');
var extend = require('./extend');
var random = require('./random');
var Google = function (keys, config) {
var _config, _search;
// Constructor
function Google(keys, config) {
if (!(this instanceof Google)) {
return new Google(keys,config);
}
var defaults = {
"count": 200
};
_config = extend(defaults, config || {});
_search = new Search(keys || [], _config, function (query, nsfw, key) {
return {
url: 'https://www.googleapis.com/customsearch/v1'
+ '?q=' + encodeURIComponent(query)
+ '&searchType=image'
+ '&safe=' + ((nsfw || false) ? 'off' : 'high')
+ '&filter=1'
+ '&key=' + key
+ '&cx=' + _config["engine"]
};
});
}
Google.prototype.getImageData = function (query, nsfw, success, error) {
if (typeof nsfw === "function") {
error = success;
success = nsfw;
nsfw = undefined;
}
var onSuccess = function(result){
var data = result["data"];
if (data && data["items"]) {
var items = data["items"];
if (typeof items === "object" && Array.isArray(items)) {
var max = Math.min(_config["count"], items.length);
if (max == 0) {
error({
status: 1,
message: Error.message(Error.no_results)
});
return;
}
var image = items[random.randomInt(0, max)];
if (image !== undefined) {
success({
contentUrl: image["link"],
name: image["title"]
});
return;
}
}
}
error({
status: 1,
message: Error.message(Error.empty_response)
});
};
var onError = function(err){
error({
status: 1,
message: Error.message(err["status"])
});
};
_search.queryApi(query, nsfw, onSuccess, onError);
};
return new Google(keys, config);
};
var exports = module.exports = Google;
/*var test = Google(["AIzaSyBWWUNm5nuTg1TZzqRjPV81gIGpHObiu-E"],{"engine":"003902443275155350118:lty-b98cdnm"});
test.getImageData("test",function(data){
console.log(data);
});
*/