<commit_before>/*
 The MIT License (see LICENSE)
 Copyright (C) 2014-2015 Teem2 LLC
*/
/**
 * @class CompositionServer {Internal}
 * Holder of the dreem <composition> for the server
 * Manages all iOT objects and the BusServer for each Composition
 */
define(function(require, exports, module) {
  module.exports = CompositionServer;

  var path = require('path'),
    fs = require('fs'),

    ExternalApps = require('./externalapps'),
    BusServer = require('./busserver'),
    FileWatcher = require('./filewatcher'),
    HTMLParser = require('./htmlparser'),
    DreemError = require('./dreemerror'),
    dreemCompiler = require('./dreemcompiler');

    var UAParser = require('ua-parser-js');

  /**
    * @constructor
    * @param {Object} args Process arguments
    * @param {String} file_root File server root
    * @param {String} name Name of the composition .dre
    */
  function CompositionServer(args, name, teemserver) {
    this.teemserver = teemserver;
    this.args = args;
    this.name = name;

    this.busserver = new BusServer();
    this.watcher = new FileWatcher();
    this.watcher.onChange = function(file) {
      this.__reloadComposition();
      
      // Tell the client to refresh itself.
      teemserver.broadcast({type:'filechange', file:file});
    }.bind(this);
    
    // lets compile and run the dreem composition
    define.onRequire = function(filename) {
      // lets output to the main watcher
      process.stderr.write('\x0F!' + filename + '\n', function() {});
      this.watcher.watch(filename);
    }.bind(this);
    
    this.__reloadComposition();
  };

  body.call(CompositionServer.prototype);

  function body() {
    /**
      * @method request
      * Handle server request for this Composition
      * @param {Request} req
      * @param {Response} res
      */
    this.request = function(req, res) {
      // Extract Query and remove it from URL
      var url = req.url,
        query = {}, 
        queryIndex = url.indexOf('?');
      if (queryIndex !== -1) {
        var queryStr = url.substring(queryIndex + 1);
        url = url.substring(0, queryIndex);
        
        if (queryStr) {
          var parts = queryStr.split('&'), i = 0, len = parts.length, nvp;
          for (; len > i; i++) {
            nvp = parts[i].split('=');
            query[nvp[0]] = nvp[1] == null ? null : nvp[1]; // Clobber instead of support for multivalue query params
          }
        }
      }
      
      // handle editor requests
      if (query.edit) {
        if (req.method == 'POST') {
          var buf = ''
          req.on('data', function(data) {buf += data.toString();});
          req.on('end', function() {
            var comppath = define.expandVariables(this.__getCompositionPath())
            this.__saveEditableFile(query.screen || 'default', comppath, buf, query.stripeditor === '1');
            res.writeHead(200, {"Content-Type":"text/json"});
            res.end();
          }.bind(this));
          return;
        } else {
          var comppath = define.expandVariables(this.__getCompositionPath()),
            data = this.__readFile(comppath),
            htmlParser = new HTMLParser(),
            jsobj = htmlParser.parse(data);
          this.__walkChildren(query.screen || 'default', jsobj, query.stripeditor === '1')
          this.__writeFileIfChanged(comppath, HTMLParser.reserialize(jsobj, '  '))
          
          var redirectUrl = url;
          redirectUrl += (query.screen ? '?screen=' + query.screen : '');
          res.writeHead(302, {
            'Location':redirectUrl
            //add other headers here...
          });
          res.end();
          return;
        }
      }
      
      if (query.raw) {
        var comppath = define.expandVariables(this.__getCompositionPath())
        res.writeHead(200, {"Content-Type":"text/text"});
        res.write(this.__readFile(comppath));
        res.end();
        return;
      }

      // Serve our Composition device
      if (req.method == 'POST') {
        // lets do an RPC call
        var buf = ''<commit_msg>Give the server extra time to write files to disk when entering edit mode<commit_after>/*
 The MIT License (see LICENSE)
 Copyright (C) 2014-2015 Teem2 LLC
*/
/**
 * @class CompositionServer {Internal}
 * Holder of the dreem <composition> for the server
 * Manages all iOT objects and the BusServer for each Composition
 */
define(function(require, exports, module) {
  module.exports = CompositionServer;

  var path = require('path'),
    fs = require('fs'),

    ExternalApps = require('./externalapps'),
    BusServer = require('./busserver'),
    FileWatcher = require('./filewatcher'),
    HTMLParser = require('./htmlparser'),
    DreemError = require('./dreemerror'),
    dreemCompiler = require('./dreemcompiler');

    var UAParser = require('ua-parser-js');

  /**
    * @constructor
    * @param {Object} args Process arguments
    * @param {String} file_root File server root
    * @param {String} name Name of the composition .dre
    */
  function CompositionServer(args, name, teemserver) {
    this.teemserver = teemserver;
    this.args = args;
    this.name = name;

    this.busserver = new BusServer();
    this.watcher = new FileWatcher();
    this.watcher.onChange = function(file) {
      this.__reloadComposition();
      
      // Tell the client to refresh itself.
      teemserver.broadcast({type:'filechange', file:file});
    }.bind(this);
    
    // lets compile and run the dreem composition
    define.onRequire = function(filename) {
      // lets output to the main watcher
      process.stderr.write('\x0F!' + filename + '\n', function() {});
      this.watcher.watch(filename);
    }.bind(this);
    
    this.__reloadComposition();
  };

  body.call(CompositionServer.prototype);

  function body() {
    /**
      * @method request
      * Handle server request for this Composition
      * @param {Request} req
      * @param {Response} res
      */
    this.request = function(req, res) {
      // Extract Query and remove it from URL
      var url = req.url,
        query = {}, 
        queryIndex = url.indexOf('?');
      if (queryIndex !== -1) {
        var queryStr = url.substring(queryIndex + 1);
        url = url.substring(0, queryIndex);
        
        if (queryStr) {
          var parts = queryStr.split('&'), i = 0, len = parts.length, nvp;
          for (; len > i; i++) {
            nvp = parts[i].split('=');
            query[nvp[0]] = nvp[1] == null ? null : nvp[1]; // Clobber instead of support for multivalue query params
          }
        }
      }
      
      // handle editor requests
      if (query.edit) {
        if (req.method == 'POST') {
          var buf = ''
          req.on('data', function(data) {buf += data.toString();});
          req.on('end', function() {
            var comppath = define.expandVariables(this.__getCompositionPath())
            this.__saveEditableFile(query.screen || 'default', comppath, buf, query.stripeditor === '1');
            res.writeHead(200, {"Content-Type":"text/json"});
            res.end();
          }.bind(this));
          return;
        } else {
          var comppath = define.expandVariables(this.__getCompositionPath()),
            data = this.__readFile(comppath),
            htmlParser = new HTMLParser(),
            jsobj = htmlParser.parse(data);
          this.__walkChildren(query.screen || 'default', jsobj, query.stripeditor === '1')
          this.__writeFileIfChanged(comppath, HTMLParser.reserialize(jsobj, '  '))
          
          var redirectUrl = url;
          redirectUrl += (query.screen ? '?screen=' + query.screen : '');
          setTimeout(function() {
            res.writeHead(302, {
              'Location':redirectUrl
              //add other headers here...
            });
            res.end();
          }, 1000);
          return;
        }
      }
      
      if (query.raw) {
        var comppath = define.expandVariables(this.__getCompositionPath())
        res.writeHead(200, {"Content-Type":"text/text"});
        res.write(this.__readFile(comppath));
        res.end();
        return;
      }

      // Serve our Composition device
      if (req.method == 'POST') {
        // lets do an RPC call
        var buf = ''
{'fraction_non_alphanumeric': 0.1398161586840832, 'fraction_numerical': 0.00725689404934688, 'mean_word_length': 2.2150077760497666, 'pattern_counts': {'":': 4, '<': 5, '<?xml version=': 0, '>': 7, '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': '6506881', 'n_tokens_mistral': 2427, 'n_tokens_neox': 2360, 'n_words': 587}