Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var server = require('http').createServer();
- var io = require('socket.io').listen('7979', { log: false }),
- lobby = require('./lobby.js'),
- worker = require("socket.io-client"), // here the client modul for connect to workplace-socket-server
- workerTokken = 'nfof6g34n7m',
- workerCount = 1,
- fs = require('fs'),
- mysql = require("mysql"),
- squel = require("squel"),
- vali = require('validator'),
- striptags = require('striptags'),
- ftpCon = require('jsftp'),
- path = require('path'), // needed for ftp (remove not empty dir)
- xhr = require('request'),
- errFileName = 'error_dev';
- /** Server Settings */
- var errorLogger = {
- enabled: false,
- file: '/srv/wpo/errorlog/'+errFileName+'.log'
- };
- var lobbyOptions = {
- memcache: {
- port: 11211,
- server: 'localhost'
- },
- lobbyOpt: {
- debug: 3, // set 0 to show spamScores, set 1 to show child-stage-results, set 2 to show stage-result and 3 or true for show all logs
- authCookieName: 'WPOCMS', // name of php session-cookie - remove this option to use default 'PHPSESSID'
- allowProxy: false, // is this false we check the IP-V6 of user and this must are static!!!
- removeInterval: 15, // check each x minutes have a user 0 connections then can be removed from the lobby (afk, idled users can be removed)
- offMargin: 15, // in seconds a margin how the user has time for reconnect before send to the contactlis he is now offline
- sockets: {'owp/dashboard/view': 'main', 'owp/mde/workplace': 'wp'}, // not defined referer will sorted to 'other' or remove this option to use on alle sites the same socket and unlimited connections
- socketMaxCon: { 'main': 1, 'wp': 1, 'other': 0 }, // set allowed opened tabs by sockets {'main': 1, 'wp': 0, 'other': 0} (0 = unlimited) - if no sockets defined set value as int socketMaxCon: 5 or remove this option to use default (unlimited)
- statusSync: ['main', 'wp'], // define the server who will sync the onlie-status
- // socketFuncs: { }
- },
- antiSpamOpt: {
- // no settings use default settings
- }
- };
- var dbConnection = {'site': { // dont change the key`s!!!
- host : "localhost",
- user : "myuser",
- password: "pass",
- database : "db",
- port : "3306"
- },'wp': {
- host : "localhost",
- user : "myuser",
- password: "pass",
- database : "db",
- port : "3306"
- }};
- function update_log( nerr )
- {
- var executeErrLoop = setInterval(function(){
- if( loggerBusy === false ){
- loggerBusy = true;
- fs.readFile(errorLogger.file, 'utf8', function(err, data){
- if(err){
- fs.writeFileSync(errorLogger.file, new Date().dateTime()+': '+nerr);
- loggerBusy = false;
- clearInterval(executeErrLoop);
- }else{
- var tmp = data+'\n'+new Date().dateTime()+': '+nerr;
- fs.writeFileSync(errorLogger.file, tmp);
- loggerBusy = false;
- clearInterval(executeErrLoop);
- }
- });
- }
- }, 500);
- }
- /* Server dependencies. */
- var db, sdb;
- function connectSiteMysql( db_config ) {
- db = mysql.createConnection(db_config); // Recreate the connection, since the old one cannot be reused.
- db.connect(function(err) { // The server is either down
- if(err) { // or restarting (takes a while sometimes).
- console.log('Error connecting to site-DB:', err);
- // setTimeout(connectSiteMysql, 1000); // We introduce a delay before attempting to reconnect,
- } // to avoid a hot loop, and to allow our node script to
- }); // process asynchronous requests in the meantime. If you're also serving http, display a 503 error.
- db.on('error', function(err) {
- console.log('db error', err);
- if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually lost due to either server restart, or a connnection idle timeout (the wait_timeout server variable configures this)
- connectSiteMysql(dbConnection['site']);
- }else{
- throw err;
- }
- });
- db.config.queryFormat = function( query, values ){
- if (!values) return query;
- return query.replace(/\:(\w+)/g, function( txt, key )
- {
- var value = ( values.hasOwnProperty(key) ) ? values[key] : txt;
- value = this.escape(value);
- /** now defined filters used präfix f_ */
- // stripe tags
- if( typeof values['f_tags'] != 'undefined' )
- {
- value = striptags(value, values['f_tags']);
- }
- // console.log(value);
- return value;
- }.bind(this));
- // console.log(query);
- };
- }
- function connectWpMysql( db_config ) {
- sdb = mysql.createConnection(db_config); // Recreate the connection, since the old one cannot be reused.
- sdb.connect(function(err) { // The server is either down
- if(err) { // or restarting (takes a while sometimes).
- console.log('Error connecting to WP-DB:', err);
- // setTimeout(connectWpMysql, 1000); // We introduce a delay before attempting to reconnect,
- } // to avoid a hot loop, and to allow our node script to
- }); // process asynchronous requests in the meantime. If you're also serving http, display a 503 error.
- sdb.on('error', function(err) {
- console.log('sdb error', err);
- if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually lost due to either server restart, or a connnection idle timeout (the wait_timeout server variable configures this)
- connectWpMysql(dbConnection['wp']);
- }else{
- throw err;
- }
- });
- sdb.config.queryFormat = function( query, values ){
- if (!values) return query;
- return query.replace(/\:(\w+)/g, function( txt, key )
- {
- var value = ( values.hasOwnProperty(key) ) ? values[key] : txt;
- value = this.escape(value);
- /** now defined filters used präfix f_ */
- // stripe tags
- if( typeof values['f_tags'] != 'undefined' )
- {
- value = striptags(value, values['f_tags']);
- }
- // console.log(value);
- return value;
- }.bind(this));
- // console.log(query);
- };
- }
- if( typeof lobbyOptions != 'undefined' ){
- Date.prototype.dateTime = function( output, utc ){
- var string = ( typeof output != 'undefined' && output != '' ) ? output : "yyyy-mm-dd hh:mi:se";
- var UTC = ( typeof utc != 'undefined' ) ? utc : true;
- if( UTC === false )
- {
- var yyyy = this.getFullYear().toString();
- var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
- var dd = this.getDate().toString();
- var hh = this.getHours().toString();
- var mi = this.getMinutes().toString();
- var se = this.getSeconds().toString();
- }
- else
- {
- var yyyy = this.getUTCFullYear().toString();
- var mm = (this.getUTCMonth()+1).toString(); // getMonth() is zero-based
- var dd = this.getUTCDate().toString();
- var hh = this.getUTCHours().toString();
- var mi = this.getUTCMinutes().toString();
- var se = this.getUTCSeconds().toString();
- }
- return string.replace('yyyy', yyyy)
- .replace('mm', (mm[1]?mm:"0"+mm[0]))
- .replace('dd', (dd[1]?dd:"0"+dd[0]))
- .replace('hh', (hh[1]?hh:"0"+hh[0]))
- .replace('mi', (mi[1]?mi:"0"+mi[0]))
- .replace('se', (se[1]?se:"0"+se[0]));
- };
- Object.prototype.extend = function( obj ){ for( var key in obj ){ this[key] = obj[key]; } };
- String.prototype.replaceLast = function(find, replace) {
- var index = this.lastIndexOf(find);
- if (index >= 0) {
- return this.substring(0, index) + replace + this.substring(index + find.length);
- }
- return this.toString();
- };
- // catch error`s
- var loggerBusy = false;
- if( errorLogger.enabled === true ){ process.on('uncaughtException', function( err ){ update_log(err); }); }
- // db connections
- connectSiteMysql(dbConnection['site']);
- connectWpMysql(dbConnection['wp']);
- // lobby init
- var lobby = new lobby(lobbyOptions, sdb, io);
- }
- /** Server */
- var socket = io.listen(server);
- socket = socket.of('/global'); // set namespace
- socket.on('connection', function(client) // run server
- {
- /** connection handling */
- lobby.onConnect(client); // add new socket to lobby, this will authorize with cookie/session-ID
- client.on('reAuth', function(){ lobby.onConnect(client); }); // this for reAuth (if default auth failed will this be called)
- client.on('disconnect', function(){ lobby.onDisconnect(client.uid, client.socketServer, client.id); });
- /** track each call of this user */
- var fetchOn = client.on;
- client.on = function( name, func ){
- fetchOn.call(this, name, function() // var name can not be changed!!!
- {
- // var args = ( typeof arguments[0] != 'undefines' ) ? arguments[0] : arguments;
- if( lobby.maxSpamCheck(name, ((lobby.asOpt.punishDublicates) === true ? JSON.stringify(arguments) : false), client.uid) === true ) // send the emit name then defined emits will not raise the spameScore
- {
- func.apply(this, arguments);
- }
- });
- };
- /** communication with a workplace client */
- // each emit need data.typ ('wp' or 'pr') and data.srv (the server ID) but not with onLoad
- client.on('wp', function(data){
- /*
- * Wenn der AP geladen wird und ein reAuth ausgeführt wird, entsteht hier ein Fehler da die uid nicht vorhanden ist, also mit der if die Ausführung verhindern.
- * Der AP verfügt über eine onReAuth Funktion welche ein emit sendet um den AP zu laden wenn reAuth abgeschlossen ist
- */
- if( typeof client.uid != 'undefined' ){ wpHandler(client.uid, data); }
- });
- function wpHandler(uid, data){
- // get serverconnection and check access of each emit
- switch( data.e ){
- case 'onLoad':
- loadWpConn( uid, data.wp, data.pr, data.active );
- break;
- case 'connectTo': // connect to a workplace or project
- connectTo( data.typ, data.srvID, false );
- break;
- default:
- if( typeof lobby.user[uid][data.typ+'s'][data.srv] != 'undefined' ) // check user has acces to this server
- {
- var connCreated = false;
- // access is allowed but has no connection, create it
- if( typeof lobby.user[uid][data.typ+'s'][data.srv]['c'] == 'undefined' ){
- connCreated = connectTo( data.typ, data.srv, false );
- }
- else // has connection check is active
- {
- connCreated = true;
- // reconnect if it needed
- lobby.user[uid][data.typ+'s'][data.srv]['c'].raw("stat", function(err, data) {
- if( err ){
- // if( err.code == 530 ){
- console.log('reconnect');
- delete( lobby.user[uid][data.typ+'s'][data.srv]['c'] );
- connCreated = connectTo( data.typ, data.srv, true );
- // }else{
- // console.log('no error');
- // connCreated = true;
- // }
- console.log('---');
- console.log(err.code);
- console.log(data);
- // console.log('error on get stat: ');
- // console.log( err );
- // console.log( err.code );
- // console.log( data );
- // console.log('---');
- // console.log('reconnect needed:');
- // lobby.user[uid][data.typ+'s'][data.srv]['c'].raw("rein", function(err, data) { if( err ){ console.log('REIN error: '); console.log( err ); }else{ console.log('re connected:'); } });
- }
- else{
- // // if( data.code !== 211 ){
- // // console.log('reconnect needed:');
- // // lobby.user[uid][data.typ+'s'][data.srv]['c'].raw("rein", function(err, data) { if( err ){ console.log('REIN error: '); console.log( err ); }else{ console.log('re connected:'); } });
- // // }else{
- // // console.log('connection is active');
- // // }
- connCreated = true;
- }
- });
- }
- // loop and wait the server connection is established
- var loopCnt = 0;
- var executeComand = setInterval(function()
- {
- if( connCreated === true ){
- clearInterval(executeComand);
- console.log('execute command');
- // has team-member only we must emit the changes to all online members
- var sendTask = true;
- var task = ( !sendTask ) ? false : {
- aTyp: data.typ,
- aID: data.srv
- };
- switch(data.e)
- {
- case 'md': // make dir
- if( task !== false ){
- task.item = ( data.path != '' ) ? idePrepId(data.path, 'dir_'+data.typ+data.srv) : data.typ+data.srv;
- task.ir = ( data.path != '' ) ? 'n' : 'y'; // is root?
- }
- createDir( lobby.user[uid][data.typ+'s'][data.srv]['c'], data.path, data.newDir, task );
- break;
- case 'rd': // read dir
- readDir( lobby.user[uid][data.typ+'s'][data.srv]['c'], data.path, false );
- break;
- case 'mf': // create a file
- if( task !== false ){
- task.item = ( data.path != '.' ) ? idePrepId(data.path, 'dir_'+data.typ+data.srv) : data.typ+data.srv;
- task.ir = ( data.path != '.' ) ? 'n' : 'y'; // is root?
- }
- createFile( lobby.user[uid][data.typ+'s'][data.srv]['c'], data.path, data.file, task );
- break;
- case 'rf': // read a file
- readFile( lobby.user[uid][data.typ+'s'][data.srv]['c'], data.file );
- break;
- case 'rem': // remove a dir or a file
- if( task !== false ){
- task.item = idePrepId(data.item, (( data.iTyp == 'f' ) ? 'file_' : 'dir_')+data.typ+data.srv);
- }
- removeItem( lobby.user[uid][data.typ+'s'][data.srv]['c'], data.item, data.iTyp, task );
- break;
- case 'ren': // rename
- rename( lobby.user[uid][data.typ+'s'][data.srv]['c'], data.from, data.to, data.type, task );
- break;
- }
- }
- if( loopCnt == 500 ){ // connection can not established emit error
- clearInterval(executeComand);
- }
- else{ loopCnt++; }
- }, 50);
- }
- else
- {
- noAccessToServer( data.srv ); // emit: no access
- }
- break;
- }
- }
- // load workplace`s datas from db and add to lobby
- // WP + loadPR : is only for reconnect after server crash/restart to restore the active project
- function loadWpConn( uid, loadThisWP, loadThisPR, active ){
- if( typeof lobby.user[uid] != 'undefined' && typeof lobby.user[uid]['wps'] == 'undefined' )
- {
- sdb.query(
- "SELECT * FROM workplaces WHERE uid = :id", {id: uid},
- function( err, workplaces )
- {
- if( err ){ // error
- console.log('SQL error on find WPs of user: '+ uid);
- console.log( err );
- }else if( workplaces.length == 0 ){ // empty
- console.log('User ('+ uid +') has no WP!');
- }else{
- // add first datas to lobby
- lobby.user[uid]['wps'] = {};
- for( i in workplaces ){
- if( workplaces.hasOwnProperty(i) ){
- var wpID = workplaces[i]['id'];
- lobby.user[uid]['wps'][wpID] = {};
- lobby.user[uid]['wps'][wpID]['name'] = workplaces[i]['name'];
- lobby.user[uid]['wps'][wpID]['srv'] = workplaces[i]['srv'];
- lobby.user[uid]['wps'][wpID]['domain'] = workplaces[i]['domain'];
- lobby.user[uid]['wps'][wpID]['typ'] = workplaces[i]['typ'];
- lobby.user[uid]['wps'][wpID]['role'] = 'owner';
- lobby.user[uid]['wps'][wpID]['access'] = {ftp: 0, db: 0, host: 0, ssh: 0}; // set all modules as disabled. Next query get connections and exist moduls will be enabled
- // set the WP id to load it - has no private workplace we must check is at this time == false then we set the business wp to load
- // or isset a WP then is reconnect and set the last active WP-ID
- if( loadThisWP === false )
- {
- loadThisWP = wpID;
- }
- }
- }
- // load connection-datas of each own workplace
- if( workplaces.length == 2 )
- {
- var connectQuery = 'oid = :id OR oid = :id2',
- connectId = {typ: 'wp', id: workplaces[0]['id'], id2: workplaces[1]['id']},
- ownWPs = [{id: workplaces[0]['id'], name: workplaces[0]['name']}, {id: workplaces[1]['id'], name: workplaces[1]['name']}];
- }
- else
- {
- var connectQuery = 'oid = :id',
- connectId = {typ: 'wp', id: workplaces[0]['id']},
- ownWPs = [{id: workplaces[0]['id'], name: workplaces[0]['name']}];
- }
- // add connection-datas to lobby
- sdb.query(
- "SELECT * FROM connect WHERE typ = :typ AND (" + connectQuery+")", connectId,
- function( err, connections )
- {
- if( err ){ // error
- console.log('SQL error on find connection data of user: '+ uid);
- console.log( err );
- }else if( connections.length == 0 ){ // empty
- console.log('User ('+ uid +') no WP conection found!');
- }else{
- for( i in connections ){
- if( connections.hasOwnProperty(i) ){
- var conSrv = connections[i]['srv'],
- conWP = connections[i]['oid'];
- lobby.user[uid]['wps'][conWP][conSrv] = {};
- lobby.user[uid]['wps'][conWP][conSrv]['dev'] = JSON.parse(connections[i]['dev']);
- lobby.user[uid]['wps'][conWP][conSrv]['test'] = {}; // workplaces have this allways empty
- lobby.user[uid]['wps'][conWP][conSrv]['live'] = {}; // workplaces have this allways empty
- // switch acces from 0 to 1 if a connecetion (modul) allready exists
- lobby.user[uid]['wps'][conWP]['access'][conSrv] = 1;
- }
- }
- loadWP( uid, ownWPs, loadThisWP, loadThisPR, active );
- }
- }
- );
- }
- }
- );
- }
- else // user has page reload the socket session exist, use it!
- {
- var ownWPs = [];
- for( i in lobby.user[uid]['wps'] ){
- if( lobby.user[uid]['wps'].hasOwnProperty(i) && lobby.user[uid]['wps'][i]['own'] === true ){
- ownWPs.push( {id: i, name: lobby.user[uid]['wps'][i]['name']} );
- }
- }
- loadWP( uid, ownWPs, loadWP, false, false );
- }
- };
- function idePrepId( id, pref )
- {
- var prefix = ( pref !== false ) ? pref : '';
- var newId = prefix + id.replace(/\#/g, '_').replace(/\./g, '').replace(/\//g, '_').replace(/\\/g, '').replace(/\ /g, '').replace(/\(/g, '').replace(/\)/g, '');
- return newId.replace(/_+/g, '_');
- }
- function loadWP( uid, ownWPs, loadWP, loadPR, active ){
- var issetAcces = false, issetWP = false, issetPR = false;
- // load own projects & access to other Projects and Workplaces
- if( typeof lobby.user[uid]['prs'] == 'undefined' ){
- lobby.user[uid]['prs'] = {};
- // select own projects
- sdb.query(
- "SELECT id, name, typ FROM projects WHERE uid = :id", {id: uid},
- function( err, projects )
- {
- if( err ){ // error
- console.log('SQL error on find own projects of user: '+ uid);
- console.log( err );
- }else{
- for( i in projects ){
- if( projects.hasOwnProperty(i) ){
- var wpID = projects[i]['id'];
- lobby.user[uid]['prs'][wpID] = {};
- lobby.user[uid]['prs'][wpID]['name'] = projects[i]['name'];
- lobby.user[uid]['prs'][wpID]['typ'] = projects[i]['typ'];
- lobby.user[uid]['prs'][wpID]['role'] = 'owner';
- }
- }
- issetAcces = true;
- }
- }
- );
- // load access table for check access to stranger workspaces
- sdb.query(
- "SELECT `a`.*, `wp`.`name` FROM `access` AS `a` LEFT JOIN `workplaces` AS `wp` ON `wp`.`id` = `a`.`oid` WHERE `a`.`uid` = :id AND `a`.`typ` = :typ LIMIT 100", {id: uid, typ: 'wp'},
- function( err, result )
- {
- if( err ){ // error
- console.log('SQL error on find stranger workplaces for user: '+ uid);
- console.log( err );
- }else{
- // console.log('find stranger wp');
- // console.log(result);
- for( i in result ){
- if( result.hasOwnProperty(i) ){
- var wpID = result[i]['oid'];
- lobby.user[uid]['wps'][wpID] = {};
- lobby.user[uid]['wps'][wpID]['name'] = result[i]['name'];
- lobby.user[uid]['wps'][wpID]['role'] = result[i]['role'];
- lobby.user[uid]['wps'][wpID]['rights'] = JSON.parse(result[i]['rights']);
- lobby.user[uid]['wps'][wpID]['sort'] = result[i]['sort'];
- lobby.user[uid]['wps'][wpID]['access'] = {
- ftp: result[i]['ftp'],
- db: result[i]['db'],
- host: result[i]['host'],
- ssh: result[i]['ssh']
- };
- }
- }
- issetWP = true;
- }
- }
- );
- // load access table for check access to stranger projects
- sdb.query(
- "SELECT `a`.*, `pr`.`name` FROM `access` AS `a` LEFT JOIN `projects` AS `pr` ON `pr`.`id` = `a`.`oid` WHERE `a`.`uid` = :id AND `a`.`typ` = :typ LIMIT 100", {id: uid, typ: 'pr'},
- function( err, result )
- {
- if( err ){ // error
- console.log('SQL error on find stranger projects for user: '+ uid);
- console.log( err );
- }else{
- for( i in result ){
- if( result.hasOwnProperty(i) ){
- var prID = result[i]['oid'];
- lobby.user[uid]['prs'][prID] = {};
- lobby.user[uid]['prs'][prID]['name'] = result[i]['name'];
- lobby.user[uid]['prs'][prID]['role'] = result[i]['role'];
- lobby.user[uid]['prs'][prID]['rights'] = JSON.parse(result[i]['rights']);
- lobby.user[uid]['prs'][prID]['sort'] = result[i]['sort'];
- lobby.user[uid]['prs'][prID]['access'] = {
- ftp: JSON.parse(result[i]['ftp']),
- db: JSON.parse(result[i]['db']),
- host: JSON.parse(result[i]['host']),
- ssh: JSON.parse(result[i]['ssh'])
- };
- }
- }
- issetPR = true;
- }
- }
- );
- }
- else{ issetAcces = true; issetWP = true; issetPR = true; }
- // create a loop that wait of all DB-query`s. If we have all datas we execute the onLoad/reconnect process
- var executeLoop = setInterval(function(){
- if( issetAcces === true && issetWP === true && issetPR === true ){
- clearInterval(executeLoop);
- var emitWP = {},
- emitPR = {};
- // prepare the emit datas, we must remove server and conection datas
- for( i in lobby.user[uid]['wps'] ){
- if( lobby.user[uid]['wps'].hasOwnProperty(i) ){
- var server = lobby.user[uid]['wps'][i];
- emitWP[i] = {
- name: server.name,
- role: server.role,
- typ: server.typ
- };
- if( server['role'] != 'owner' ){ emitWP[i]['sort'] = server['sort']; }
- }
- }
- for( i in lobby.user[uid]['prs'] ){
- if( lobby.user[uid]['prs'].hasOwnProperty(i) ){
- var server = lobby.user[uid]['prs'][i];
- emitPR[i] = {
- name: server.name,
- role: server.role,
- typ: server.typ
- };
- if( server['role'] != 'owner' ){ emitPR[i]['sort'] = server['sort']; }
- }
- }
- // send server datas to the client. The client send new emit to establish the connections
- client.emit('wp', {e: 'setServers', wps: emitWP, prs: emitPR });
- }
- }, 500);
- }
- // create connection to a workplace or project
- function connectTo( typ, srvID, reconnect ){
- var uid = client.uid;
- var srv = lobby.user[uid][typ+'s'][srvID],
- srvDataExist = false, srvConDataExist = false,
- access = {};
- // es wird vorrausgesetzt das in der Lobby bereits ein Index an verfügbaren Projekten/Arbeitsplätzen besteht so dass wenn
- // ein Projekt geladen wird das noch keine Verbindung hat erst auf Anfrage, dessen Serverdaten aus der db geladen werden.
- // So muss die Lobby nicht jegliche Verbindungsdaten speichern und auf Grund des Indexes ist auch der Zugriff gewährleistet
- if( typeof lobby.user[uid][typ+'s'][srvID] != 'undefined' && typeof lobby.user[uid][typ+'s'][srvID]['srv'] == 'undefined' )
- {
- // get connectiondatas
- sdb.query(
- "SELECT * FROM connect WHERE typ = :typ AND oid = :oid", {typ: typ, oid: srvID},
- function( err, connections )
- {
- if( err ){ // error
- console.log('SQL error on find connection data of ID: '+ uid);
- console.log( err );
- }else{
- // get name and serverdatas
- var table = ( typ == 'pr' ) ? 'projects' : 'workplaces';
- sdb.query(
- "SELECT srv, domain FROM "+table+" WHERE id = :id", {id: srvID},
- function( err, srvData )
- {
- if( err ){ // error
- console.log('SQL error on find srv & name of ID: '+ uid);
- console.log( err );
- }else{
- lobby.user[uid][typ+'s'][srvID]['srv'] = srvData['srv'];
- lobby.user[uid][typ+'s'][srvID]['domain'] = srvData['domain'];
- srvDataExist = true;
- }
- }
- );
- for( i in connections ){
- if( connections.hasOwnProperty(i) ){
- var conSrv = connections[i]['srv'];
- lobby.user[uid][typ+'s'][srvID][conSrv] = {};
- lobby.user[uid][typ+'s'][srvID][conSrv]['dev'] = JSON.parse(connections[i]['dev']);
- if( typ == 'pr' ){
- lobby.user[uid][typ+'s'][srvID][conSrv]['test'] = JSON.parse(connections[i]['test']);
- lobby.user[uid][typ+'s'][srvID][conSrv]['live'] = JSON.parse(connections[i]['live']);
- }
- }
- }
- srvConDataExist = true;
- }
- }
- );
- }
- else if( typeof lobby.user[uid][typ+'s'][srvID] == 'undefined' )
- {
- noAccessToServer( srvID ); // emit has no access
- return false; // go out of this function (exit)
- }
- else
- {
- srvDataExist = true;
- srvConDataExist = true;
- }
- var executeConnection = setInterval(function(){
- if( srvDataExist === true && srvConDataExist === true )
- {
- clearInterval(executeConnection);
- lobby.user[uid][typ+'s'][srvID]['c'] = new ftpCon({
- host: srv.srv,
- port: srv.ftp.dev[0] // The port defaults to 21, but let's include it anyway.
- });
- lobby.user[uid][typ+'s'][srvID]['c'].on("error", function(err) {
- client.emit('wp', {e: 'wpError', error: 'FTP'+error.code});
- return false;
- });
- // First, we authenticate the user
- lobby.user[uid][typ+'s'][srvID]['c'].auth(srv.ftp.dev[1], srv.ftp.dev[2], function(err, res) {
- if( typeof err == 'undefined' ){
- lobby.user[uid][typ+'s'][srvID]['c'].raw('cwd '+srv.ftp.dev[3]); // set homepath
- // call the client server connection is established
- if( reconnect === false ){
- console.log('emit connected');
- client.emit('wp', {e: 'connectedTo', srvID: srvID, typ: typ, rights: lobby.user[uid][typ+'s'][srvID]['rights'], access: lobby.user[uid][typ+'s'][srvID]['access'] }); }
- }
- else{
- client.emit('wp', {e: 'wpError', error: typ+'Fail'});
- delete lobby.user[uid][typ+'s'][srvID]['c'];
- return false;
- }
- });
- return true;
- }
- }, 500);
- }
- function noAccessToServer( srvID ){
- client.emit('wp', {e: 'wpError', error: 'noSrvAccess', name: srvID});
- }
- // read a folder
- function readDir( ftp, path, task ){
- ftp.ls(path, function(err, res) {
- if( err ){
- console.log('error on read dir: ');
- console.log( err );
- client.emit('wp', {e: 'wpError', error: 'FTPrd'});
- }else{
- // emit to the initiator
- // client.emit('wp', {e: 'addTree', tree: res});
- // emit to online members
- if( task !== false ){
- // hier kommt noch ne foreach um jeden user durch zu laufen
- client.emit('wp', {e: 'addTree', tree: res, task: task});
- }
- else{ // wenn foreach da ist die else löschen
- client.emit('wp', {e: 'addTree', tree: res});
- }
- }
- });
- }
- // create dir
- function createDir( ftp, path, newDir, task ){
- ftp.raw("mkd", path+newDir, function(err, data) {
- if( err ){
- client.emit('wp', {e: 'wpError', error: 'FTPmkd'+err.code});
- }else{
- client.emit('wp', {e: 'wpSuccess', msg: 'dc'});
- readDir( ftp, ( path == '' ) ? '.' : path, task );
- }
- });
- }
- // create file
- function createFile( ftp, path, newFile, task ){
- ftp.put(new Buffer(''), path+newFile, function(hadError) {
- if( hadError ){
- client.emit('wp', {e: 'wpError', error: 'FTPcf', msg: hadError });
- }else{
- client.emit('wp', {e: 'wpSuccess', msg: 'fc'});
- readDir( ftp, (path == '') ? '.' : path, task );
- }
- });
- }
- // read file
- function readFile( ftp, file ){
- ftp.get(file, function(err, socket) {
- if( err ){
- client.emit('wp', {e: 'wpError', error: 'FTPrf'});
- }else{
- socket.on("data", function(d) {
- this.fileIsEmpty = false;
- client.emit('wp', {e: 'rf', content: d.toString() });
- });
- socket.on("close", function(hadErr) {
- // fallback is file empty
- if( typeof this.fileIsEmpty === 'undefined' ){
- client.emit('wp', {e: 'rf', content: '' });
- delete(this.fileIsEmpty);
- }
- if( hadErr ){ client.emit('wp', {e: 'wpError', error: 'FTPf'}); }
- });
- socket.resume();
- }
- });
- }
- // rename
- function rename( ftp, from, to, type, task ){
- var oldName = from.split('/').pop();
- ftp.rename(from, from.replaceLast(oldName, to), function(err, res) {
- if( err ){
- console.log( err );
- client.emit('wp', {e: 'wpError', error: 'FTPre'});
- }else{
- // emit to the initiator
- // client.emit('wp', {e: 'renamed'});
- // emit to online members
- if( task !== false ){
- task.oldPath = from;
- task.newName = to;
- task.typ = type;
- // hier kommt noch ne foreach um jeden user durch zu laufen
- client.emit('wp', {e: 'renamed', task});
- }
- else{ // wenn foreach da ist die else löschen
- client.emit('wp', {e: 'renamed', task});
- }
- }
- });
- }
- // remove file or dir - nachfolgende Funktionen gehören zur Löschfunktion
- function removeItem( ftp, item, type, task ){
- if( item != '' && item != '/' && item != './' ){
- if( type == 'd' ){
- // check is dir empty
- ftp.ls(item, function(err, res) {
- if( err ){
- client.emit('wp', {e: 'wpError', error: 'FTPrd'});
- }else{
- if( res.length == 0 ){
- ftp.raw('rmd', item, function(err, data) {
- if( err ){
- client.emit('wp', {e: 'wpError', error: 'FTPrem'+err.code});
- }else{
- // emit to the initiator
- // client.emit('wp', {e: 'deleted'});
- // emit to online members
- if( task !== false ){
- // hier kommt noch ne foreach um jeden user durch zu laufen
- client.emit('wp', {e: 'deleted', typ: type, item: task.item});
- }
- else{ // wenn foreach da ist die else löschen
- client.emit('wp', {e: 'deleted'});
- }
- }
- });
- }else{
- task.type = type;
- removeAllInFolder(ftp, item, false, task);
- }
- }
- });
- }else{
- ftp.raw('dele', item, function(err, data) {
- if( err ){
- client.emit('wp', {e: 'wpError', error: 'FTPrem'+err.code});
- }else{
- // emit to the initiator
- // client.emit('wp', {e: 'deleted'});
- // emit to online members
- if( task !== false ){
- // hier kommt noch ne foreach um jeden user durch zu laufen
- client.emit('wp', {e: 'deleted', typ: type, item: task.item});
- }
- else{ // wenn foreach da ist die else löschen
- client.emit('wp', {e: 'deleted'});
- }
- }
- });
- }
- }
- }
- function removeAllInFolder(ftp, mainFolder, onlyContent, task) {
- walk(ftp, mainFolder)
- .then((results) => {
- let files = flatten(results)
- .filter(Boolean);
- // add the mainfolder to the list if not only content
- if( !onlyContent ){
- var findName = mainFolder.split('/');
- files.push({
- name: findName[Object.keys(findName).length - 1],
- type: 1,
- filepath: mainFolder.replace('./', '')
- });
- }
- // console.log("About to try deleting ", files.map((file) => file.filepath));
- // Non-empty directories can't be removed, should I remove all files first?
- let deletions = files.map((file) => {
- if (isDirectory(file)) {
- return deleteDirectory(ftp, file);
- } else {
- return deleteFile(ftp, file);
- }
- });
- return Promise.all(deletions);
- }).then((deletionResults) => {
- console.log(task);
- // emit to the initiator
- // client.emit('wp', {e: 'deleted'});
- // emit to online members
- if( task !== false ){
- // hier kommt noch ne foreach um jeden user durch zu laufen
- client.emit('wp', {e: 'deleted', typ: task.type, item: task.item});
- }
- else{ // wenn foreach da ist die else löschen
- client.emit('wp', {e: 'deleted'});
- }
- // console.log("Deletion results: ", deletionResults);
- }).catch((error) => {
- client.emit('wp', {e: 'wpError', error: 'FTPrem', msg: error});
- // console.log("Error: ", error);
- });
- }
- function walk(ftp, directory) {
- return list(ftp, directory)
- .then((files) => {
- if (files.length === 0) {
- return Promise.resolve();
- }
- return Promise.all(files.map((file) => {
- file.filepath = path.join(directory, file.name);
- let promises = [];
- if (isDirectory(file)) {
- promises.push(walk(ftp, path.join(directory, file.name)));
- }
- // Make sure the directory is after the files in the list of promises
- promises.push(Promise.resolve(file));
- return Promise.all(promises);
- }));
- });
- }
- function deleteDirectory(ftp, directory) {
- return new Promise((resolve, reject) => {
- ftp.raw('rmd', directory.filepath, (error, result) => {
- if (error) {
- return reject(error);
- } else {
- return resolve(result);
- }
- });
- })
- }
- function deleteFile(ftp, file) {
- return new Promise((resolve, reject) => {
- ftp.raw('dele', file.filepath, (error, result) => {
- if (error) {
- return reject(error);
- } else {
- return resolve(result);
- }
- });
- })
- }
- function list(ftp, directory) {
- return new Promise((resolve, reject) => {
- ftp.ls(directory, (error, files) => {
- if (error) {
- reject(error);
- return;
- }
- resolve(files);
- });
- });
- }
- function isDirectory(file) {
- return file.type === 1;
- }
- const flatten = list => list.reduce( (a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), [] );
- /** contact interaction */
- client.on('contact', function(data){
- switch(data.e)
- {
- case 'getList': // emit: getList
- // console.log( wSrv );
- // wSrv['001'].emit("task", 'illexmedia', client.uid, 'readFolder', {path: '/'}); // wp, user, task, data)
- var contactList = lobby.user[client.uid]['contacts'];
- for (i = 0; i < contactList.length; ++i)
- {
- contactList[i]['online'] = ( lobby.isOn(contactList[i]['id']) ) ? 'online' : 'offlline';
- }
- client.emit('contact', {e: 'getListe', liste: contactList});
- break;
- case 'sendRequest': // emit: requestPosted
- var myID = client.uid,
- cID = data.id,
- grp = data.gid;
- console.log('goRequest to: '+cID+' group: '+grp);
- if( vali.isInt(cID) && vali.isInt(grp, { min: 1, max: 7 }) )
- {
- console.log('go querys');
- db.query("SELECT status FROM contacts WHERE uid LIKE :myId AND cid = :cid LIMIT 1", {myId: myID, cid: cID}, // check db of exist request
- function( err, result )
- {
- if( err )
- {
- socket.emit('error', 'db_error');
- }
- else if( result.length == 0 ) // no request exist
- {
- var datum = new Date().dateTime();
- var insert = "INSERT INTO contacts (uid, cid, status, grp, date) VALUES (:m_id, :m_cid, '2', :m_grp, :m_date), (:u_id, :u_cid, '3', :u_grp, :u_date)"; // insert request
- db.query(
- insert, {m_id: myID, m_cid: cID, m_grp: grp, m_date: datum, u_id: cID, u_cid: myID, u_grp: grp, u_date: datum },
- function( err, result )
- {
- console.log( result );
- }
- );
- // client.emit('requestPosted', 'empty');
- }
- else
- {
- console.log('request exist');
- }
- }
- );
- }
- break;
- case 'cancleRequest':
- break;
- case 'add':
- break;
- case 'remove':
- break;
- case 'block':
- break;
- case 'reject':
- deliver(socket.id, 8, {'testReceive': 'Bla'});
- break;
- case 'rejectBlock':
- break;
- case 'notNew':
- break;
- case 'chat':
- break;
- }
- });
- /** header searchbar */
- client.on('searchbar',function(data){
- var string='';
- switch( data['group'] )
- {
- case 'accounts':
- string = "SELECT persons, pid FROM accounts WHERE persons LIKE :param";
- var temp = data.string.substr(0, 20).split(" ");
- data.string = '%'+temp.join(',')+'%';
- break;
- }
- if( string != '' )
- {
- db.query(
- string, {param: data.string, f_tags: ['<a>','<php>']},
- function( err, result )
- {
- if( err ){
- client.emit('searBarResult', 'error');
- }else if( result.length == 0 ){
- client.emit('searBarResult', 'empty');
- }else{
- client.emit('searBarResult', {typ: data['group'], result: result});
- }
- }
- );
- }
- });
- /** emit handlings */
- client.on('testEmit',function(data)
- {
- console.log('klick received: '+ data);
- // if( lobby.checkSpam('testEmit', arguments) ) // die lobby muss dann nach entsprechender Verarbeitung ture oder false liefern um die Anfrage weiter verarbeiten zu können
- // {
- // lobby.deliver( client.uid, 1, {'testReceive': {msg: "server empfang und sendete zurück..."}}, 'main');
- // }
- });
- });
- console.log('Juhu Server running');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement