Advertisement
Guest User

Untitled

a guest
Nov 14th, 2016
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.62 KB | None | 0 0
  1. "use strict";
  2.  
  3. const pg = require('pg'),
  4. EventEmitter = require('events').EventEmitter,
  5. EE = new EventEmitter,
  6. connect = 'pg://postgres:9385411q@localhost:5432/',
  7. config = {
  8. users:{ id:'SERIAL NOT NULL PRIMARY KEY',
  9. owner:'INT REFERENCES users',
  10. token:'VARCHAR(200)',
  11. captcha_key: 'VARCHAR(32)',
  12. ban: 'BOOLEAN NOT NULL DEFAULT FALSE',
  13. access: 'BIGINT DEFAULT 0',
  14. limit_ok: 'INT DEFAULT 0',
  15. limit_time: 'BIGINT DEFAULT 0',
  16. phone: 'BIGINT',
  17. send: 'INT DEFAULT 0',
  18. key: 'UUID DEFAULT gen_random_uuid()',
  19. captcha_balance: 'REAL DEFAULT 0',
  20. error: 'json',
  21. app:'INT',
  22. online: 'BOOLEAN NOT NULL DEFAULT FALSE'
  23. },
  24. bids:{id:'SERIAL NOT NULL PRIMARY KEY',
  25. aid:'INT REFERENCES users',
  26. cid:'INT',
  27. eid:'INT',
  28. maid:'INT[]',
  29. country:'INT',
  30. cities:'INT[]',
  31. sex:'INT DEFAULT 0',
  32. age_from:'INT',
  33. age_to:'INT',
  34. last_seen:'INT',
  35. count:'INT',
  36. status:'INT DEFAULT 0',
  37. go:'INT DEFAULT 0',
  38. date:'BIGINT DEFAULT extract(epoch from now())*1000',
  39. count_denied:'INT DEFAULT 0',
  40. count_already:'INT DEFAULT 0',
  41. count_ok:'INT DEFAULT 0',
  42. count_captcha:'INT DEFAULT 0',
  43. count_ok_having:'INT DEFAULT 0',
  44. from_having:'INT DEFAULT 0',
  45. error: 'json'
  46. },
  47. tasks:{ id:'SERIAL NOT NULL PRIMARY KEY',
  48. bid:'INT REFERENCES bids',
  49. uid:'INT',
  50. state:'INT DEFAULT 0',
  51. state_data:'BIGINT DEFAULT 0',
  52. aid:'INT REFERENCES users',
  53. info:'json'
  54. }
  55. /*money_y:{
  56. id:'SERIAL NOT NULL PRIMARY KEY',
  57. sender:'VARCHAR(100)',
  58. date:'BIGINT DEFAULT extract(epoch from now())*1000',
  59. amount:'REAL DEFAULT 0',
  60. operation_id:'VARCHAR(100)',
  61. currency:'VARCHAR(3)'
  62. }*/
  63. };
  64.  
  65. var pool;
  66. var listen_client;
  67.  
  68. function init_data_base() {
  69.  
  70. var client = new pg.Client(connect+'postgres');
  71. client.connect();
  72. client.query('CREATE DATABASE vktoken', function (err, res) {
  73.  
  74. if (err &&err.code != '42P04')
  75. console.error(err);
  76. else if (res)
  77. console.log(res);
  78.  
  79. client.end();
  80.  
  81. EE.emit('init_data_base');
  82. });
  83.  
  84. }
  85.  
  86. function init_table() {
  87.  
  88. var client = new pg.Client(connect+'vktoken');
  89. client.connect();
  90.  
  91. var k = 0;
  92.  
  93. for (var T in config) {
  94. k++;
  95.  
  96. client.query('CREATE TABLE '+T+'()', function (err, res) {
  97. k--;
  98. if (err && err.code != '42P07')
  99. console.error(err);
  100. else if (res)
  101. console.log(res);
  102. });
  103.  
  104. for (var C in config[T]) {
  105. k++;
  106.  
  107. client.query('ALTER TABLE '+T+' ADD COLUMN '+C+' '+config[T][C]+';', function (err, res) {
  108. k--;
  109. if (err && err.code != '42701')
  110. console.error(err);
  111. else if (res)
  112. console.log(res);
  113.  
  114. if (!k)
  115. EE.emit('init_table');
  116.  
  117. });
  118. }
  119. }
  120. }
  121.  
  122. function init_pool(max_pool) {
  123.  
  124. var config = {
  125. user: 'postgres',
  126. database: 'vktoken',
  127. password: '9385411q',
  128. port: 5432,
  129. max: max_pool,
  130. min: 1,
  131. idleTimeoutMillis: 10000
  132. };
  133.  
  134. var Pool = require('pg').Pool;
  135. pool = new Pool(config);
  136.  
  137. EE.emit('init_pool');
  138. }
  139.  
  140. function init_listen(lisen) {
  141.  
  142. if(lisen){
  143. listen_client = new pg.Client(connect+'vktoken');
  144. listen_client.connect();
  145. listen_client.on('notification', function(msg) {
  146. EE.emit(msg.channel, msg.payload);
  147. });
  148. }
  149.  
  150. EE.emit('init_listen');
  151. }
  152.  
  153. function cb_db(err, res, cb) {
  154.  
  155. if (typeof(cb) == 'function')
  156. if(err)
  157. cb(err);
  158. else
  159. cb(res);
  160. }
  161.  
  162. // metods----------------------------------------
  163. var user = {
  164. add_new :function (id, cb) {
  165. pool.query('INSERT INTO users(id, owner) VALUES($1,$1)', [id], function (err, res) {
  166. cb_db(err, res, cb);
  167. });
  168. },
  169. get_json :function (id, cb) {
  170. pool.query('SELECT array_to_json(ARRAY(SELECT row_to_json(users) FROM users ' +
  171. 'WHERE owner = $1 OR id = $1)) AS users', [id], function (err, res) {
  172. cb(res);
  173. });
  174. },
  175. get :function (maid, cb) {
  176. pool.query('SELECT temp.id, temp.token, temp.owner, users.captcha_key, true AS on FROM users AS temp ' +
  177. 'JOIN users ON (temp.owner = users.id) WHERE temp.id = ANY ($1)', [maid], function (err, res) {
  178. cb(res);
  179. });
  180. },
  181. get_id_form_key :function (key, cb) {
  182. pool.query('SELECT id FROM users WHERE key = $1', [key], function (err, res) {
  183. cb_db(err, res, cb);
  184. });
  185. },
  186. get_key_form_id :function (id, cb) {
  187. pool.query('SELECT key, ban FROM users WHERE id = $1', [id], function (err, res) {
  188. cb_db(err, res, cb);
  189. });
  190. },
  191. get_all_do_continue :function (cb) {
  192. pool.query('SELECT limit_time, id FROM users '+
  193. 'WHERE limit_time <> 0 AND access > extract(epoch from now())*1000 ', function (err, res) {
  194. cb(res);
  195. });
  196. },
  197. get_captcha_key :function (id, cb) {
  198. pool.query('SELECT captcha_key FROM users WHERE id = $1', [id], function (err, res) {
  199. cb(res.rows[0].captcha_key);
  200. });
  201. },
  202. update_token :function (id, token, cb) {
  203. pool.query('UPDATE users ' +
  204. 'SET token = $2, error = null ' +
  205. 'WHERE users.id = $1', [id, token], function (err, res) {
  206. cb_db(err, res, cb);
  207. });
  208. },
  209. update_phone :function (id, phone, cb) {
  210. pool.query('UPDATE users ' +
  211. 'SET phone = $2 ' +
  212. 'WHERE users.id = $1', [id, phone], function (err, res) {
  213. cb_db(err, res, cb);
  214. });
  215. },
  216. update_app :function (id, app, cb) {
  217. pool.query('UPDATE users SET app = $2 ' +
  218. 'WHERE id = $1', [id, app]);
  219. },
  220. update_captcha_balance :function (id, balance) {
  221. pool.query('UPDATE users ' +
  222. 'SET captcha_balance = $2 ' +
  223. 'WHERE id = $1', [id, balance], function (err, res) {
  224. cb_db(err, res);
  225. });
  226. },
  227. update_access :function (id, access) {
  228. pool.query('UPDATE users ' +
  229. 'SET access = $2, error = null ' +
  230. 'WHERE id = $1', [id, access]);
  231. },
  232. update_captcha :function (id, key, balance) {
  233. pool.query('UPDATE users ' +
  234. 'SET captcha_key = $2, captcha_balance = $3 ' +
  235. 'WHERE users.id = $1', [id, key, balance]);
  236. },
  237. set_error :function (id, err) {
  238. pool.query('UPDATE users SET error = $2 WHERE id = $1', [id, err]);
  239. },
  240. set_owner :function (id, owner, cb) {
  241. pool.query('UPDATE users ' +
  242. 'SET owner = $2 '+
  243. 'WHERE users.id = $1', [id, owner], function (err, res) {
  244. cb_db(err, res, cb);
  245. });
  246. },
  247. set_real_limit :function (id) {
  248. pool.query('UPDATE users SET limit_time = 0, limit_ok = (SELECT count(*) FROM tasks ' +
  249. 'JOIN bids ON (tasks.bid = bids.id ' +
  250. 'AND $1 = ANY(bids.maid) ' +
  251. 'AND tasks.state = 1 ' +
  252. 'AND tasks.aid = $1 ' +
  253. 'AND tasks.state_data >= extract(epoch from now())*1000 - 13*60*60*1000)) ' +
  254. 'WHERE users.id = $1', [id], function (err, res) {
  255. cb_db(err, res);
  256. });
  257. },
  258. update_real_limit :function (id) {
  259. pool.query('UPDATE users SET limit_ok = (SELECT count(*) FROM tasks ' +
  260. 'JOIN bids ON (tasks.bid = bids.id ' +
  261. 'AND $1 = ANY(bids.maid) ' +
  262. 'AND tasks.state = 1 ' +
  263. 'AND tasks.aid = $1 ' +
  264. 'AND tasks.state_data >= extract(epoch from now())*1000 - 13*60*60*1000)) ' +
  265. 'WHERE users.id = $1', [id], function (err, res) {
  266. cb_db(err, res);
  267. });
  268. },
  269. set_online :function (id, online) {
  270. pool.query('UPDATE users SET online = $2 WHERE id = $1', [id, online]);
  271. },
  272. set_online_default :function () {
  273. pool.query('UPDATE users SET online = false WHERE online = true');
  274. },
  275. limit_ok_inc :function (id) {
  276. pool.query('UPDATE users SET limit_ok = limit_ok + 1 WHERE id = $1', [id]);
  277. },
  278. continuation :function (id) {
  279. pool.query('SELECT continuation($1)', [id]);
  280. }
  281. };
  282.  
  283. var bid = {
  284. add_json :function (aid, v, cb) {
  285. var maid = v.maid,
  286. tasks = v.tasks,
  287. cities = v.cities===null?null:'{'+String(v.cities)+'}';
  288.  
  289. delete v.tasks;
  290. delete v.maid;
  291. delete v.cities;
  292. v.aid = aid;
  293.  
  294. pool.query('INSERT INTO bids(maid,aid,cid,eid,country,cities,sex,age_from,age_to,count,last_seen) ' +
  295. 'SELECT $2 AS maid,aid,cid,eid,country,$3 AS cities,sex,age_from,age_to,count,last_seen ' +
  296. 'FROM json_populate_record(null::bids, $1) RETURNING id', [JSON.stringify(v), '{'+String(maid)+'}', cities], function (err, res) {
  297.  
  298. if (res.rowCount&&tasks) {
  299. var bid = res.rows[0].id;
  300. task.add_uids(bid, tasks, function () {
  301. bid.start_invite(bid);
  302. });
  303. }
  304.  
  305. cb_db(err, res, cb);
  306. });
  307. },
  308. count_ok_inc :function (id) {
  309. pool.query('UPDATE bids SET count_ok = count_ok+1 WHERE id = $1', [id]);
  310. },
  311. count_denied_inc :function (id) {
  312. pool.query('UPDATE bids SET count_denied = count_denied+1 WHERE id = $1', [id]);
  313. },
  314. count_captcha_inc :function (id) {
  315. pool.query('UPDATE bids SET count_captcha = count_captcha+1 WHERE id = $1', [id]);
  316. },
  317. count_already_inc :function (id) {
  318. pool.query('UPDATE bids SET count_already = count_already+1 WHERE id = $1', [id]);
  319. },
  320. get_json :function (id, cb){
  321. pool.query('SELECT array_to_json(ARRAY( SELECT row_to_json(bids) FROM bids ' +
  322. 'INNER JOIN users ON bids.aid = users.id ' +
  323. 'WHERE (users.owner = $1 OR users.id = $1) AND bids.status <> 5 ' +
  324. 'ORDER BY bids.id DESC)) AS bids', [id], function (err, res) {
  325. cb_db(err,res,cb);
  326. });
  327. },
  328. get_all_do_task :function (cb) {
  329. pool.query('SELECT row_to_json(bids) AS bid FROM bids '+
  330. 'WHERE go = 0 AND status = 1', function (err, res) {
  331. cb_db(err,res,cb);
  332. });
  333. },
  334. get_all_do_invite :function (cb) {
  335. pool.query('SELECT row_to_json(bids) AS bid FROM bids '+
  336. 'WHERE go = 1 AND status = 1', function (err, res) {
  337. cb_db(err,res,cb);
  338. });
  339. },
  340. update_status :function (id, aid, status, from_having, cb) {
  341. pool.query('UPDATE bids ' +
  342. 'SET status = $3, from_having = COALESCE($4, from_having) ' +
  343. 'WHERE bids.id = $1 AND bids.aid = $2', [id, aid, status, from_having], function (err, res) {
  344. cb_db(err, res, cb);
  345. });
  346. },
  347. update_maid :function (id, maid) {
  348. pool.query('UPDATE bids SET maid = $2 WHERE id = $1', [id, '{'+String(maid)+'}']);
  349. },
  350. set_status_sys :function (bid, status, err, cb) {
  351. pool.query('UPDATE bids ' +
  352. 'SET status = $2, error = $3' +
  353. 'WHERE bids.id = $1', [bid, status, err], function (err, res) {
  354. cb_db(err, res, cb);
  355. });
  356. },
  357. start_invite :function (bid, cb) {
  358. pool.query('UPDATE bids ' +
  359. 'SET status = 0, go = 1, from_having = 0, ' +
  360. 'count = (SELECT count(*) FROM tasks WHERE bid = $1), ' +
  361. 'count_ok_having = (SELECT count(DISTINCT t1.uid) AS count_ok_having FROM tasks AS t1 ' +
  362. 'JOIN tasks ON (t1.uid = tasks.uid AND tasks.state = 1) ' +
  363. 'WHERE t1.bid = $1) ' +
  364. 'WHERE id = $1', [bid], function (err, res) {
  365. cb_db(err, res, cb);
  366. });
  367. },
  368. set_error :function (id, err) {
  369. pool.query('UPDATE bids SET error = $2 WHERE id = $1', [id, err]);
  370. },
  371. set_done :function (id, err) {
  372. pool.query('UPDATE bids SET error = $2 WHERE id = $1 and go = 0', [id, err]);
  373. },
  374. performed :function (cb) {
  375. pool.query('SELECT count(*) AS count FROM bids WHERE status = 1 AND go = 1', function (err, res) {
  376. cb(res.rows[0].count);
  377. });
  378. }
  379. };
  380.  
  381. var task = {
  382. add_uids :function (bid_id, data, cb) {
  383. pool.query('INSERT INTO tasks(bid, uid) ' +
  384. 'SELECT $1 AS bid, uid FROM (SELECT SUBSTRING(str,\'([0-9]+)\')::INT AS uid ' +
  385. 'FROM regexp_split_to_table($2, \'\\s|,|:|\\n|\\.\') As str) AS tasks ' +
  386. 'WHERE NOT uid ISNULL', [bid_id, data], function (err, res) {
  387. cb_db(err, res, cb);
  388. });
  389. },
  390. add_json :function (bid_id, data, cb) {
  391. pool.query('INSERT INTO tasks(bid, uid) ' +
  392. 'SELECT bids.id AS bid, x.id AS uid ' +
  393. 'FROM json_to_recordset($2) AS x(id INT, sex INT, city JSON, country JSON, last_seen JSON, bdate TEXT) ' +
  394. 'JOIN bids ON bids.id = $1 ' +
  395. 'WHERE (bids.sex = 0 OR x.sex = bids.sex) ' +
  396. 'AND (bids.cities ISNULL OR to_number(x.city->>\'id\',\'99999999999\') = ANY(bids.cities)) ' +
  397. 'AND (bids.country = 0 OR x.country->>\'id\' = bids.country::TEXT) ' +
  398. 'AND (bids.last_seen = 0 OR EXTRACT(EPOCH FROM now()) - to_number(x.last_seen->>\'time\',\'9999999999\') <= bids.last_seen*86400) ' +
  399. 'AND (bids.age_to = 0 OR EXTRACT(YEAR FROM now()) - to_number(right(x.bdate, 4), \'9999\') BETWEEN bids.age_from AND bids.age_to) ', [bid_id, JSON.stringify(data)], function (err, res) {
  400. cb_db(err, res, cb);
  401. });
  402. },
  403. get_all :function (bid_id, cb) {
  404. pool.query('SELECT tasks.id, uid, eid, bid FROM tasks ' +
  405. 'JOIN bids ON tasks.bid = bids.id ' +
  406. 'JOIN users ON bids.aid = users.id ' +
  407. 'WHERE tasks.bid = $1 AND (tasks.state = 0 OR tasks.state = 14) AND users.ban = FALSE AND bids.status = 1 AND bids.go = 1', [bid_id], function (err, res) {
  408. cb_db(err, res, cb);
  409. });
  410. },
  411. update_state :function (id, aid, state, info, cb) {
  412.  
  413. if(info === undefined) info = null;
  414.  
  415. pool.query('UPDATE tasks SET aid = $2, state = $3, info = $4 WHERE id = $1', [id, aid, state, info], function (err, res) {
  416. cb_db(err, res, cb);
  417. });
  418. },
  419. del :function (bid_id, cb) {
  420. pool.query('DELETE FROM tasks WHERE bid = $1', [bid_id], function (err, res) {
  421. cb(res);
  422. });
  423. },
  424. invite :function (task, sender, url, cb) {
  425. pool.query('SELECT invite($1, $2, $3)', [task, sender, url], function (err, res) {
  426. cb_db(err, res, cb);
  427. });
  428. },
  429. invite_cb :function (res, cb) {
  430. pool.query('SELECT invite_cb($1)', [res], function (err, res) {
  431. cb_db(err, res, cb);
  432. });
  433. }
  434. };
  435.  
  436. var money = {
  437. add_json_money_y :function (data, cb) {
  438. pool.query('INSERT INTO money_y(sender,amount,operation_id,currency) ' +
  439. 'SELECT sender,amount::REAL,operation_id,currency ' +
  440. 'FROM json_populate_record(null::money_y, \''+data+'\')', function (err, res) {
  441. cb_db(err, res, cb);
  442. });
  443. }
  444. };
  445.  
  446. // metods----------------------------------------
  447.  
  448. function APIDB() {
  449. this.User = user;
  450. this.Bid = bid;
  451. this.Task = task;
  452. this.Money = money;
  453. this.on = function (type, cb) {
  454. listen_client.query('LISTEN "'+type+'"');
  455. EE.addListener(type, cb);
  456. }
  457. }
  458.  
  459. function start(max, lisen, cb) {
  460.  
  461. EE.on('init_data_base', function() {
  462. init_table();
  463. });
  464.  
  465. EE.on('init_table', function() {
  466. init_pool(max);
  467. });
  468.  
  469. EE.on('init_pool', function () {
  470. init_listen(lisen);
  471. });
  472.  
  473. EE.on('init_listen', function () {
  474. EE.emit('connected');
  475. });
  476.  
  477. EE.on('connected', function() {
  478. cb(new APIDB);
  479. });
  480.  
  481. init_data_base();
  482. }
  483.  
  484. exports = module.exports = start;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement