exports.create = function( log ) {
   'use strict';

   var REQUIRE_CONFIG_NAME = exports.REQUIRE_CONFIG_NAME;
   var INDENT_DEPTH = 3;
   var LOG_PREFIX = 'requireConfigMerger: ';

   var fs = require( 'fs' );
   var q = require( 'q' );
   var path = require( './path-platform/path' ).posix;
   var _ = require( 'lodash' );

   var readFile = q.denodeify( fs.readFile );

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   var api = {
      merge: merge
   };

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   function merge( requireConfigPaths ) {
      return q.all( requireConfigPaths.map( function( requireConfigPath ) {
         return readFile( path.join( requireConfigPath, REQUIRE_CONFIG_NAME ), 'utf-8' )
            .then( function( content ) {
               return { path: requireConfigPath, content: content };
            } );
      } ) )
         .then( function( requireInfos ) {
            var mergedConfig = requireInfos
               .filter( function( requireInfos ) {
                  return !!requireInfos.content;
               } )
               .map( parseContents )
               .reduce( mergeRequireConfigs, {} );

            var result =
               '/*jshint quotmark:false,-W079*/\n' + // ignore quote type and possible redefinition of require
               'var require = ' + serializeConfig( mergedConfig, 0 ) + ';';
            return result;
         } );
   }

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   function parseContents( requireInfo ) {
      var code = 'return (function() { ' + requireInfo.content + '; return require; })();';
      /* jshint evil:true */
      return {
         path: requireInfo.path,
         config: new Function( code )()
      };
   }

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   function mergeRequireConfigs( existingConfig, appendeeInfo ) {
      var configToAppend = appendeeInfo.config;
      Object.keys( configToAppend )
         .forEach( function( prop ) {
            if( !configToAppend.hasOwnProperty( prop ) ) {
               return;
            }

            if( !existingConfig.hasOwnProperty( prop ) ) {
               existingConfig[ prop ] = configToAppend[ prop ];
               return;
            }

            if( mergers.hasOwnProperty( prop ) ) {
               mergers[ prop ]( existingConfig, appendeeInfo, configToAppend[ prop ] );
            }
            // anything else won't be merged or overwritten
         } );

      return existingConfig;
   }

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   var mergers = {

      deps: function( config, appendeeInfo, propertyConfig ) {
         config.deps = _.union( config.deps, propertyConfig );
      },

      ////////////////////////////////////////////////////////////////////////////////////////////////////////

      paths: function( config, appendeeInfo, propertyConfig ) {
         Object.keys( propertyConfig )
            .forEach( function( moduleName ) {
               if( isConfiguredAsPackage( moduleName, config ) ) {
                  var requireName = path.join( appendeeInfo.path, REQUIRE_CONFIG_NAME );
                  log.warn( LOG_PREFIX + 'WARN:', '"' + moduleName + '" is already configured as package. ' +
                     '\n  Skipping path configuration found in "' + requireName + '".' );
                  return;
               }
               var modulePath = propertyConfig[ moduleName ];
               if( config.paths.hasOwnProperty( moduleName ) && config.paths[ moduleName ] !== modulePath ) {
                  // Whenever an already configured path for a module differs from the configured path of
                  // another require configuration, we add a map entry in that modules path mapping
                  if( !config.hasOwnProperty( 'map' ) ) {
                     config.map = {};
                  }
                  if( !config.map.hasOwnProperty( appendeeInfo.path ) ) {
                     config.map[ appendeeInfo.path ] = {};
                  }

                  var appendeeMap = config.map[ appendeeInfo.path ];
                  if( !appendeeMap.hasOwnProperty( moduleName ) ) {
                     appendeeMap[ moduleName ] = modulePath;
                  }
               }
               else {
                  config.paths[ moduleName ] = modulePath;
               }
            } );
      },

      ////////////////////////////////////////////////////////////////////////////////////////////////////////

      shim: function( config, appendeeInfo, propertyConfig ) {
         config.shim = _.assign( propertyConfig, config.shim );
      },

      ////////////////////////////////////////////////////////////////////////////////////////////////////////

      map: function( config, appendeeInfo, propertyConfig ) {
         if( !config.map ) {
            config.map = {};
         }

         Object.keys( propertyConfig )
            .forEach( function( mapRootDir ) {
               var newMapRootDir = path.join( appendeeInfo.path, mapRootDir === '*' ? '' : mapRootDir );
               var mapping = propertyConfig[ mapRootDir ];
               if( !config.map.hasOwnProperty( newMapRootDir ) ) {
                  config.map[ newMapRootDir ] = mapping;
               }
               else {
                  _.assign( config.map[ newMapRootDir ], mapping );
               }
            } );
      },

      ////////////////////////////////////////////////////////////////////////////////////////////////////////

      packages: function( config, appendeeInfo, propertyConfig ) {
         propertyConfig.forEach( function( newPackage ) {
            if( !config.packages.some( function( _ ) { return _.name === newPackage.name; } ) ) {
               config.packages.push( newPackage );
            }
         } );
      }

   };

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   function serializeConfig( object, indentLevel ) {
      if( Array.isArray( object ) ) {
         if( object.length === 0 ) {
            return '[]';
         }
         return '[\n' + indentString( indentLevel + 1 ) +
            object
               .map( function( entry ) { return serializeConfig( entry, indentLevel + 1 ); } )
               .join( ',\n' + indentString( indentLevel + 1 ) ) +
            '\n' + indentString( indentLevel ) + ']';
      }

      if( Object.prototype.toString.call( object ) === '[object Object]' ) {
         return '{ ' +
            Object.keys( object )
               .map( function( key ) {
                  return '\n' + indentString( indentLevel + 1 ) +
                     JSON.stringify( key ) + ': ' +
                     serializeConfig( object[ key ], indentLevel + 1 );
               } ).join( ', ') +
            '\n' + indentString( indentLevel ) + '}';
      }

      if( typeof object === 'function' ) {
         return object.toString();
      }

      return JSON.stringify( object );
   }

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   function isConfiguredAsPackage( moduleName, config ) {
      var modulePrefix = moduleName.split( '/' )[0];
      return ( config.packages || [] ).some( function( packageConfig ) {
         return packageConfig.name === modulePrefix;
      } );
   }

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   function indentString( indentLevel ) {
      if( indentLevel <= 0 ) {
         return '';
      }
      return new Array( indentLevel * INDENT_DEPTH + 1 ).join( ' ' );
   }

   return api;

};
Example #2
0
  } catch (err) {
    if (err.code === 'ENOENT') {
      // Parent directory doesn't exist,
      // so just create it and write the file.
      writeFileSync(path, data, options);
    } else {
      throw err;
    }
  }
};

// ---------------------------------------------------------
// ASYNC
// ---------------------------------------------------------

var promisedReadFile = Q.denodeify(fs.readFile);
var promisedRename = Q.denodeify(fs.rename);
var promisedWriteFile = Q.denodeify(fs.writeFile);
var promisedAppendFile = Q.denodeify(fs.appendFile);
var promisedMkdirp = Q.denodeify(mkdirp);

var readAsync = function (path, returnAs) {
  var deferred = Q.defer();

  var retAs = returnAs || 'utf8';
  var encoding = 'utf8';
  if (retAs === 'buffer') {
    encoding = null;
  } else if (retAs === 'buf') {
    console.warn("[fs-jetpack] DEPRECATION WARNING: Please use 'buffer' " +
      "instead of 'buf' in read() method.");
Example #3
0
'use strict';
var Q = require('q');
var readFile = Q.denodeify(require('fs').readFile);
var resolve = require('path').resolve;

function presetOpts(cb) {
  var parserOpts = {
    headerPattern: /^(\w*)\: (.*)$/,
    headerCorrespondence: [
      'component',
      'shortDesc'
    ]
  };

  var writerOpts = {
    transform: function(commit) {
      if (commit.component === 'perf') {
        commit.component = 'Performance';
      } else if (commit.component === 'deps') {
        commit.component = 'Dependencies';
      } else {
        return;
      }

      return commit;
    },
    groupBy: 'component',
    commitGroupsSort: 'title',
    commitsSort: ['component', 'shortDesc']
  };
Example #4
0
#!/opt/node/bin/node

var fs = require('fs');
var promise = require('q'); 
var read = promise.denodeify(require('fs').readFile)


var XivelyClient = require('xively');
var x = new XivelyClient();
var FEED_ID = "2047342041";
x.setKey('YOGj6nNmTRiciDSg2ioX5iamkxtJyYWiGoTZ6nseSWdys5nM');

var dp = {
      "version":"1.0.0",
       "datastreams" : [ ]
}

read('/home/pi/pi-status/system.txt')
.then(function (content) {
  var obj = JSON.parse(content);
  var ram = obj.ram
  var cpu_temp =  obj.temp
  ram.used = ram.total-ram.free 

  dp.datastreams[0] = { "id": "ram_used", "current_value": ram.used/1024}; 
  dp.datastreams[1] = { "id": "ram_free", "current_value": ram.free/1024}; 
  dp.datastreams[2] = { "id": "ram_total", "current_value": ram.total/1024}; 
  dp.datastreams[3] = { "id": "cpu_temperature_raw", "current_value": cpu_temp }; 
})
.then(function() { 
  x.feed.new(FEED_ID, {
Example #5
0
            c.path.substr(c.root.path.length + 1) + (c.props.Directory === true ? '/' : '')
        );
    });

    ig.on('end', function() {
        // Normalize paths on Windows
        if(process.platform === 'win32') {
            return d.resolve(files.map(function(file) {
                return file.replace(/\\/g, '/');
            }));
        }

        // Simply return paths otherwise
        return d.resolve(files);
    });

    ig.on('error', d.reject);

    return d.promise;
};

module.exports = {
    list: getFiles,
    readFile: Q.denodeify(fs.readFile),
    writeFile: Q.denodeify(fs.writeFile),
    mkdirp: Q.denodeify(fsExtra.mkdirp),
    copy: Q.denodeify(fsExtra.copy),
    remove: Q.denodeify(fsExtra.remove),
    symlink: Q.denodeify(fsExtra.symlink),
};
Example #6
0
function finishRequest(parsed, on_finish) {
  var renderer = getRenderer();
  var rendered;
  var name;
  var template;
  var context;
  var context_func;
  var cached;
  var loadTemplate = memoExpiring('templates',
    Q.denodeify(defaultLoader.get.bind(defaultLoader)));
  var loadContextHandler = memoExpiring('contextHandlers',
    Q.denodeify(defaultContextHandler.getFn.bind(defaultContextHandler)));

  name = parsed.template;
  if (renderer.cacheGet) cached = renderer.cacheGet(name);

  if (!parsed.complete) {
    return on_finish(new Error('invalid request'), null);
  }

  return loadTemplate(name)
  .then(function(tmpl) {
    template = tmpl;
    if (parsed.handler) {
      return loadContextHandler(parsed.handler)
      .then(function(contextFn) {
        return contextFn;
      });
    }
    return null;
  })
  .then(function(context_func) {
    if (context_func) {
      return context_func(parsed.context);
    }
    return parsed.context;
  })
  .then(function(ctx) {
    context = ctx;
    if (parsed.asfunc) {
      if (renderer.compile) {
        rendered = renderer.compile(name, template);
        return rendered;
      }

      var err = 'Templating interface ' + renderer.name + ' does not support compilation';
      return new Error(err);
    }

    if (cached) {
      rendered = cached(context || {});
      return rendered;
    }

    rendered = renderer.render(name, template, context || {});
    return rendered;
  })
  .then(function(res) {
    on_finish(null, res);
  })
  .catch(function (err) {
    on_finish(err, null);
  });
}
Example #7
0
   * @param key
   *   The key to convert
   * @return
   *   The form component key
   */
  getFormComponentKey: function(key) {
    return key.replace(/\.data\./g, '.');
  },

  /**
   * A promisified version of request. Use this if you need
   * to be able to mock requests for tests, as it's much easier
   * to mock this than the individual required 'request' modules
   * in each file.
   */
  request: Q.denodeify(require('request')),

  /**
   * Utility function to ensure the given id is always a BSON object.
   *
   * @param _id {String|Object}
   *   A mongo id as a string or object.
   *
   * @returns {Object}
   *   The mongo BSON id.
   */
  idToBson: function(_id) {
    return _.isObject(_id)
      ? _id
      : mongoose.Types.ObjectId(_id);
  },
Example #8
0
var start = new Date();
var Q = require("q");
var FS = require("fs");
var marked = require("marked");
var ncp = require('ncp').ncp;

// Convert Node callback APIs to Q promise ones.
var readFile = Q.denodeify(FS.readFile);
var writeFile = Q.denodeify(FS.writeFile);
var readdir = Q.denodeify(FS.readdir);
var mkdir = Q.denodeify(FS.mkdir);
var exists = function(path) { // Doesn't behave like other FS.xyz functions...
    var dfd = Q.defer();
    FS.exists(path, dfd.resolve);
    return dfd.promise;
};

var faqs = {};
var entryHeader, entryFooter, chapterHeader, chapterFooter,
    tocHeader, tocFooter, indexHeader, indexFooter, indexHeader2;
var inputFolder = "../faq-src";
var outputFolder = "../output";
var resourceFolder = "../resources";
var templateFolder = "../templates";

var indexFilter = function(include) {
    return function(item) {
        return include ? (item === "index") : (item !== "index");
    };
};
var noIndex = indexFilter(false);
Example #9
0
FileStore = function() {
  var Q, fs, read, write;
  Q = require("q");
  fs = require("fs");
  write = Q.denodeify(fs.writeFile);
  read = Q.denodeify(fs.readFile);
  return FileStore = (function(_super) {
    var _checkDir;

    __extends(FileStore, _super);

    function FileStore(options) {
      var opts;
      opts = {
        directory: "./.jefri"
      };
      _(opts).extend(options);
      FileStore.__super__.constructor.call(this, opts);
      _checkDir(this.settings.directory);
      this.storage = this.settings.directory;
    }

    FileStore.prototype._set = function(key, value) {
      var path;
      path = this._buildPath(key);
      return fs.writeFileSync(path, value);
    };

    FileStore.prototype._get = function(key) {
      var path;
      path = this._buildPath(key);
      try {
        return fs.readFileSync(path);
      } catch (_error) {
        return "{}";
      }
    };

    FileStore.prototype._buildPath = function(key) {
      var path;
      key = key.split('/');
      path = "" + this.storage + "/" + key[0];
      _checkDir(path);
      if (key.length === 1) {
        key[1] = "list";
      }
      path = "" + path + "/" + key[1];
      return path;
    };

    _checkDir = function(directory) {
      var dir;
      try {
        dir = fs.statSync(directory);
      } catch (_error) {
        fs.mkdirSync(directory);
        dir = fs.statSync(directory);
      }
      if (!dir.isDirectory()) {
        throw "FileStorage target isn't a directory: " + directory;
      }
    };

    return FileStore;

  })(JEFRi.Stores.ObjectStore);
};
Example #10
0
// assertions everywhere to make sure that we are not dealing with a ZIP type
// that I haven't designed for. Things like spanning archives, non-DEFLATE
// compression, encryption, etc.
var fs = require('graceful-fs');
var Q = require('q');
var path = require('path');
var util = require('util');
var events = require('events');
var structures = require('./structures');
var signatures = require('./signatures');
var extractors = require('./extractors');
var FileDetails = require('./file-details');

// Denodify some node lib methods

var fstat = Q.denodeify(fs.fstat);
var read = Q.denodeify(fs.read);
var fopen = Q.denodeify(fs.open);

// Class definition

function DecompressZip(filename) {
    events.EventEmitter.call(this);

    this.filename = filename;
    this.stats = null;
    this.fd = null;
    this.chunkSize = 1024 * 1024; // Buffer up to 1Mb at a time

    // When we need a resource, we should check if there is a promise for it
    // already and use that. If the promise is already fulfilled we don't do the
Example #11
0
 .then(function () {
   muted = false;
   var play = Q.denodeify(channel.play.bind(channel));
   return play({media: soundToPlay}, currentPlayback);
 })
Example #12
0
var stream = require('stream');
if (!stream.Readable) {
    var stream = require('readable-stream');
}
var fs = require('fs');
var Q = require('q');
var path = require('path');
var zlib = require('zlib');
var touch = Q.denodeify(require('touch'));
var mkpath = Q.denodeify(require('mkpath'));
var writeFile = Q.denodeify(fs.writeFile);
var inflateRaw = Q.denodeify(zlib.inflateRaw);
var symlink = Q.denodeify(fs.symlink);
var stat = Q.denodeify(fs.stat);
var cache = {};

// Use a cache of promises for building the directory tree. This allows us to
// correctly queue up file extractions for after their path has been created,
// avoid trying to create the path twice and still be async.
var mkdir = function (dir) {
    dir = path.normalize(path.resolve(process.cwd(), dir) + path.sep);

    if (!cache[dir]) {
        var parent;

        if (fs.existsSync(dir)) {
            parent = new Q();
        } else {
            parent = mkdir(path.dirname(dir));
        }
Example #13
0
/* eslint no-console: 0 */

'use strict';

var Q = require('q');
var os = require('os');
var childProcess = require('child_process');
var promisedExec = Q.denodeify(childProcess.exec);
var jetpack = require('..');

var startTimer = function () {
    var start = Date.now();
    return function stop() {
        return Date.now() - start;
    };
};

var testDir = jetpack.dir(os.tmpdir() + '/jetpack-benchmark', { empty: true });
var toCopyDir = testDir.dir('to-copy');

for (var i = 0; i < 10000; i += 1) {
    toCopyDir.file(i + '.txt', { content: 'text' });
    toCopyDir.file(i + '.md', { content: 'markdown' });
}

var stop;
var jetpackTime;
var jetpackFilteredTime;
var nativeTime;

stop = startTimer();
Example #14
0
'use strict';

var rootHandler = require('./rootHandler'),
    server = require('../server'),
    config = require('config'),
    googleapis = require('googleapis'),
    log = require('loglevel'),
    Q = require('q');

var youtube = googleapis.youtube({version: 'v3', auth: config.youtube.apiKey}),
    getVideoData = Q.denodeify(youtube.videos.list);

function getReformattedVideoData(videoData) {
  return {
    id: videoData.id,
    duration: videoData.contentDetails.duration,
    title: videoData.snippet.title,
    thumbnails: videoData.snippet.thumbnails
  };
}

function createMessage(response) {
    var defer = Q.defer();
    var videoData = response[0].items[0];
    var video = getReformattedVideoData(videoData);

    var message = JSON.stringify({
        type: 'video',
        body: {video: video}
    });
var fs = require('fs'),
    path = require('path'),
    Q = require('q'),
    xml2js = require('xml2js');

var parser = new xml2js.Parser();

var fs_readfile = Q.denodeify( fs.readFile );
var parseString = Q.denodeify( parser.parseString );

var xmlPath = path.join(__dirname, 'src', 'livetpls.xml');

//---

function processXml( xmlPath, tplGroupName, lang ) {
  return fs_readfile( xmlPath )
    .then(function fileContent( content ) {
      return parseString( content );
    })
    .then(function processXML( xml ) {
      return processLivetpls( xml, tplGroupName, lang );
    });
}

//---

function processLivetpls( xml, tplGroupName, lang ) {

  var output = '';

  var templateSet = xml.templateSet;
Example #16
0
 .then(function () {
   var play = Q.denodeify(ari.channels.play.bind(ari));
   return play({channelId: chanId, media: soundToPlay,
                playbackId: playback.id});
 })
Example #17
0
exports.templateGenerator = function(params, curr) {

    var handlebars = require('handlebars'),
        layouts = require('handlebars-layouts'),
        fs = require('fs'),
        nodePath = require('path'),
        Q = require('q'),
        urlReq = params.req.params.params,
        urlparams = params.req.params.params.match(/[^\/]+/g),
        templateItems = {},
        repeater = false,
        category = false,
        header='',
        footer='',
        sidebar='',
        repeaterTemplate = '';


    //HANDLE REPEATER
    if (curr && curr.hasOwnProperty("repeaters")) {
      repeater = true;
    }
    //PROMISSES
    var fs_stat = Q.denodeify(fs.stat);

    // Register helpers
    handlebars.registerHelper(layouts(handlebars));

    // Register partials
    var templatepath,
        isCat=false,
        render = false;

    if (urlparams[0] && urlparams[0] == 'admin' && (!urlparams[1] || curr[0] == 'loggedout')) {
        handlebars.registerPartial('layout', fs.readFileSync(nodePath.resolve(__dirname, '../../')+'/views/admin/layout.hbs', 'utf8'));
        templatepath = nodePath.resolve(__dirname, '../../')+'/views/admin/index.html';
    } else if (urlparams[0] && urlparams[0] == 'admin') {
        handlebars.registerPartial('layout', fs.readFileSync(nodePath.resolve(__dirname, '../../')+'/views/admin/layout.hbs', 'utf8'));
        templatepath = nodePath.resolve(__dirname, '../../')+'/views/'+urlReq+'.html';
    }else if(curr=='404'){
      // Render partials
      header = fs.readFileSync(nodePath.resolve(__dirname, '../../../')+'/template/src/header.html', 'utf8');
      footer = fs.readFileSync(nodePath.resolve(__dirname, '../../../')+'/template/src/footer.html', 'utf8');
      sidebar = fs.readFileSync(nodePath.resolve(__dirname, '../../../')+'/template/src/sidebar.html', 'utf8');
      handlebars.registerPartial('layout', fs.readFileSync(nodePath.resolve(__dirname, '../../../')+'/template/src/layout.hbs', 'utf8'));
      if (urlparams[0] && urlparams[0] == 'admin') {
        templatepath = nodePath.resolve(__dirname, '../../')+'/views/admin/404.html';
      } else {
        templatepath = nodePath.resolve(__dirname, '../../../')+'/template/src/404.html';
      }
      render = true;
    }else if(urlReq!=='favicon.ico'){
      if(urlReq=='categories'){ isCat=curr['contentType']; urlReq = curr['contentType']+'_summ'; }
      // Render partials
      header = fs.readFileSync(nodePath.resolve(__dirname, '../../../')+'/template/src/header.html', 'utf8');
      footer = fs.readFileSync(nodePath.resolve(__dirname, '../../../')+'/template/src/footer.html', 'utf8');
      sidebar = fs.readFileSync(nodePath.resolve(__dirname, '../../../')+'/template/src/sidebar.html', 'utf8');
      handlebars.registerPartial('layout', fs.readFileSync(nodePath.resolve(__dirname, '../../../')+'/template/src/layout.hbs', 'utf8'));
      templatepath = nodePath.resolve(__dirname, '../../../')+'/template/src/'+urlReq+'.html';
      render = true;
    }


    fs_stat(templatepath).then(
    function(stats) {
        templateOutput(templatepath, render);
    }, function(err) {
      if (params.req.info.referrer.match(/\/admin/g)) {
          params.rep(false);
      } else {
        templateOutput(templatepath, render);
      }
    });

    let addRepeaters = (path) => {
      let output=fs.readFileSync(path, 'utf8'),
          getSum=(typeof params.req.params.lastCat!=='undefined')?'':'_summ';
      if(/###(.*)###/.test(output)){
        let toGet = output.match(/###(.*)###/gmi)
        for(var elem in toGet){
          let thisval = toGet[elem].match(/###(.*)###/)[1];
          let pathTemplate = nodePath.resolve(__dirname, '../../../')+'/template/src/'+thisval+getSum+'.html';
          let elementTemplate=fs.readFileSync(pathTemplate, 'utf8');
          output=output.replace(toGet[elem], elementTemplate)
        }
        return output;
      }
        return output;
    }
    // Compile template
    let templateOutput = (path, render) => {
        // Render template
        let output,
            fileContent = addRepeaters(path),
            initloop=(isCat)?'{{#each '+ isCat +'}}':'',
            endloop=(isCat)?'{{/each}}':'',
            htmlContent = (render)?'{{#extend "layout"}}'+header+'{{#content "content"}}' +initloop + fileContent + endloop+'{{/content}}'+sidebar+footer+'{{/extend}}':fileContent,
            template = handlebars.compile(htmlContent);

          for(var key in curr) {
            switch (true) {
              case (key == 'groups'):
                templateItems[key] = {};
                for (var item in curr[key]) {
                  templateItems[key][curr[key][item].group] = curr[key][item].name;
                }

              break;

              case (key == 'ctype'):

                if(typeof curr[key] !== 'string'){
                curr[key].forEach(function (el, i, arr){

                  if (typeof templateItems[el.type] === 'undefined') {
                    templateItems[el.type] = new Array();
                  }

                  templateItems[el.type].push(el.content[0]);

                  var menukey = urlparams[1];
                  if (typeof templateItems.menus[urlparams[1]] === 'undefined') {
                    menukey = 'dashboard';
                  }

                  templateItems['areatitle'] = (urlparams[0]!='index') ? templateItems.menus[0].name : 'Dashboard';
                });}

              break;

              case (/repeaters/.test(key)):

                  let thisRep = curr['type']+'_'+(key.split('_')[1] || '');
                  if(typeof templateItems[thisRep] === 'undefined')templateItems[thisRep]=[];
                  templateItems[thisRep] = curr[key];
                  templateItems[thisRep].forEach(function(el, i) {
                    let keys = Object.keys(templateItems[thisRep][i]['repeatfront']);
                    templateItems[thisRep][i][keys] = templateItems[thisRep][i]['repeatfront'][keys];
                  })

              break;

              case (key == 'repeatfront'):

                for (var innerkey in curr[key]) {
                  curr[key][innerkey].forEach(function(el, i) {
                    var oddevenclass;
                    (i % 2) ? oddevenclass = true : oddevenclass = false;
                    el.oddeven = oddevenclass;
                  });

                  templateItems[innerkey] = curr[key][innerkey];
                }
              break;

              default:
              if (key.match(/file_/g)) {
                if (key.match(/unique_file_/g)) {
                  templateItems[key] = curr[key];
                } else {
                  templateItems[key] = curr[key].path;
                }
              } else {
                templateItems[key] = curr[key];
              }

              break;
            }
          }
          output = template(templateItems);
        if (render) {
          params.rep(output);
        } else {
            params.rep({
              status: 'ok',
              message: '',
              data: output
            });
        }
    }
}
Example #18
0
#!/usr/bin/env node
/*jshint node: true */
var express = require('express'),
    path = require('path'),
    extractAssets = require('./extractAssets'),

    fs = require('fs'),
    fsextra = require('fs-extra'),
    q = require('q'),
    readFile = q.denodeify(fs.readFile),
    writeFile = q.denodeify(fs.writeFile),
    mkdirs = q.denodeify(fsextra.mkdirs),
    copy = q.denodeify(fsextra.copy),
    createFile = q.denodeify(fsextra.createFile),

    manifestTemplate = fs.readFileSync(path.join(__dirname, 'template.webapp')),

    seedName = new Date().getTime(),
    counter = 1;

// Turn on q's long stack trace for dev, but turn off before shipping:
// https://github.com/kriskowal/q#long-stack-traces
q.longStackSupport = true;

var app = express();

app.use(express.bodyParser({ keepExtensions: true }));

// Maybe you do not want this for the final builder. Would allow any random
// posts.
app.use(function(req, res, next) {
Example #19
0
var fs = require('fs');
var Q = require('q');
var semver = require('semver');


var read = Q.denodeify(fs.readFile);
var write = Q.denodeify(fs.writeFile);

var findLine = function (data) {
  if (data) {
    var linebyline = data.split('\n');
    var preciseString = find(linebyline, 'Unreleased')[0];
    var lineNr = linebyline.indexOf(preciseString); 
    return {
      lineNr: lineNr, 
      data: linebyline
    };
  };
};

var match = function (searchString) {
  return function (toBeSearched) {
    return toBeSearched.match(searchString);
  };
};


var find = function (data, string) {
  return data.filter(match(string));
};
/*
 * tools
 */

var q = require('q')
,_ = require('lodash')
,fs = require('fs')
,request = require('request')
,setting = wnc.setting
,request = require('request')
,qexe = q.denodeify(require('child_process').exec)

exports.qr = function(args) {

	var uri = args.uri || args.url
	,def = q.defer()

	request(args, function(err, response, body) {
		if(err) def.reject(err)
		else def.resolve({
			response: response
			,body: body
		})
	})

	return def.promise
}

//cmds
exports.cmds = function(req, res) { 
	var
Example #21
0
'use strict';

var commander = require('commander');
var fs = require('fs-extra');
var q = require('q');
var path = require('path');

var commandsPath = path.resolve(__dirname + '/commands');

var readdir = q.denodeify(fs.readdir);
readdir(commandsPath).then(function(files) {
  files.forEach(function(filename) {
    var file = commandsPath + '/' + filename;
    if (fs.statSync(file).isFile()) {
      var commandName = filename.slice(filename.lastIndexOf('/') + 1, filename.lastIndexOf('.'));
      var c = require('./commands/' + commandName);
      if (c.getCommandParameters && typeof c.getCommandParameters === 'function') {
        commandName = commandName + ' ' + c.getCommandParameters();
      }
      var command = commander.command(commandName);
      c.createCommand(command);
    }
  });
  commander.parse(process.argv);
});

"use strict";

var fs = require("fs");
var path = require("path");
var mkdirp = require("mkdirp");
var gm = require("gm");
var manipulationMethods = require("./manipulation-methods");
var Queue = require("./process-queue");
var mime = require("mime");
var Q = require("q");
var fsStat = Q.denodeify(fs.stat);

var fsExists = function (file) {
    var defer = Q.defer();
    fs.exists(file, function (exists) {
        if (exists) {
            defer.resolve();
        } else {
            defer.reject(new Error('ENOFILE'));
        }
    });

    return defer.promise;
};

var planTasks = function (preset) {
    var tasks = preset.tasks;

    var getSourceFile = function (req) {
        var targetPath = preset.target;
        return path.join(preset.basePath, req.path.replace(targetPath, preset.from));
    var walker = inspector.createTreeWalkerSync(from);
    while (walker.hasNext()) {
        var inspectData = walker.getNext();
        var destPath = pathUtil.join(to, inspectData.relativePath);
        if (options.allowedToCopy(inspectData.absolutePath)) {
            copySync(inspectData, destPath);
        }
    }
};

//---------------------------------------------------------
// Async
//---------------------------------------------------------

var promisedReadFile = Q.denodeify(fs.readFile);
var promisedSymlink = Q.denodeify(fs.symlink);
var promisedReadlink = Q.denodeify(fs.readlink);
var promisedMkdirp = Q.denodeify(mkdirp);

var copyAsync = function (inspectData, to) {
    var mod = mode.normalizeFileMode(inspectData.mode);
    if (inspectData.type === 'dir') {
        return promisedMkdirp(to, { mode: mod });
    } else if (inspectData.type === 'file') {
        return promisedReadFile(inspectData.absolutePath)
        .then(function (data) {
            return fileOps.writeAsync(to, data, { mode: mod });
        });
    } else if (inspectData.type === 'symlink') {
        return promisedReadlink(inspectData.absolutePath)
Example #24
0
var debug = require('debug')('shuttle-in');
var q = require('q');

var request = require('request').defaults({
    jar: true,
    json: true,
    followRedirect: false
});
var requestQ = q.denodeify(request);


var baseUrl = 'http://shuttle-in.com';
var loginUrl = baseUrl + '/Account';

function login(loginUrl) {
    return requestQ(loginUrl)
        .then(function() {
            var response = arguments[0][0];
            return requestQ({
                method: 'POST',
                url: loginUrl,
                form: {
                    PortalID: 45,
                    Password: '******'
                }
            });
        });
}

function shuttleInApi(path) {
    var url = baseUrl + path;
Example #25
0
// libraries for processing folders
/* jshint esnext:true, globalstrict:true */
/* global require, __dirname, exports, module, console, escape */
"use strict";

var Q = require('q');
var fs = require('fs');
var path = require('path');
var fs_stat = Q.denodeify(fs.stat);
var fs_readdir = Q.denodeify(fs.readdir);
var fs_readFile = Q.denodeify(fs.readFile);
var fs_writeFile = Q.denodeify(fs.writeFile);
var fs_unlink = Q.denodeify(fs.unlink);

var chokidar = require('chokidar');
var marked = require('marked');
marked.setOptions({ gfm:true,	breaks: true });

var escape_markdown = require('./markdown-escape');
var mmm = require('mmmagic');
var magic = new mmm.Magic(mmm.MAGIC_MIME_TYPE);

function get_mimetype(dir) {
	var deferred = Q.defer();
	magic.detectFile(dir, deferred.makeNodeResolver());
	return deferred.promise;
}

function markdown_to_html (str,options) {
	var deferred = Q.defer();
	marked(str,options, deferred.makeNodeResolver());
Example #26
0
 return Q.fcall(function () {
     var entryFolder = persistenceFormat.getEntryFullPath(entryId);
     var getManifestFiles = Q.denodeify(glob);
     return getManifestFiles("**/*.m3u8", {cwd: entryFolder, realpath: true});
 }).then(function (flavorManifestPaths) {
Example #27
0
var fs = require('fs');
var gm = require('gm');
var multer  = require('multer');
var imgProc = require('./lib/image_processing');
var classifier = require('./lib/classifier');




// var imagePath = '/documents/gruid-test-guide.png';
var imagePath = 'public/documents/out.png';
var tmpPath = 'public/tmp/';

var express = require('express'),
  app = express(),
  fs_readFile = q.denodeify(fs.readFile),
  fs_writeFile = q.denodeify(fs.writeFile);

// "name=test_drawing" -F "drawing_pdf=@package_bde_elan.pdf"  >


app.use(bodyParser());
app.use(multer({ dest: './public/uploads'}))
app.use(express.static(__dirname + '/public'));

app.post('/ocrdata', function(req, res){
  var imageData = req.body.image_data,
    base64Data = imageData.replace(/^data:image\/png;base64,/,""),
    binaryData = new Buffer(base64Data, 'base64').toString('binary'),
    imagePath = "out.png";
Example #28
0
#!/usr/bin/env node

require('colors');
var browserify = require('browserify');
var EventEmitter = require('events').EventEmitter;
var fs = require('fs');
var httpServer = require('http-server');
var nodeunit = require('nodeunit');
var optimist = require('./runner-options');
var Q = require('q');
var querystring = require('querystring');
var runnerDisplay = require('./browser-display');
var portfinder = Q.denodeify(require('portfinder').getPort);
var installSelenium = Q.denodeify(require('selenium-standalone').install);
var startSeleniumCb = require('selenium-standalone').start;
var xtend = require('xtend/mutable');
var wd = require('wd');

var browser;

optimist.
  usage('Run the jsdom test suite in a browser via WebDriver').
  describe('http-port', 'port to run test server on').
  describe('web-driver-port', 'port to run Selenium on').
  describe('verbose-web-driver', 'print verbose output from wd to stdout').
  describe('verbose-browser-console', 'print browser console to stdout');

var argv = optimist.argv;

if (argv.help) {
  optimist.showHelp();
Example #29
0
var path = require('path'),
    fs = require('fs'),
    Q = require('q');

var readFile = Q.denodeify(fs.readFile);

function copy(object) {
    return Object.keys(object)
        .reduce(function(result, prop) {
            result[prop] = object[prop];

            return result;
        }, {});
}

function Responder(method, url, dynamicFn) {
    this.method = method;
    this.url = url;

    this.dynamicFn = dynamicFn || function() {};
    this.response = null;
    this.headers = {};
}
Responder.prototype = {
    proxy: function(_src) {
        var src = path.resolve(process.cwd(), _src);

        return this.respond(200, readFile(src));
    },
    respond: function(code, data) {
        this.response = {
Example #30
0
function PostgresDB(dbConfig) {

  var connect = Q.denodeify(pg.connect.bind(pg));

  /**
   * Retrieves the bridge profile.
   *
   * @return {Q} result - a promise containing the row where the bridge
   *   settings are stored
   */
  this.getBridgeProfile = function() {

    return connect(dbConfig.dbConnection)
      .then(function (values) {
        var profile = dbConfig.bridgeProfile;
        var client = values[0];
        var done = values[1];
        var query = Q.denodeify(client.query.bind(client));

        return query('SELECT exists(SELECT 1 FROM bridge_profile WHERE '
                   + 'bridge_type = $1)', [profile])
          .then(function (result) {
            if (!result.rows[0].exists) {
              profile = 'default';
            }
            return query('SELECT * FROM bridge_profile WHERE bridge_type = $1',
                         [profile]);
          })
          .then(function (result) {
            console.log('Fetched bridge profile', profile);
            return result.rows[0];
          })
          .catch(function (err) {
            console.error(err);
          })
          .finally(function () {
            done();
          });
    })
    .catch(function (err) {
      console.error(err);
    });

  };

  /**
   * Retrieves a user profile.
   *
   * @param {String} userType - the type of user to retrieve
   * @return {Q} result - a promise containing the row where the user
   *   profile is stored
   */
  this.getUserProfile = function(userType) {

    return connect(dbConfig.dbConnection)
      .then(function (values) {
        var client = values[0];
        var done = values[1];
        var query = Q.denodeify(client.query.bind(client));

        return query('SELECT exists(SELECT 1 FROM user_profile WHERE '
                   + 'user_type = $1)', [userType])
          .then(function (result) {
            if (!result.rows[0].exists) {
              userType = 'default';
            }
            return query('SELECT * FROM user_profile WHERE user_type = '
                       + '$1', [userType]);
          })
          .then(function (result) {
            return result.rows[0];
          })
          .catch(function (err) {
            console.error(err);
          })
          .finally(function () {
            done();
          });
      })
      .catch(function (err) {
        console.error(err);
      });

  };

  /**
   * Retrieves a group profile.
   *
   * @param {String} groupType - the type of group to retrieve
   * @return {Q} result - a promise containing the row where the group
   *   profile is stored
   */
  this.getGroupProfile = function(groupType) {

    return connect(dbConfig.dbConnection)
      .then(function (values) {
        var client = values[0];
        var done = values[1];
        var query = Q.denodeify(client.query.bind(client));

        return query('SELECT exists(SELECT 1 FROM group_profile WHERE '
                   + 'group_type = $1)', [groupType])
          .then(function (result) {
            if (!result.rows[0].exists) {
              groupType = 'default';
            }
            return query('SELECT * FROM group_profile WHERE group_type = '
                       + '$1', [groupType]);
          })
          .then(function (result) {
            return result.rows[0];
          })
          .catch(function (err) {
            console.error(err);
          })
          .finally(function () {
            done();
          });
      })
      .catch(function (err) {
        console.error(err);
      });

  };

}