|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +var _defineProperty = require("@babel/runtime/helpers/defineProperty"); |
| 4 | +var axios = require('axios'); |
| 5 | +var tool = require('./tool'); |
| 6 | +class WPush { |
| 7 | + constructor({ |
| 8 | + token, |
| 9 | + key, |
| 10 | + proxy |
| 11 | + }) { |
| 12 | + _defineProperty(this, "_KEY", void 0); |
| 13 | + _defineProperty(this, "baseURL", 'https://api.wpush.cn/api/v1/send'); |
| 14 | + _defineProperty(this, "httpsAgent", void 0); |
| 15 | + const $key = { |
| 16 | + token, |
| 17 | + ...key |
| 18 | + }; |
| 19 | + if (!$key.token) { |
| 20 | + throw new Error('Missing Parameter: token'); |
| 21 | + } |
| 22 | + this._KEY = $key.token; |
| 23 | + if (proxy && proxy.enable) { |
| 24 | + this.httpsAgent = tool.proxy2httpsAgent(proxy); |
| 25 | + } |
| 26 | + } |
| 27 | + async send(sendOptions) { |
| 28 | + if (!sendOptions.message && !sendOptions.customOptions) { |
| 29 | + return { |
| 30 | + status: 0, |
| 31 | + statusText: 'Missing Parameter: message', |
| 32 | + extraMessage: null |
| 33 | + }; |
| 34 | + } |
| 35 | + let wPushOptions; |
| 36 | + if (sendOptions.customOptions) { |
| 37 | + wPushOptions = sendOptions.customOptions; |
| 38 | + } else { |
| 39 | + wPushOptions = { |
| 40 | + title: sendOptions.title || sendOptions.message.split('\n')[0].trim().slice(0, 10), |
| 41 | + content: sendOptions.message |
| 42 | + }; |
| 43 | + } |
| 44 | + wPushOptions.apikey = this._KEY; |
| 45 | + if (sendOptions.extraOptions) { |
| 46 | + wPushOptions = { |
| 47 | + ...wPushOptions, |
| 48 | + ...sendOptions.extraOptions |
| 49 | + }; |
| 50 | + } |
| 51 | + const axiosOptions = { |
| 52 | + url: `${this.baseURL}`, |
| 53 | + method: 'POST', |
| 54 | + headers: { |
| 55 | + 'Content-type': 'application/json' |
| 56 | + }, |
| 57 | + data: wPushOptions |
| 58 | + }; |
| 59 | + if (this.httpsAgent) { |
| 60 | + axiosOptions.httpsAgent = this.httpsAgent; |
| 61 | + } |
| 62 | + return axios(axiosOptions).then(response => { |
| 63 | + if (response.data) { |
| 64 | + if (response.data.code === 0) { |
| 65 | + return { |
| 66 | + status: 200, |
| 67 | + statusText: 'Success', |
| 68 | + extraMessage: response |
| 69 | + }; |
| 70 | + } |
| 71 | + return { |
| 72 | + status: 100, |
| 73 | + statusText: 'Error', |
| 74 | + extraMessage: response |
| 75 | + }; |
| 76 | + } |
| 77 | + return { |
| 78 | + status: 101, |
| 79 | + statusText: 'No Response Data', |
| 80 | + extraMessage: response |
| 81 | + }; |
| 82 | + }).catch(error => ({ |
| 83 | + status: 102, |
| 84 | + statusText: 'Request Error', |
| 85 | + extraMessage: error |
| 86 | + })); |
| 87 | + } |
| 88 | +} |
| 89 | +exports.WPush = WPush; |
0 commit comments