Advertisement
Guest User

Untitled

a guest
Apr 21st, 2016
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.71 KB | None | 0 0
  1. App = {
  2. 'exect':function(commnad){
  3. if(this[commnad] !== undefined){
  4. LOG('Запуск команды ' + commnad, [commnad]);
  5. this[commnad]();
  6. } else {
  7. LOG('Команда ' + commnad + ' не опознана ');
  8. }
  9. },
  10. 'sync':function(){
  11. //new Sync('cdr',fs,connect,30000,50);
  12. },
  13. 'kill':function(){
  14. process.exit(0);
  15. }
  16. }
  17.  
  18. App.sync ={};
  19.  
  20. App.init = function(fs,connect){
  21. this.fs = fs;
  22. this.connect = connect;
  23.  
  24. this.connect.startPing(); //Запускаем пинг
  25. App.sync._start();
  26. this.sync.start();
  27. }
  28.  
  29. App.sync.cdrtimer = undefined;
  30.  
  31.  
  32. App.slosetimer = 0;
  33.  
  34. App.sync._start = function(){
  35.  
  36. new Sync('cdr',
  37. fs,
  38. App.connect,
  39. confing.tableSyncStepTime,
  40. confing.tableSyncRowStep,
  41. function(){
  42. App.slosetimer++;
  43. //LOG('cdr+',[App.slosetimer]);
  44. },
  45. function(){
  46. App.slosetimer--;
  47. //LOG('cdr-',[App.slosetimer]);
  48. }
  49. );
  50.  
  51.  
  52. new Sync('queue_log',
  53. fs,
  54. App.connect,
  55. confing.tableSyncStepTime,
  56. confing.tableSyncRowStep,
  57. function(){
  58. App.slosetimer++;
  59. //LOG('queue_log+',[App.slosetimer]);
  60. },
  61. function(){
  62. App.slosetimer--;
  63. //LOG('queue_log-',[App.slosetimer]);
  64. }
  65. );
  66.  
  67. Filesunc.sync(function(){
  68. //LOG('Filesunc-',[App.slosetimer]);
  69. App.slosetimer--;
  70. },function(){
  71. //LOG('Filesunc+',[App.slosetimer]);
  72. App.slosetimer++;
  73. });
  74. }
  75.  
  76. App.sync.start = function(){
  77. var self = this;
  78. if (App.sync.cdrtimer !== undefined) return;
  79. App.sync.cdrtimer = setInterval(function(){
  80. LOG('Таймаут запуска синхронизации :'+ App.slosetimer ,[App.sync.cdrtimer,confing.tableSync]);
  81.  
  82. // if (App.slosetimer != 0){
  83. // LOG('Не все синхронизации закончили свою работу :'[App.slosetimer]);
  84. // } else {
  85. App.sync._start();
  86.  
  87.  
  88. },confing.tableSync);
  89.  
  90.  
  91. }
  92.  
  93.  
  94.  
  95. App.sync.stop = function(){
  96. LOG('Остановки синхронизации, автозапуска не будет :');
  97. App.sync.cdrtimer = undefined;
  98. clearInterval(App.sync.cdrtimer);
  99. }
  100.  
  101. Connect = function(request,fs){
  102. // this.id = confing.id;
  103. // this.host = confing.host;
  104. // this.hash = confing.hash;
  105. // this.pingtime = confing.pingtime;
  106.  
  107. this.sendFile = function(url){
  108. //Отправка файла
  109. var form = new FormData();
  110. form.append('path', url.substr(0,url.lastIndexOf('/'))+'/' );
  111. form.append('a', 'sfile');
  112. form.append('id', confing.id);
  113. form.append('h', confing.hash);
  114.  
  115. form.append('file',fs.createReadStream(url));
  116. form.submit(confing.host, function(err, res) {
  117. res.resume(); // for node-0.10.x
  118. });
  119. }
  120.  
  121.  
  122.  
  123. this.stopPing = function(){
  124. LOG('Пинг остановлен');
  125. clearInterval(this.pingtimer);
  126. }
  127.  
  128. this.startPing = function(){
  129. LOG('Запущен пинг');
  130. var self = this;
  131. this.pingtimer = setInterval(function(){
  132. self.ping();
  133. },confing.pingtime);
  134. }
  135.  
  136. this.ping = function(){
  137. var self = this;
  138. this.send('ping',{},function(resp){
  139. if (resp.body === undefined){
  140. LOG('ping нет ответа от сервера или ответ не корректный');
  141. return;
  142. }
  143. var resp = JSON.parse(resp.body);
  144. if (resp.status === 'ok'){
  145. if(resp.command != ''){
  146. LOG('Получена команда ',[resp.command]);
  147. App.exect(resp.command);
  148. }
  149. }
  150. console.log('ping result',resp);
  151. });
  152. }
  153.  
  154.  
  155. this.send = function(action,da,cb){
  156. var datas = {'a':action,'h':confing.hash,'id':confing.id};
  157.  
  158. if (da != undefined){
  159. for (var d in da){
  160. datas[d] = da[d];
  161. }
  162. }
  163.  
  164. // if (da !== undefined){
  165. // d.data = da;
  166. // }
  167. request.post(
  168. confing.host,
  169. { form: datas },
  170. function (error, response, body) {
  171. if (!error && response.statusCode == 200) {
  172. if ( cb !== undefined ) {
  173. cb(response);
  174. }
  175. } else {
  176. if ( cb !== undefined ) {
  177. cb(error);
  178. console.log(error, response, body);
  179. }
  180. }
  181. }
  182. );
  183. }
  184. }
  185.  
  186.  
  187.  
  188. Sync = function(table,fs,connect,synctime,s,cb,cstr){
  189. if (cstr !== undefined){
  190. cstr();
  191. }
  192. var step = s;
  193. var last = 0;
  194.  
  195. try { //Считываем данные из файла о последней синхронизации
  196. last = parseInt(fs.readFileSync('last'+table+'.txt', 'utf8'));
  197. } catch (err) {
  198. fs.writeFileSync('last'+table+'.txt', step );
  199. last = 0;
  200. }
  201.  
  202. LOG('Запущен новый экземпляр синхронизации',[table,synctime]);
  203.  
  204. var self = this;
  205. MYSQLL.GetCountCdr(table,function(d){
  206.  
  207. LOG('Записей в базе ' +d + ' указатель стоит на '+ last ,[d,last]);
  208.  
  209. var sdfsf = setInterval(function(){
  210. MYSQLL.getStoo(table,last,step,function(rows){
  211. var dd = d;
  212. var strr = JSON.stringify(rows);
  213. connect.send(
  214. 'senddata',
  215. {'sql':strr,'table':table}
  216. );
  217. if (last == dd){
  218. fs.writeFileSync('last'+table+'.txt', dd);
  219. clearInterval(sdfsf);
  220. LOG('Таймер '+table +' остановлен, на записи :'+last ,[sdfsf,table,dd,last]);
  221.  
  222. if (cb !== undefined){
  223. cb();
  224. }
  225.  
  226. } else {
  227. last += rows.length;
  228. fs.writeFileSync('last'+table+'.txt', last);
  229. console.log('step ',last, step);
  230. }
  231. });
  232. },synctime);
  233. });
  234. }
  235.  
  236.  
  237. Filesunc = {};
  238. Filesunc.readdir = function(c){
  239. recursive(confing.mp3dir, function (err, files) {
  240. c(files);
  241. });
  242. }
  243. Filesunc.bs = false;
  244. Filesunc.sync = function(start,end){
  245. //Получаем все файлы в папке
  246. if (Filesunc.bs) return;
  247. LOG('Запусуск синхронизации файлов');
  248. start();
  249. Filesunc.bs = true;
  250. Filesunc.readdir(function(a){
  251.  
  252. if ( !a ) {
  253. return;
  254. }
  255.  
  256. var mask = confing.fileMask;
  257. var l = a.length;
  258. while(l--){
  259. if ( !mask.test( a[l] )){
  260. a.splice(l,1);
  261. }
  262. }
  263.  
  264. LOG('Аудио файлов в системе ' + a.length );
  265. var list = JSON.stringify(a); //Массив файлов в троку
  266. connect.send("filesync",{'string':list},function(resp){
  267. if(!resp) return;
  268. if (resp.body !== undefined){
  269. var d = JSON.parse(resp.body);
  270. var files = d.data;
  271. LOG('Файлов для синхронизации ' +files.length);
  272. Filesunc.StartSyncFile(files,end);
  273. //Ответ от сервера какие файлы нужно отправить
  274. }
  275. });
  276.  
  277. });
  278. }
  279.  
  280. Filesunc.StartSyncFile = function(files,end){
  281. var fleng = files.length;
  282. var i = 0;
  283. var fsyncTimer = setInterval(function(){
  284. if (files[i] !== undefined){
  285. var fil = files[i];
  286. connect.sendFile(fil);
  287. console.log('send ',fil);
  288. }
  289. i++;
  290. if (fleng <= i){
  291. clearInterval(fsyncTimer);
  292. Filesunc.bs = false;
  293. end();
  294. }
  295. },confing.FileStep);
  296. }
  297.  
  298.  
  299.  
  300.  
  301. MySql = function(h,u,p,db,t)
  302. {
  303. this.db = db;
  304.  
  305. var config = {
  306. host: h
  307. ,user: u
  308. ,password: p
  309. ,timezone:t
  310. };
  311.  
  312. var pool = mysql.createPool( config );
  313.  
  314. pool.on('connection', function (connection) {
  315. connection.query("use " + db)
  316. });
  317.  
  318. this.connection = {
  319. query: function( sql, values, cb ){
  320. console.log('DDDD EEEEE BBBBB UUUU GGGGG ' + sql );
  321. var _values, _cb;
  322.  
  323. if (typeof values === 'function') {
  324. _cb = values;
  325. } else {
  326. _cb = cb;
  327. _values = values;
  328. }
  329.  
  330. pool.getConnection(function(err, connection) {
  331. if( err ){
  332. console.log('DB ERROR: ' + err);
  333. return;
  334. }
  335.  
  336. connection.query( sql, _values, _cb );
  337. connection.release();
  338. });
  339. }
  340. }
  341.  
  342. //////////////////////
  343.  
  344. this.getStoo = function(table,col,step,c){
  345. var strQuery = "select * from "+table+" limit "+col+", " +step;
  346. this.connection.query(strQuery, function(err, rowss){
  347. if(err) {
  348. console.log(strQuery);
  349. throw err;
  350. } else {
  351. if (typeof c === "function"){
  352. c(rowss);
  353. }
  354. }
  355. });
  356.  
  357. }
  358.  
  359. this.GetCountCdr= function(table,c){
  360. //this.connection.query("use "+ this.db);
  361. var strQuery = "select count(*) as c from "+table+" ";
  362. this.connection.query(strQuery, function(err, rowss){
  363. if(err) {
  364. throw err;
  365. } else {
  366. if (typeof c === "function"){
  367. c(rowss[0]['c']);
  368. }
  369. }
  370. });
  371. }
  372.  
  373.  
  374. }
  375.  
  376. fs = require('fs');
  377. recursive = require('recursive-readdir');
  378. mysql = require('mysql');
  379. FormData = require('form-data');
  380.  
  381. //process.env.TZ = 'Asia/Novokuznetsk';
  382.  
  383. confing = {
  384. "id":"ip7d0104a0",
  385. "host":"http://stat.thecall.ru/ii",
  386. "pingtime":60000,
  387. "hash":"843f84fFF4f",
  388. "tableSyncStepTime":6000,
  389. "tableSyncRowStep":250,
  390. "tableSync":3600000,
  391. "mp3dir":"/records/mp3/",
  392. "FileStep":1000,
  393. "dbhost":"localhost",
  394. "dbuser":"asterisk_user",
  395. "dbpassword":"7CE-c83fhJdlpE3w",
  396. "db":"asterisk",
  397. "timezone":"Asia/Novokuznetsk",
  398. "fileMask": /\d.\-2016\-0[34]./
  399. // /\?*/
  400. }
  401.  
  402.  
  403.  
  404. LOG = function(message,data){
  405. var dat = Date();
  406. if (data !== undefined && typeof data === "object"){
  407. var ddd = data.join(',');
  408. } else {
  409. var ddd = '';
  410. }
  411. var string = '#'+new Date() + message+ ' ' + ddd + "\n";
  412. console.log(string);
  413. // var fname = dat.substr(8,7).split(' ').join('');
  414. var fname = Date().substr(4,11).split(' ').join('');
  415. fs.appendFile('log/'+fname+'.txt', string);
  416. }
  417.  
  418.  
  419.  
  420. var request = require('request');
  421. var TABLESYNCCDR = false;
  422.  
  423. MYSQLL = new MySql(confing.dbhost,confing.dbuser,confing.dbpassword,confing.db,confing.timezone);
  424. connect = new Connect(request,fs);
  425.  
  426. App.init(fs,connect);
  427.  
  428. process.on('exit', function(code) {
  429. LOG(' Завершение программы ');
  430. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement