Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- App = {
- 'exect':function(commnad){
- if(this[commnad] !== undefined){
- LOG('Запуск команды ' + commnad, [commnad]);
- this[commnad]();
- } else {
- LOG('Команда ' + commnad + ' не опознана ');
- }
- },
- 'sync':function(){
- //new Sync('cdr',fs,connect,30000,50);
- },
- 'kill':function(){
- process.exit(0);
- }
- }
- App.sync ={};
- App.init = function(fs,connect){
- this.fs = fs;
- this.connect = connect;
- this.connect.startPing(); //Запускаем пинг
- App.sync._start();
- this.sync.start();
- }
- App.sync.cdrtimer = undefined;
- App.slosetimer = 0;
- App.sync._start = function(){
- new Sync('cdr',
- fs,
- App.connect,
- confing.tableSyncStepTime,
- confing.tableSyncRowStep,
- function(){
- App.slosetimer++;
- //LOG('cdr+',[App.slosetimer]);
- },
- function(){
- App.slosetimer--;
- //LOG('cdr-',[App.slosetimer]);
- }
- );
- new Sync('queue_log',
- fs,
- App.connect,
- confing.tableSyncStepTime,
- confing.tableSyncRowStep,
- function(){
- App.slosetimer++;
- //LOG('queue_log+',[App.slosetimer]);
- },
- function(){
- App.slosetimer--;
- //LOG('queue_log-',[App.slosetimer]);
- }
- );
- Filesunc.sync(function(){
- //LOG('Filesunc-',[App.slosetimer]);
- App.slosetimer--;
- },function(){
- //LOG('Filesunc+',[App.slosetimer]);
- App.slosetimer++;
- });
- }
- App.sync.start = function(){
- var self = this;
- if (App.sync.cdrtimer !== undefined) return;
- App.sync.cdrtimer = setInterval(function(){
- LOG('Таймаут запуска синхронизации :'+ App.slosetimer ,[App.sync.cdrtimer,confing.tableSync]);
- // if (App.slosetimer != 0){
- // LOG('Не все синхронизации закончили свою работу :'[App.slosetimer]);
- // } else {
- App.sync._start();
- },confing.tableSync);
- }
- App.sync.stop = function(){
- LOG('Остановки синхронизации, автозапуска не будет :');
- App.sync.cdrtimer = undefined;
- clearInterval(App.sync.cdrtimer);
- }
- Connect = function(request,fs){
- // this.id = confing.id;
- // this.host = confing.host;
- // this.hash = confing.hash;
- // this.pingtime = confing.pingtime;
- this.sendFile = function(url){
- //Отправка файла
- var form = new FormData();
- form.append('path', url.substr(0,url.lastIndexOf('/'))+'/' );
- form.append('a', 'sfile');
- form.append('id', confing.id);
- form.append('h', confing.hash);
- form.append('file',fs.createReadStream(url));
- form.submit(confing.host, function(err, res) {
- res.resume(); // for node-0.10.x
- });
- }
- this.stopPing = function(){
- LOG('Пинг остановлен');
- clearInterval(this.pingtimer);
- }
- this.startPing = function(){
- LOG('Запущен пинг');
- var self = this;
- this.pingtimer = setInterval(function(){
- self.ping();
- },confing.pingtime);
- }
- this.ping = function(){
- var self = this;
- this.send('ping',{},function(resp){
- if (resp.body === undefined){
- LOG('ping нет ответа от сервера или ответ не корректный');
- return;
- }
- var resp = JSON.parse(resp.body);
- if (resp.status === 'ok'){
- if(resp.command != ''){
- LOG('Получена команда ',[resp.command]);
- App.exect(resp.command);
- }
- }
- console.log('ping result',resp);
- });
- }
- this.send = function(action,da,cb){
- var datas = {'a':action,'h':confing.hash,'id':confing.id};
- if (da != undefined){
- for (var d in da){
- datas[d] = da[d];
- }
- }
- // if (da !== undefined){
- // d.data = da;
- // }
- request.post(
- confing.host,
- { form: datas },
- function (error, response, body) {
- if (!error && response.statusCode == 200) {
- if ( cb !== undefined ) {
- cb(response);
- }
- } else {
- if ( cb !== undefined ) {
- cb(error);
- console.log(error, response, body);
- }
- }
- }
- );
- }
- }
- Sync = function(table,fs,connect,synctime,s,cb,cstr){
- if (cstr !== undefined){
- cstr();
- }
- var step = s;
- var last = 0;
- try { //Считываем данные из файла о последней синхронизации
- last = parseInt(fs.readFileSync('last'+table+'.txt', 'utf8'));
- } catch (err) {
- fs.writeFileSync('last'+table+'.txt', step );
- last = 0;
- }
- LOG('Запущен новый экземпляр синхронизации',[table,synctime]);
- var self = this;
- MYSQLL.GetCountCdr(table,function(d){
- LOG('Записей в базе ' +d + ' указатель стоит на '+ last ,[d,last]);
- var sdfsf = setInterval(function(){
- MYSQLL.getStoo(table,last,step,function(rows){
- var dd = d;
- var strr = JSON.stringify(rows);
- connect.send(
- 'senddata',
- {'sql':strr,'table':table}
- );
- if (last == dd){
- fs.writeFileSync('last'+table+'.txt', dd);
- clearInterval(sdfsf);
- LOG('Таймер '+table +' остановлен, на записи :'+last ,[sdfsf,table,dd,last]);
- if (cb !== undefined){
- cb();
- }
- } else {
- last += rows.length;
- fs.writeFileSync('last'+table+'.txt', last);
- console.log('step ',last, step);
- }
- });
- },synctime);
- });
- }
- Filesunc = {};
- Filesunc.readdir = function(c){
- recursive(confing.mp3dir, function (err, files) {
- c(files);
- });
- }
- Filesunc.bs = false;
- Filesunc.sync = function(start,end){
- //Получаем все файлы в папке
- if (Filesunc.bs) return;
- LOG('Запусуск синхронизации файлов');
- start();
- Filesunc.bs = true;
- Filesunc.readdir(function(a){
- if ( !a ) {
- return;
- }
- var mask = confing.fileMask;
- var l = a.length;
- while(l--){
- if ( !mask.test( a[l] )){
- a.splice(l,1);
- }
- }
- LOG('Аудио файлов в системе ' + a.length );
- var list = JSON.stringify(a); //Массив файлов в троку
- connect.send("filesync",{'string':list},function(resp){
- if(!resp) return;
- if (resp.body !== undefined){
- var d = JSON.parse(resp.body);
- var files = d.data;
- LOG('Файлов для синхронизации ' +files.length);
- Filesunc.StartSyncFile(files,end);
- //Ответ от сервера какие файлы нужно отправить
- }
- });
- });
- }
- Filesunc.StartSyncFile = function(files,end){
- var fleng = files.length;
- var i = 0;
- var fsyncTimer = setInterval(function(){
- if (files[i] !== undefined){
- var fil = files[i];
- connect.sendFile(fil);
- console.log('send ',fil);
- }
- i++;
- if (fleng <= i){
- clearInterval(fsyncTimer);
- Filesunc.bs = false;
- end();
- }
- },confing.FileStep);
- }
- MySql = function(h,u,p,db,t)
- {
- this.db = db;
- var config = {
- host: h
- ,user: u
- ,password: p
- ,timezone:t
- };
- var pool = mysql.createPool( config );
- pool.on('connection', function (connection) {
- connection.query("use " + db)
- });
- this.connection = {
- query: function( sql, values, cb ){
- console.log('DDDD EEEEE BBBBB UUUU GGGGG ' + sql );
- var _values, _cb;
- if (typeof values === 'function') {
- _cb = values;
- } else {
- _cb = cb;
- _values = values;
- }
- pool.getConnection(function(err, connection) {
- if( err ){
- console.log('DB ERROR: ' + err);
- return;
- }
- connection.query( sql, _values, _cb );
- connection.release();
- });
- }
- }
- //////////////////////
- this.getStoo = function(table,col,step,c){
- var strQuery = "select * from "+table+" limit "+col+", " +step;
- this.connection.query(strQuery, function(err, rowss){
- if(err) {
- console.log(strQuery);
- throw err;
- } else {
- if (typeof c === "function"){
- c(rowss);
- }
- }
- });
- }
- this.GetCountCdr= function(table,c){
- //this.connection.query("use "+ this.db);
- var strQuery = "select count(*) as c from "+table+" ";
- this.connection.query(strQuery, function(err, rowss){
- if(err) {
- throw err;
- } else {
- if (typeof c === "function"){
- c(rowss[0]['c']);
- }
- }
- });
- }
- }
- fs = require('fs');
- recursive = require('recursive-readdir');
- mysql = require('mysql');
- FormData = require('form-data');
- //process.env.TZ = 'Asia/Novokuznetsk';
- confing = {
- "id":"ip7d0104a0",
- "host":"http://stat.thecall.ru/ii",
- "pingtime":60000,
- "hash":"843f84fFF4f",
- "tableSyncStepTime":6000,
- "tableSyncRowStep":250,
- "tableSync":3600000,
- "mp3dir":"/records/mp3/",
- "FileStep":1000,
- "dbhost":"localhost",
- "dbuser":"asterisk_user",
- "dbpassword":"7CE-c83fhJdlpE3w",
- "db":"asterisk",
- "timezone":"Asia/Novokuznetsk",
- "fileMask": /\d.\-2016\-0[34]./
- // /\?*/
- }
- LOG = function(message,data){
- var dat = Date();
- if (data !== undefined && typeof data === "object"){
- var ddd = data.join(',');
- } else {
- var ddd = '';
- }
- var string = '#'+new Date() + message+ ' ' + ddd + "\n";
- console.log(string);
- // var fname = dat.substr(8,7).split(' ').join('');
- var fname = Date().substr(4,11).split(' ').join('');
- fs.appendFile('log/'+fname+'.txt', string);
- }
- var request = require('request');
- var TABLESYNCCDR = false;
- MYSQLL = new MySql(confing.dbhost,confing.dbuser,confing.dbpassword,confing.db,confing.timezone);
- connect = new Connect(request,fs);
- App.init(fs,connect);
- process.on('exit', function(code) {
- LOG(' Завершение программы ');
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement