@icgio/icg-utils 1.6.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,94 @@
1
+ const needle = require('needle')
2
+
3
+ const coins_map = require('./coingecko-coins-map.js')
4
+ const parse_pair = require('./utils.js').parse_pair
5
+
6
+ let get_coingecko_rates = (cb, pair) => {
7
+ if (pair) {
8
+ let [cur, base_cur] = parse_pair(pair)
9
+ let cur_id = coins_map[cur], vs_cur = ['USDT', 'TUSD', 'PAX', 'BUSD', 'USDK', 'USDC', 'HUSD', 'DAI'].indexOf(base_cur) > -1 ? 'usd' : base_cur.toLowerCase()
10
+ needle.get(`https://api.coingecko.com/api/v3/simple/price?ids=${cur_id}&vs_currencies=${vs_cur}`, (err, res, body) => {
11
+ cb(body[cur_id][vs_cur])
12
+ })
13
+ return
14
+ }
15
+ let result = {}, quote_cur = 'USD', page = 1, per_page_nums = 250
16
+ let get_coingecko_rate = (page, cb) => {
17
+ needle.get('https://api.coingecko.com/api/v3/coins/markets?vs_currency=' + quote_cur.toLowerCase() + '&per_page=' + per_page_nums + '&page=' + page, (err, res, body) => {
18
+ if (body && body.length > 0) {
19
+ for (let coin of body) {
20
+ let symbol = coin.symbol
21
+ if (!symbol || !coin.current_price)
22
+ continue
23
+
24
+ symbol = symbol.toUpperCase()
25
+
26
+ if (symbol === 'BAT' && coin.id !== 'basic-attention-token')
27
+ continue
28
+ else if (symbol === 'SBTC' && coin.id !== 'super-bitcoin')
29
+ continue
30
+ // else if (coin.symbol === 'BTG' && coin.id === 'bitgem')
31
+ // continue
32
+ // else if (coin.symbol === 'BTM' && coin.id === 'bitmark')
33
+ // coin.symbol = 'BITM'
34
+ // else if (coin.symbol === 'CMT' && coin.id === 'comet')
35
+ // continue
36
+ // else if (coin.symbol === 'ICN' && coin.id === 'icoin')
37
+ // continue
38
+ // else if (coin.symbol === 'KNC' && coin.id === 'kingn-coin')
39
+ // continue
40
+ // else if (coin.symbol === 'MIOTA')
41
+ // coin.symbol = 'IOTA'
42
+ // else if (coin.symbol === 'PAI' && coin.id === 'project-pai')
43
+ // coin.symbol = 'PPAI'
44
+ // else if (coin.symbol === 'RCN' && coin.id === 'rcoin')
45
+ // continue
46
+ // else if (coin.symbol === 'ST' && coin.id === 'simple-token')
47
+ // coin.symbol = 'OST'
48
+ // else if (coin.symbol === 'TIX' && coin.id === 'tickets')
49
+ // continue
50
+ // else if (coin.symbol === 'BLZ' && coin.id === 'blazecoin')
51
+ // continue
52
+ // else if (coin.symbol === 'USNBT')
53
+ // coin.symbol = 'NBT'
54
+ // if (result[coin.symbol]) {
55
+ // console.log(coin.symbol)
56
+ // }
57
+
58
+ result[symbol] = {
59
+ 'USD': parseFloat(coin.current_price),
60
+ 'USDT': parseFloat(coin.current_price),
61
+ '24h_change': parseFloat(coin.price_change_percentage_24h),
62
+ '24h_volume_usd': parseFloat(coin.total_volume),
63
+ 'rank': parseInt(coin.market_cap_rank) || 10000,
64
+ 'market_cap': parseInt(coin.market_cap),
65
+ 'update_time': new Date(coin.last_updated)
66
+ }
67
+ }
68
+ if (!result.BTC || !result.ETH) {
69
+ setTimeout(() => { get_coingecko_rates(cb) }, 5000)
70
+ } else {
71
+ for (let cur in result) {
72
+ result[cur].BTC = result[cur].USD / result.BTC.USD
73
+ result[cur].ETH = result[cur].USD / result.ETH.USD
74
+ }
75
+ if (body.length < per_page_nums) {
76
+ cb(result)
77
+ } else {
78
+ page++
79
+ get_coingecko_rate(page, cb)
80
+ }
81
+ }
82
+ } else {
83
+ setTimeout(() => { get_coingecko_rates(cb) }, 5000)
84
+ }
85
+ })
86
+ }
87
+ get_coingecko_rate(page, cb)
88
+ }
89
+
90
+ // get_coingecko_rates((res) => {
91
+ // console.log(res)
92
+ // })
93
+
94
+ module.exports = get_coingecko_rates
@@ -0,0 +1,13 @@
1
+ const needle = require('needle')
2
+ const utils = require('./utils.js')
3
+
4
+ let get_forex_rate = function (pair, cb) {
5
+ let [cur, base_cur] = utils.parse_pair(pair)
6
+ needle.get(`http://www.apilayer.net/api/live?access_key=d679190b0d9dab9d9353f20caea4682f&source=${cur}&currencies=${base_cur}&format=1`, (err, res, body) => {
7
+ if (body.success) {
8
+ cb(body.quotes[pair])
9
+ }
10
+ })
11
+ }
12
+
13
+ module.exports.get_forex_rate = get_forex_rate
@@ -0,0 +1,62 @@
1
+ const htmlparser = require('htmlparser2')
2
+ const needle = require('needle')
3
+
4
+ function tag_parser (body, tag_name, tag_attrs, cb) {
5
+ let result = []
6
+ let parser = new htmlparser.Parser({
7
+ onopentag: (name, attrs) => {
8
+ let flag = true
9
+ for (let tag_attr in tag_attrs) {
10
+ if (!attrs[tag_attr] || tag_attrs[tag_attr] !== attrs[tag_attr])
11
+ flag = false
12
+ }
13
+ if (flag && name === tag_name) {
14
+ result.push(attrs)
15
+ }
16
+ },
17
+ onend: () => {
18
+ cb(result)
19
+ }
20
+ }, { decodeEntities: true })
21
+ parser.write(body)
22
+ parser.end()
23
+ }
24
+
25
+ function text_parser (body, include_new_line=false, cb) {
26
+ let result = []
27
+ let parser = new htmlparser.Parser({
28
+ ontext: (text) => {
29
+ if (!include_new_line && !text.startsWith('\n'))
30
+ result.push(text)
31
+ },
32
+ onend: () => {
33
+ cb(result)
34
+ }
35
+ }, { decodeEntities: true })
36
+ parser.write(body)
37
+ parser.end()
38
+ }
39
+
40
+ function html_parser (url, options, cb) {
41
+ let tag_name = options.tag_name
42
+ let tag_attrs = options.tag_attrs
43
+ let text = options.text
44
+ let text_include_new_line = options.text_include_new_line
45
+ if (tag_name && tag_attrs && text) {
46
+ console.error('unable to parse tag and text at the same time')
47
+ return
48
+ }
49
+ if (tag_name && tag_attrs) {
50
+ needle.get(url, (res, err, body) => {
51
+ tag_parser(body, tag_name, tag_attrs, cb)
52
+ })
53
+ } else if (text) {
54
+ needle.get(url, (res, err, body) => {
55
+ text_parser(body, text_include_new_line, cb)
56
+ })
57
+ } else {
58
+ console.error('wrong options')
59
+ }
60
+ }
61
+
62
+ module.exports = html_parser
@@ -0,0 +1,79 @@
1
+ const _ = require('lodash')
2
+
3
+ const InfluxDB = require('influx')
4
+
5
+ function schema_check (fields) {
6
+ let result = true
7
+ for (let key in fields) {
8
+ if (!fields[key] && fields[key] !== 0) {
9
+ result = false
10
+ }
11
+ }
12
+ return result
13
+ }
14
+
15
+ function check_points (points) {
16
+ return points.filter(point => {
17
+ if (schema_check(point.fields) && (!point.timestamp || point.timestamp instanceof Date)) {
18
+ return true
19
+ } else {
20
+ console.error(point)
21
+ return false
22
+ }
23
+ })
24
+ }
25
+
26
+ module.exports = class Influx {
27
+ constructor (config) {
28
+ let config_db = {
29
+ host: config.server,
30
+ database: config.database
31
+ }
32
+ if (config.schema) {
33
+ config_db.schema = config.schema
34
+ }
35
+ if (config.password) {
36
+ config_db.username = config.user || config.username
37
+ config_db.password = config.password
38
+ }
39
+ this.db = new InfluxDB.InfluxDB(config_db)
40
+ this.database = config.database
41
+ this.database_exist = false
42
+ }
43
+ static get FLOAT() { return InfluxDB.FieldType.FLOAT }
44
+ static get INTEGER() { return InfluxDB.FieldType.INTEGER }
45
+ static get STRING() { return InfluxDB.FieldType.STRING }
46
+ static get BOOLEAN() { return InfluxDB.FieldType.BOOLEAN }
47
+ query(query_string, cb) {
48
+ this.db.query(query_string).then(res => {
49
+ res.map(e => {
50
+ e.date = new Date(e.time.toNanoISOString())
51
+ return e
52
+ })
53
+ cb ({ success: true, body: res })
54
+ }).catch(err => {
55
+ cb ({ success: false, error: err })
56
+ })
57
+ }
58
+ write_points_with_check (points, cb) {
59
+ if (!this.database_exist) {
60
+ this.db.getDatabaseNames().then(res => {
61
+ if (res.indexOf(this.database) === -1) {
62
+ this.db.createDatabase(this.database).then(res => {
63
+ this.database_exist = true
64
+ })
65
+ } else {
66
+ this.database_exist = true
67
+ }
68
+ })
69
+ } else if (check_points(points)) {
70
+ this.db.writePoints(points).then(res => {
71
+ cb ({ success: true, body: res })
72
+ }).catch(err => {
73
+ cb ({ success: false, error: err })
74
+ })
75
+ } else {
76
+ cb ({ success: false, error: 'points-error' })
77
+ }
78
+ }
79
+ }
package/lib/logger.js ADDED
@@ -0,0 +1,40 @@
1
+ const winston = require('winston')
2
+ const Papertrail = require('winston-papertrail').Papertrail
3
+
4
+ let logger = new(winston.Logger)({
5
+ levels: {
6
+ error: 0,
7
+ warn: 1,
8
+ info: 2,
9
+ verbose: 3,
10
+ debug: 4,
11
+ silly: 5
12
+ },
13
+ colors: {
14
+ silly: 'grey',
15
+ verbose: 'grey',
16
+ debug: 'blue',
17
+ info: 'green',
18
+ warn: 'yellow',
19
+ error: 'red'
20
+ },
21
+ transports: [
22
+ // new(Papertrail)({
23
+ // host: 'logs5.papertrailapp.com',
24
+ // port: 53204,
25
+ // colorize: true,
26
+ // level: 'debug'
27
+ // }),
28
+ new(winston.transports.Console)({
29
+ prettyPrint: true,
30
+ colorize: true,
31
+ timestamp: true,
32
+ level: 'debug'
33
+ })
34
+ // new (winston.transports.File)({
35
+ // filename: 'out.log',
36
+ // level: 'debug'
37
+ // })
38
+ ]
39
+ })
40
+ module.exports = logger
package/lib/mail.js ADDED
@@ -0,0 +1,57 @@
1
+ const logger = require('./logger.js')
2
+
3
+ const nodemailer = require('nodemailer')
4
+
5
+ module.exports.send = function (address, subject, data, config) {
6
+ const mailgun = require('mailgun-js')({
7
+ apiKey: config.mail_api_key,
8
+ domain: config.mail_domain
9
+ })
10
+ let options = {
11
+ from: config.mail_from_address,
12
+ to: address,
13
+ subject: config.message_prefix() + subject
14
+ }
15
+ if (/<[a-z][\s\S]*>/i.test(data)) {
16
+ options.html = data
17
+ } else {
18
+ options.text = data
19
+ }
20
+ mailgun.messages().send(options, (err, body) => {
21
+ if (err) {
22
+ logger.error('Mail sent error: %j', err)
23
+ } else if (body.id) {
24
+ logger.info('Mail sent successfully')
25
+ }
26
+ })
27
+ }
28
+
29
+ module.exports.send_cn = function (address, subject, data, config, cd) {
30
+ let transporter = nodemailer.createTransport({
31
+ host: config.mail_smtp_server,
32
+ port: 465,
33
+ secure: true,
34
+ auth: {
35
+ user: config.mail_from_address_china,
36
+ pass: cd.mail_user_password
37
+ }
38
+ })
39
+ let options = {
40
+ from: config.mail_from_address_china,
41
+ to: address,
42
+ subject: subject
43
+ }
44
+ if (/<[a-z][\s\S]*>/i.test(data)) {
45
+ options.html = data
46
+ options.text = ''
47
+ } else {
48
+ options.text = data
49
+ options.html = ''
50
+ }
51
+ transporter.sendMail(options, (err, body) => {
52
+ if (err) {
53
+ return logger.error('Mail sent error: %j', err)
54
+ }
55
+ logger.info('Mail sent successfully: %j', body.response)
56
+ })
57
+ }
@@ -0,0 +1,24 @@
1
+ module.exports = class RateLimiter {
2
+ constructor (settings) {
3
+ this.max_concurrent = settings.max_concurrent ? settings.max_concurrent : null
4
+ this.interval_concurrent = settings.interval_concurrent ? settings.interval_concurrent : null
5
+ this.count = 0
6
+ }
7
+ process (func, ...args) {
8
+ if (!this.max_concurrent || !this.interval_concurrent) {
9
+ func(...args)
10
+ return
11
+ }
12
+ if (this.count === 0) {
13
+ setTimeout(() => { this.count = 0 }, this.interval_concurrent)
14
+ }
15
+ if (this.count < this.max_concurrent) {
16
+ this.count ++
17
+ func(...args)
18
+ } else {
19
+ setTimeout(() => {
20
+ this.process(func, ...args)
21
+ }, this.interval_concurrent)
22
+ }
23
+ }
24
+ }