-
Notifications
You must be signed in to change notification settings - Fork 1
/
VkApi.js
94 lines (75 loc) · 1.87 KB
/
VkApi.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
'use strict';
const Promise = require('bluebird');
const lib = require('./lib');
const fs = Promise.promisifyAll(require('fs'));
const vkApiUrl = 'https://api.vk.com/method';
class VkApi {
constructor(token) {
this._token = token;
};
apiRequest(method, opts) {
opts = opts || {};
const requestData = {
uri : `${vkApiUrl}/${method}`,
method : 'post',
};
const form = opts.data || {};
form['access_token'] = this._token;
requestData['form'] = form;
if (opts.onProgress) {
requestData[onProgress] = opts.onProgress;
}
return lib.rp(requestData);
};
async getuploadUrl() {
const result = await this.apiRequest('docs.getUploadServer');
return JSON.parse(result).response.upload_url;
};
async sendFile(opts) {
const stat = await fs.statAsync(opts.file);
const reqData = {
uri : opts.url,
method : 'post',
formData : {
file : fs.createReadStream(opts.file),
},
};
if (opts.onProgress) {
reqData.onProgress = (sent, speed) => {
const percent = lib.roundToPlace(sent * 100 / stat.size, 2);
const mbSent = lib.roundToPlace(sent / Math.pow(2, 20), 2);
const mbSize = lib.roundToPlace(stat.size / Math.pow(2, 20), 2);
opts.onProgress({
percent,
mbSent,
mbSize,
speed
});
};
}
const uploadResult = await lib.rp(reqData);
try {
const jsonRes = JSON.parse(uploadResult);
return jsonRes.file;
} catch (error) {
console.log(error, uploadResult);
}
};
saveFile(opts) {
if (!opts.uploadFile) {
throw new Error("error while uploading gif");
}
const data = {
file : opts.uploadFile,
title : opts.title,
};
if (opts.captcha) {
data.captcha_sid = opts.captcha.sid;
data.captcha_key = opts.captcha.answer;
}
return this.apiRequest('docs.save', {
data : data
});
};
}
module.exports = VkApi;