This repository has been archived by the owner on Apr 4, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathindex.js
79 lines (66 loc) · 1.99 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
const fs = require('fs')
const https = require('https')
const stream = require('stream')
const querystring = require('querystring')
const FormData = require('form-data')
const fileType = require('file-type')
exports = module.exports = fnProto(function SauceNAO(...args) {
let api_key
if(new.target) {
api_key = args[0]
if(!api_key || typeof api_key !== 'string')
throw new TypeError('no api_key passed to constructor')
return fnProto(getSauce)
} else return getSauce(...args)
async function getSauce(input, options) {
let form = new FormData()
if(Object(options) === options)
for(let key in options) form.append(key, options[key])
form.append('output_type', 2)
if(api_key) form.append('api_key', api_key)
switch(true) {
case (typeof input === 'string'):
if(~input.search(/^https?:\/\//))
form.append('url', input)
else
form.append('file', fs.createReadStream(input))
break
case (input instanceof stream.Readable):
form.append('file', input)
break
case (input instanceof Buffer):
let inputType = fileType(input)
form.append('file', input, {
filename: `file.${inputType.ext}`,
contentType: inputType.mime
})
break
default: throw new TypeError('unrecognized input format')
}
let response = await new Promise((resolve, reject) => {
form.submit('https://saucenao.com/search.php', (err, res) => {
if(err) reject(err)
else resolve(res)
})
})
try {
response.body = ''
response.setEncoding('utf8')
response.on('data', chunk => response.body += chunk)
await new Promise(r => response.on('end', r))
response.json = JSON.parse(response.body)
} catch (err) {
err.response = response
throw err
}
return response
}
})
exports.prototype = {}
function fnProto(fn) {
return new Proxy(fn, {
getPrototypeOf(target) {
return exports.prototype
}
})
}