-
Notifications
You must be signed in to change notification settings - Fork 0
/
bing.js
85 lines (76 loc) · 2.61 KB
/
bing.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
"use strict";
// bing.js
var Search = require('./search');
var Error = require('./errors');
var extend = require('./extend');
var random = require('./random');
var Bing = function (keys, config) {
var _config, _search;
// Constructor
function Bing(keys, config) {
if (!(this instanceof Bing)) {
return new Bing(keys);
}
var defaults = {
"count": 1000,
"market": 'en-en'
};
_config = extend(defaults, config || {});
_search = new Search(keys || [], _config, function (query, nsfw, key) {
return {
url: 'https://api.cognitive.microsoft.com/bing/v5.0/images/search'
+ '?q=' + encodeURIComponent(query)
+ '&count=' + _config["count"]
+ '&offset=0'
+ '&mkt=' + _config["market"]
+ '&safeSearch=' + ((nsfw || false) ? 'Off' : 'Moderate'),
headers : {"Ocp-Apim-Subscription-Key": key}
};
});
}
Bing.prototype.getImageData = function (query, nsfw, success, error) {
if (typeof nsfw === "function") {
error = success;
success = nsfw;
nsfw = undefined;
}
var onSuccess = function(result){
var ok = false;
var data = result["data"];
if (data && data["value"]) {
var value = data["value"];
if (typeof value === "object" && Array.isArray(value)) {
var max = Math.min(_config["count"], value.length);
if (max == 0) {
error({
status: 1,
message: Error.message(Error.no_results)
});
return;
}
var image = value[random.randomInt(0, max)];
if (image !== undefined && image["contentUrl"] != undefined){
success({
contentUrl: image["contentUrl"],
name: image["name"]
});
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 Bing(keys, config);
};
var exports = module.exports = Bing;