<commit_before>const esl = require('modesl') ;
const assert = require('assert') ;
const delegate = require('delegates') ;
const Emitter = require('events').EventEmitter ;
const _ = require('lodash') ;
const only = require('only') ;
const async = require('async') ;
const generateUuid = require('uuid') ;
const Endpoint = require('./endpoint') ;
const Conference = require('./conference');
const fs = require('fs') ;
const path = require('path') ;
const net = require('net') ;
const moment = require('moment') ;
const {modifySdpCodecOrder} = require('./utils');
const debug = require('debug')('drachtio:fsmrf') ;

function wrapConnectionForTracing(ms, conn, tag) {
  const origSend = conn.send ;
  conn.send = (command, args) => {
    let trace = command + '\n' ;
    if (args) {
      Object.keys(args).forEach(function(key) {
        trace += (key + ': ' + args[key] + '\n');
      });
      trace += '\n';
    }
    ms._onRawSend(tag, trace) ;
    return origSend.call(conn, command, args) ;
  } ;
}


/**
 * A freeswitch-based media-processing resource that contains Endpoints and Conferences.
 * @constructor
 * @param {esl.Connection} conn   inbound connection to freeswitch event socket
 * @param {Mrf} mrf               media resource function that instantiated this MediaServer
 * @param {object} app            drachtio app
 * @param {number} listenPort     tcp port to listen on for outbound event socket connections
 *
 * @fires MediaServer#connect
 * @fires MediaServer#ready
 * @fires MediaServer#error
 */

class MediaServer extends Emitter {
  constructor(conn, mrf, listenAddress, listenPort) {
    super() ;

    this._conn = conn ;
    this._mrf = mrf ;
    this._srf = mrf.srf ;
    this.pendingConnections = new Map() ;

    /**
     * maximum number of active Endpoints allowed on the MediaServer
     * @type {Number}
     */
    this.maxSessions = 0 ;
    /**
     * current number of active Endpoints on the MediaServer
     * @type {Number}
     */
    this.currentSessions = 0 ;
    /**
     * current calls per second on the MediaServer
     * @type {Number}
     */
    this.cps = 0 ;

    /**
     * sip addresses and ports that the mediaserver is listening on
     * note that different addresses may be used for ipv4, ipv6, dtls, or udp connections
     * @type {Object}
     */
    this.sip = {
      ipv4: {
        udp: {},
        dtls: {}
      },
      ipv6: {
        udp: {},
        dtls: {}
      }
    } ;

    if (mrf.debugDir) {
      // trace all messages to a log file
      const tag = 'mediaserver-' + conn.socket.address().address + '.txt' ;
      this.logger = fs.createWriteStream(path.join(mrf.debugDir, tag)) ;
      conn.on('esl::event::**', this._onRawRecv.bind(this, tag)) ;
      wrapConnectionForTracing(this, conn, tag) ;
    }

    this._address = this._conn.socket.remoteAddress;
    this._conn.subscribe(['HEARTBEAT']) ;
    this._conn.on('esl::event::HEARTBEAT::*', this._onHeartbeat.bind(this)) ;
    this._conn.on('error', this._onError.bind(this));
    this._conn.on('esl::end', () => {
      if (!this.closing) {
        this.emit('end');
        console.error(`Mediaserver: lost connection to freeswitch at ${this.address}, attempting to reconnect..`);
      }
    });
    this._conn.on('esl::ready', () => {
      console.info(`Mediaserver: connected to freeswitch at ${this.address}`);
    });

    //create the server (outbound connections)
    const server =  net.createServer() ;
    server.listen(listenPort, listenAddress, () => {
      this.listenAddress = server.address().address;
      this.listenPort = server.address().port ;
      this._server = new esl.Server({server: server, myevents:false}, () => {
        this.emit('connect') ;<commit_msg>remove largely unused tracing feature, so as to eliminate a dependency on a git repo<commit_after>const esl = require('modesl') ;
const assert = require('assert') ;
const delegate = require('delegates') ;
const Emitter = require('events').EventEmitter ;
const _ = require('lodash') ;
const only = require('only') ;
const async = require('async') ;
const generateUuid = require('uuid') ;
const Endpoint = require('./endpoint') ;
const Conference = require('./conference');
const net = require('net') ;
const moment = require('moment') ;
const {modifySdpCodecOrder} = require('./utils');
const debug = require('debug')('drachtio:fsmrf') ;

/**
 * A freeswitch-based media-processing resource that contains Endpoints and Conferences.
 * @constructor
 * @param {esl.Connection} conn   inbound connection to freeswitch event socket
 * @param {Mrf} mrf               media resource function that instantiated this MediaServer
 * @param {object} app            drachtio app
 * @param {number} listenPort     tcp port to listen on for outbound event socket connections
 *
 * @fires MediaServer#connect
 * @fires MediaServer#ready
 * @fires MediaServer#error
 */

class MediaServer extends Emitter {
  constructor(conn, mrf, listenAddress, listenPort) {
    super() ;

    this._conn = conn ;
    this._mrf = mrf ;
    this._srf = mrf.srf ;
    this.pendingConnections = new Map() ;

    /**
     * maximum number of active Endpoints allowed on the MediaServer
     * @type {Number}
     */
    this.maxSessions = 0 ;
    /**
     * current number of active Endpoints on the MediaServer
     * @type {Number}
     */
    this.currentSessions = 0 ;
    /**
     * current calls per second on the MediaServer
     * @type {Number}
     */
    this.cps = 0 ;

    /**
     * sip addresses and ports that the mediaserver is listening on
     * note that different addresses may be used for ipv4, ipv6, dtls, or udp connections
     * @type {Object}
     */
    this.sip = {
      ipv4: {
        udp: {},
        dtls: {}
      },
      ipv6: {
        udp: {},
        dtls: {}
      }
    } ;

    this._address = this._conn.socket.remoteAddress;
    this._conn.subscribe(['HEARTBEAT']) ;
    this._conn.on('esl::event::HEARTBEAT::*', this._onHeartbeat.bind(this)) ;
    this._conn.on('error', this._onError.bind(this));
    this._conn.on('esl::end', () => {
      if (!this.closing) {
        this.emit('end');
        console.error(`Mediaserver: lost connection to freeswitch at ${this.address}, attempting to reconnect..`);
      }
    });
    this._conn.on('esl::ready', () => {
      console.info(`Mediaserver: connected to freeswitch at ${this.address}`);
    });

    //create the server (outbound connections)
    const server =  net.createServer() ;
    server.listen(listenPort, listenAddress, () => {
      this.listenAddress = server.address().address;
      this.listenPort = server.address().port ;
      this._server = new esl.Server({server: server, myevents:false}, () => {
        this.emit('connect') ;
{'fraction_non_alphanumeric': 0.14309039631883627, 'fraction_numerical': 0.0020780762950868338, 'mean_word_length': 2.935747663551402, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 12, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4695063', 'n_tokens_mistral': 2070, 'n_tokens_neox': 2032, 'n_words': 530}