Ejemplo n.º 1
0
    // callback which is invoked each time a message matches the configured route.
    function handleMessage(msg) {

      var svcsMsg = xtend(self.baseMsg, msg);

      svcsMsg.parseRoutingKey();

      svcsMsg.channel = ch;
      svcsMsg.ack = ackMessage;

      // Ack method for the msg
      function ackMessage() {
        ch.ack(msg);
      }

      var middleware = Array.isArray(self.options.middleware) ?
        self.container.middleware.concat(self.options.middleware) : self.container.middleware;

      // run all the middleware passing the message through each with the result being updateMsg
      pipeline(middleware, svcsMsg).then(function processMiddleware(updateMsg) {
        // cater for pipeline returning an array if the array of functions passed was empty!?
        if (Array.isArray(updateMsg)) {
          self.options.handler(updateMsg[0]);
        }
        else {
          self.options.handler(updateMsg);
        }
        debug('queue', self.options.queue);
        if (self.options.autoAck) {
          debug('autoAck', 'true');
          ackMessage();
        }
      }, self.options.errorHandler);
    }
Ejemplo n.º 2
0
	before( function( done ) {
		var actions = [
			function() {
				return rabbit.closeAll( true );
			},
			function() {
				return rabbit.getChannel( 'one' );
			},
			function() {
				return rabbit.addExchange( 'ex.1', 'fanout', 
				{
					autoDelete: true
				} );
			},
			function() {
				return rabbit.addQueue( 'q.1', 
				{
					autoDelete: true,
					subscribe: true
				} );
			},
			function() {
				return rabbit.bindQueue( 'ex.1', 'q.1', '' );
			}
		];

		pipeline( actions )
			.done( function() { 
				done(); 
			} );
	} );
Ejemplo n.º 3
0
	scanAndListAPs: function() {
		return pipeline([
			WifiUtilities.scan,
			WifiUtilities.cleanApList,
			WifiUtilities.displayAPList
		]);
	},
Ejemplo n.º 4
0
	_sendFile: function(buffer) {
		var self = this;
		this.seq = 0;
		return pipeline([
			function() {
				log.verbose('send file header');
				return self._sendFileHeader('binary', buffer.length);
			},
			function(fileResponse) {
				if (fileResponse !== ymodem.ACK) {
					return when.reject('file header not acknowledged');
				}

				// keep sending packets until we are done
				return poll(function() {
					var start = (self.seq - 1) * self.options.packetLength;
					var buf = buffer.slice(start, start + self.options.packetLength);
					return self._sendPacket(buf);
				}, 1, function() {
					return ((self.seq - 1) * self.options.packetLength) >= buffer.length;
				});
			},
			function() {
				var buf = new Buffer([ymodem.EOT]);
				log.verbose('write', self.seq, buf, buf.length);
				return self._sendRawPacket(buf);
			}
		]);
	},
Ejemplo n.º 5
0
ImportanceEditor.prototype.updateImportance = function (params) {
  return pipeline([
    _.bind(function () {
      if (params.name) {
        return db.runQueryInTransaction(
          this.tx, "update_importance_name", [params.id, params.name]
        );
      }
    }, this),
    _.bind(function () {
      if (params.description) {
        return db.runQueryInTransaction(
          this.tx, "update_importance_description", [params.id, params.description]
        );
      }
    }, this),
    _.bind(function () {
      if (params.value !== undefined) {
        return db.runQueryInTransaction(
          this.tx, "update_importance_value", [params.id, params.value]
        );
      }
    }, this),
    _.bind(function () {
      if (params.defaultImportanceId) {
        return db.runQueryInTransaction(
          this.tx, "update_default_importance_id",
          [params.id, params.defaultImportanceId]
        );
      }
    }, this)
  ]);
};
Ejemplo n.º 6
0
	createAccessToken: function (clientName) {

		if (!clientName) {
			clientName = "user";
		}

		var allDone = pipeline([
			this.getCredentials,
			function (creds) {
				var api = new ApiClient(settings.apiUrl);
				return api.createAccessToken(clientName, creds.username, creds.password);
			}
		]);

		allDone.done(
			function (result) {
				var now_unix = Date.now();
				var expires_unix = now_unix + (result.expires_in * 1000);
				var expires_date = new Date(expires_unix);
				console.log('New access token expires on ' + expires_date);
				console.log('    ' + result.access_token);
				process.exit(0);
			},
			function (err) {
				// console.log("there was an error creating a new access token: " + err);
				process.exit(1);
			}
		);
		return;
	},
Ejemplo n.º 7
0
		return getContents(loc).then(function (contents) {
			debug_log('got contents of ' + loc );
			debug_log(contents);
			return pipeline([
				function () {
					debug_log('Deleting ...');
					return deleteResource(loc).then(function () {
						debug_log('Deleting OK');
					});
				},
				function () {
					debug_log('Mkdir '+loc+' ...');
					return mkdir(loc).then(function () {
						debug_log('Mkdir OK');
					});
				},
				function () {
					var putLoc = pathResolve(loc, MAIN_SCRIPTED_RC_FILE);
					debug_log('putting contents to '+putLoc+' ...');
					return putContents(putLoc, contents).then(function () {
						debug_log('putting OK');
					});
				}
			]);
		});
Ejemplo n.º 8
0
 getLookups: function (lookups) {
   var calls = _.map(this.keys, function (key) {
     return _.bind(this.lookup, this,
       lookups[key + "Id"], "lookup_" + key + "_list");
   }, this);
   return pipeline(calls);
 },
Ejemplo n.º 9
0
	_compileAndDownload: function(api, files, platform_id, filename, targetVersion) {
		return pipeline([
			//compile
			function () {
				return api.compileCode(files, platform_id, targetVersion);
			},

			//download
			function (resp) {
				if (resp && resp.binary_url) {
					return api.downloadBinary(resp.binary_url, filename).then(function() {
						return resp.sizeInfo;
					});
				} else {
					return when.reject(resp.errors);
				}
			}
		]).then(
			function (sizeInfo) {
				if (sizeInfo) {
					console.log('Memory use: ');
					console.log(sizeInfo);
				}
				console.log('Compile succeeded.');
				console.log('Saved firmware to:', path.resolve(filename));
			});
	},
Ejemplo n.º 10
0
		], function(answers) {
			pipeline([
				function() {
					if (answers.wipe) {
						return api.removeAccessToken(settings.username, answers.password, settings.access_token);
					} else {
						console.log(arrow, 'Leaving your token intact.');
					}
				},
				function() {
					console.log(
						arrow,
						util.format('You have been logged out from %s.',
						chalk.bold.cyan(settings.username))
					);
					settings.override(null, 'username', null);
					settings.override(null, 'access_token', null);
				}
			]).then(function() {
				allDone.resolve();
			}, function(err) {
				console.error('There was an error revoking the token', err);
				allDone.reject(err);
			});
		});
Ejemplo n.º 11
0
	before( function( done ) {
		var actions = [
			function() {
				return rabbit.closeAll( true );
			},
			function() {
				return rabbit.addExchange( 'topic.ex.1', 'topic', 
				{
					autoDelete: true,
					persistent: true
				} );
			},
			function() {
				return rabbit.addQueue( 'topic.q.1', 
				{
					autoDelete: true,
					subscribe: true
				} );
			},
			function() {
				return rabbit.bindQueue( 'topic.ex.1', 'topic.q.1', 'this.is.*.*' );
			}
		];

		pipeline( actions )
			.done( function() { 
				done(); 
			} );
	} );
Ejemplo n.º 12
0
db.prototype.runQuery = function (query, queryParameters, templateParameters) {
  return pipeline(
    [
      _.bind(this._getConnection, this),
      _.bind(this._runQuery, this, query, queryParameters, templateParameters)
    ]
  );
};
Ejemplo n.º 13
0
module.exports = function _export(options) {
  var url = options.url
  options.pagerank = options.pagerank || false
  return pipeline([
    getPageRank.bind(null, url, options.pagerank),
    sendToAnalyze.bind(null, url, options.body)
  ])
}
Ejemplo n.º 14
0
	nyanMode: function(deviceid, onOff) {
		var api = new ApiClient();
		if (!api.ready()) {
			return when.reject('not logged in!');
		}

		if (!onOff || (onOff === '') || (onOff === 'on')) {
			onOff = true;
		} else if (onOff === 'off') {
			onOff = false;
		}

		if ((deviceid === '') || (deviceid === 'all')) {
			deviceid = null;
		} else if (deviceid === 'on') {
			deviceid = null;
			onOff = true;
		} else if (deviceid === 'off') {
			deviceid = null;
			onOff = false;
		}


		if (deviceid) {
			return api.signalDevice(deviceid, onOff).catch(function (err) {
				console.error('Error', err);
				return when.reject(err);
			});
		} else {

			var toggleAll = function (devices) {
				if (!devices || (devices.length === 0)) {
					console.log('No devices found.');
					return when.resolve();
				} else {
					var promises = [];
					devices.forEach(function (device) {
						if (!device.connected) {
							promises.push(when.resolve(device));
							return;
						}
						promises.push(api.signalDevice(device.id, onOff));
					});
					return when.all(promises);
				}
			};


			return pipeline([
				api.listDevices.bind(api),
				toggleAll
			]).catch(function(err) {
				console.error('Error', err);
				return when.reject(err);
			});
		}
	},
Ejemplo n.º 15
0
db.prototype.startTransaction = function () {
  winston.verbose("creating transaction");
  return pipeline(
    [
      _.bind(this._getConnection, this),
      _.bind(this._startTransaction, this)
    ]
  );
};
Ejemplo n.º 16
0
	login: function (username, password) {
		var self = this;

		if (this.tries >= (password ? 1 : 3)) {
			console.log();
			console.log(alert, "It seems we're having trouble with logging in.");
			console.log(
				alert,
				util.format('Please try the `%s help` command for more information.',
					chalk.bold.cyan(cmd))
			);
			return when.reject();
		}

		var allDone = pipeline([
			//prompt for creds
			function () {
				if (password) {
					return {username: username, password: password};
				}
				return prompts.getCredentials(username, password);
			},

			//login to the server
			function (creds) {

				var api = new ApiClient();
				username = creds.username;
				self.newSpin('Sending login details...').start();
				return api.login(settings.clientId, creds.username, creds.password);
			},

			function (accessToken) {

				self.stopSpin();
				console.log(arrow, 'Successfully completed login!');
				settings.override(null, 'access_token', accessToken);
				if (username) {
					settings.override(null, 'username', username);
				}
				self.tries = 0;
				return when.resolve(accessToken);
			}
		]);

		return allDone.catch(function (err) {

			self.stopSpin();
			console.log(alert, "There was an error logging you in! Let's try again.");
			console.error(alert, err);
			self.tries = (self.tries || 0) + 1;

			return self.login(username);
		});
	},
Ejemplo n.º 17
0
 function (sessionClientInitializer) {
     return when_pipeline([
         function () {
             return sessionClientInitializer.on("pong", function (e) {
                 console.log("GOT PONG", e)
             }) },
         function () {
             return sessionClientInitializer.initialize();
         }
     ]);
 }
Ejemplo n.º 18
0
Spark.prototype.getAttributesForAll = function () {
  if (this._attributeCache) {
    return when.resolve(this._attributeCache);
  }

  // TODO: Probably bind to this in pipeline execution
  return pipeline([
    this.listDevices.bind(this),
    this.lookupAttributesForAll.bind(this)
  ]);
};
Ejemplo n.º 19
0
	_promptForOta: function(api, attrs, fileMapping, targetVersion) {
		var self = this;
		var newFileMapping = {
			basePath: fileMapping.basePath,
			map: {}
		};
		return pipeline([
			function() {
				var sourceExtensions = ['.h', '.cpp', '.ino', '.c'];
				var list = Object.keys(fileMapping.map);
				var isSourcey = _.some(list, function(file) {
					return sourceExtensions.indexOf(path.extname(file)) >= 0;
				});
				if (!isSourcey) {
					var binFile = fileMapping.map[list[0]];
					newFileMapping.map[list[0]] = binFile;
					return binFile;
				}

				var filename = temp.path({ suffix: '.bin' });
				return self._compileAndDownload(api, fileMapping, attrs.platform_id, filename, targetVersion).then(function() {
					newFileMapping.map['firmware.bin'] = filename;
					return filename;
				});
			},
			function(file) {
				return whenNode.lift(fs.stat)(file);
			},
			function(stats) {
				var dataUsage = utilities.cellularOtaUsage(stats.size);

				return when.promise(function(resolve, reject) {
					console.log();
					console.log(alert, 'Flashing firmware Over The Air (OTA) uses cellular data, which may cause you to incur usage charges.');
					console.log(alert, 'This flash is estimated to use at least ' + chalk.bold(dataUsage + ' MB') + ', but may use more depending on network conditions.');
					console.log();
					console.log(alert, 'Please type ' + chalk.bold(dataUsage) + ' below to confirm you wish to proceed with the OTA flash.');
					console.log(alert, 'Any other input will cancel.');

					inquirer.prompt([{
						name: 'confirmota',
						type: 'input',
						message: 'Confirm the amount of data usage in MB:'
					}], function(ans) {
						if (ans.confirmota !== dataUsage) {
							return reject('User cancelled');
						}
						resolve(newFileMapping);
					});
				});
			}
		]);
	},
Ejemplo n.º 20
0
	_flashKnownApp: function(api, deviceid, filePath) {
		var self = this;
		if (!settings.knownApps[filePath]) {
			console.error("I couldn't find that file: " + filePath);
			return when.reject();
		}

		return pipeline([
			function getAttrs() {
				return api.getAttributes(deviceid);
			},
			function getFile(attrs) {
				var spec = _.find(specs, { productId: attrs.product_id });
				if (spec) {
					if (spec.knownApps[filePath]) {
						return { list: [spec.knownApps[filePath]] };
					}

					if (spec.productName) {
						console.log("I don't have a %s binary for %s.", filePath, spec.productName);
						return when.reject();
					}
				}

				return when.promise(function (resolve, reject) {
					inquirer.prompt([{
						name: 'type',
						type: 'list',
						message: 'Which type of device?',
						choices: [
							'Photon',
							'Core',
							'P1',
							'Electron'
						]
					}], function(ans) {
						var spec = _.find(specs, { productName: ans.type });
						var binary = spec && spec.knownApps[filePath];

						if (!binary) {
							console.log("I don't have a %s binary for %s.", filePath, ans.type);
							return reject();
						}

						resolve({ list: [binary] });
					});
				});
			},
			function doTheFlash(file) {
				return self._doFlash(api, deviceid, file);
			}
		]);
	},
Ejemplo n.º 21
0
	_sendPublicKeyToServer: function(deviceid, filename, algorithm) {
		var self = this;
		if (!fs.existsSync(filename)) {
			filename = utilities.filenameNoExt(filename) + '.pub.pem';
			if (!fs.existsSync(filename)) {
				console.error("Couldn't find " + filename);
				return when.reject("Couldn't find " + filename);
			}
		}

		deviceid = deviceid.toLowerCase();

		var api = new ApiClient();
		if (!api.ready()) {
			return when.reject('Not logged in');
		}

		var pubKey = temp.path({ suffix: '.pub.pem' });
		var inform = path.extname(filename).toLowerCase() === '.der' ? 'DER' : 'PEM';

		return pipeline([
			function() {
				// try both private and public versions and both algorithms
				return utilities.deferredChildProcess('openssl ' + algorithm + ' -inform ' + inform + ' -in ' + filename + ' -pubout -outform PEM -out ' + pubKey)
					.catch(function(err) {
						return utilities.deferredChildProcess('openssl ' + algorithm + ' -pubin -inform ' + inform + ' -in ' + filename + ' -pubout -outform PEM -out ' + pubKey);
					})
					.catch(function(err) {
						// try other algorithm next
						algorithm = algorithm === 'rsa' ? 'ec' : 'rsa';
						return utilities.deferredChildProcess('openssl ' + algorithm + ' -inform ' + inform + ' -in ' + filename + ' -pubout -outform PEM -out ' + pubKey);
					})
					.catch(function(err) {
						return utilities.deferredChildProcess('openssl ' + algorithm + ' -pubin -inform ' + inform + ' -in ' + filename + ' -pubout -outform PEM -out ' + pubKey);
					});
			},
			function() {
				return whenNode.lift(fs.readFile)(pubKey);
			},
			function(keyBuf) {
				var apiAlg = algorithm === 'rsa' ? 'rsa' : 'ecc';
				return api.sendPublicKey(deviceid, keyBuf, apiAlg, self.options.productId);
			}
		]).catch(function(err) {
			console.log('Error sending public key to server: ' + err);
			return when.reject();
		}).finally(function() {
			fs.unlink(pubKey, function() {
				// do nothing
			});
		});
	},
Ejemplo n.º 22
0
		serialPort.open(function () {
			var configDone = pipeline([
				function () {
					return that.serialPromptDfd(serialPort, null, 'w', 5000, true);
				},
				function (result) {
					if (!result) {
						return that.serialPromptDfd(serialPort, null, 'w', 5000, true);
					}
					else {
						return when.resolve();
					}
				},
				function () {
					return that.serialPromptDfd(serialPort, 'SSID:', ssid + '\n', 5000, false);
				},
				function () {
					return that.serialPromptDfd(serialPort, 'Security 0=unsecured, 1=WEP, 2=WPA, 3=WPA2:', securityType + '\n', 1500, true);
				},
				function (result) {
					var passPrompt = 'Password:'******'security' line will have received the
						//prompt instead, so lets assume we're good since we already got the ssid prompt, and just pipe
						//the pass.

						if (securityType === '0') {
							//we didn't have a password, so just hit return
							serialPort.write('\n');

						}
						passPrompt = null;
					}

					if (!passPrompt || !password || (password === '')) {
						return when.resolve();
					}

					return that.serialPromptDfd(serialPort, passPrompt, password + '\n', 5000);
				},
				function () {
					if (device.type === 'Photon') {
						return that.serialPromptDfd(serialPort, '\n', null, 15000);
					}
					return that.serialPromptDfd(serialPort, 'Spark <3 you!', null, 15000);
				}
			]);
			utilities.pipeDeferred(configDone, wifiDone);
		});
Ejemplo n.º 23
0
function createGuestUser(resolver, compDef, wire) {
    let database = compDef.options.database;

    let url = `mongodb://localhost:27017/${database}`;

    pipeline([
        connectP,
        createUsersCollectionP,
        createGuestUserP,
        addDefaultRoleToGuestUserP
    ], url).then((res) => {
        resolver.resolve();
    }).catch((err) => {resolver.reject(err)});
}
Ejemplo n.º 24
0
	writeServerPublicKey: function (filename, ipOrDomain, port) {
		var dfu = this.dfu;
		if (filename === '--protocol') {
			filename = null;
			ipOrDomain = null;
		}
		if (filename && !fs.existsSync(filename)) {
			console.log('Please specify a server key in DER format.');
			return -1;
		}
		if (port === '--protocol') {
			port = null;
		}
		if (ipOrDomain === '--protocol') {
			ipOrDomain = null;
			port = null;
		}
		var self = this;
		this.checkArguments(arguments);

		return pipeline([
			dfu.isDfuUtilInstalled,
			dfu.findCompatibleDFU,
			function() {
				return self.validateDeviceProtocol();
			},
			function() {
				return self._getDERPublicKey(filename);
			},
			function(derFile) {
				filename = derFile;
				return self._getIpAddress(ipOrDomain);
			},
			function(ip) {
				return self._formatPublicKey(filename, ip, port);
			},
			function(bufferFile) {
				var segment = self._getServerKeySegmentName();
				return dfu.write(bufferFile, segment, false);
			}
		]).then(
			function () {
				console.log('Okay!  New keys in place, your device will not restart.');
			},
			function (err) {
				console.log('Make sure your device is in DFU mode (blinking yellow), and is connected to your computer');
				console.error('Error - ' + err);
				return when.reject(err);
			});
	},
Ejemplo n.º 25
0
	getAllVariables: function (args) {
		if (this._cachedVariableList) {
			return when.resolve(this._cachedVariableList);
		}

		console.error("polling server to see what cores are online, and what variables are available");

		var tmp = when.defer();
		var that = this;
		var api = new ApiClient(settings.apiUrl, settings.access_token);
		if (!api.ready()) {
			return;
		}

		var lookupVariables = function (cores) {
			if (!cores || (cores.length == 0)) {
				console.log("No cores found.");
				that._cachedVariableList = null;
			}
			else {
				var promises = [];
				for (var i = 0; i < cores.length; i++) {
					var coreid = cores[i].id;
					if (cores[i].connected) {
						promises.push(api.getAttributes(coreid));
					}
					else {
						promises.push(when.resolve(cores[i]));
					}
				}

				when.all(promises).then(function (cores) {
					//sort alphabetically
					cores = cores.sort(function (a, b) {
						return (a.name || "").localeCompare(b.name);
					});

					that._cachedVariableList = cores;
					tmp.resolve(cores);
				});
			}
		};

		pipeline([
			api.listDevices.bind(api),
			lookupVariables
		]);

		return tmp.promise;
	},
Ejemplo n.º 26
0
    getAllAttributes: function () {
        if (this._attributeCache) {
            return when.resolve(this._attributeCache);
        }

        console.log("polling server to see what cores are online, and what functions are available");


        var that = this;


        var lookupAttributes = function (cores) {
            var tmp = when.defer();

            if (!cores || (cores.length == 0)) {
                console.log("No cores found.");
                that._attributeCache = null;
                tmp.reject("No cores found");
            }
            else {
                var promises = [];
                for (var i = 0; i < cores.length; i++) {
                    var coreid = cores[i].id;
                    if (cores[i].connected) {
                        promises.push(that.getAttributes(coreid));
                    }
                    else {
                        promises.push(when.resolve(cores[i]));
                    }
                }

                when.all(promises).then(function (cores) {
                    //sort alphabetically
                    cores = cores.sort(function (a, b) {
                        return (a.name || "").localeCompare(b.name);
                    });

                    that._attributeCache = cores;
                    tmp.resolve(cores);
                });
            }
            return tmp.promise;
        };

        return pipeline([
            that.listDevices.bind(that),
            lookupAttributes
        ]);
    },
Ejemplo n.º 27
0
    "complex cross table": function () {
        var socket;
        var update = {
            objects: [
                {
                    "trellis": "user",
                    "id": 9,
                    "followers": [12]
                },
                {
                    "trellis": "user",
                    "id": 7,
                    "followees": [9]
                }
            ]
        };
        var query = {
            "trellis": "user",
            "expansions": ["followers"],
            "filters": [
                {
                    "path": "id",
                    "value": 9
                }
            ]
        };

        return pipeline([
            function () {
                return lab.login_socket('cj', 'pass');
            },
            function (s) {
                return socket = s;
            },
            function () {
                return lab.emit(socket, 'update', update);
            },
            function () {
                return lab.emit(socket, 'query', query).then(function (response) {
                    var objects = response.objects;
                    console.log('response', response);
                    assert.equals(objects.length, 1);
                    assert.equals(objects[0].followers.length, 2);
                    assert.equals(objects[0].followers[1].name, "hero");
                    assert.equals(objects[0].follower_count, 2);
                });
            }
        ]);
    },
Ejemplo n.º 28
0
	_handleLibraryExample: function (fileMapping) {
		return pipeline([
			function () {
				var list = _.values(fileMapping.map);
				if (list.length == 1) {
					return require('particle-library-manager').isLibraryExample(list[0]);
				}
			},
			function (example) {
				if (example) {
					return example.buildFiles(fileMapping);
				}
			}
		]);
	}
Ejemplo n.º 29
0
	applicationStartUp: function(){
		// Method: applicationStartUp.
		//		Runs through the application start up tasks, before launching application.
		var application = this;
		
		pipeline(application.startuptasks, application).then(function() {
			try{	
				application.startApp(); 
			} catch (ex){
				console.log(ex);
				//Alloy.Globals.Events.trigger("Application.onError", [ex]);
			}
		}, function(ex){
			Alloy.Globals.Events.trigger("Application.onError", [ex]);
		});
	},
Ejemplo n.º 30
0
    "remove": function () {
        var socket;
        var update = {
            objects: [
                {
                    "trellis": "user",
                    "id": 7,
                    "followers": [
                        {
                            "id": 9,
                            "_removed_": true
                        }
                    ]
                }
            ]
        };
        var query = {
            "trellis": "user",
            "expansions": ["followers"],
            "filters": [
                {
                    "path": "id",
                    "value": 7
                }
            ]
        };

        return pipeline([
            function () {
                return lab.login_socket('cj', 'pass');
            },
            function (s) {
                return socket = s;
            },
            function () {
                return lab.emit(socket, 'update', update);
            },
            function () {
                return lab.emit(socket, 'query', query).then(function (response) {
                    var objects = response.objects;
                    console.log('response', response);
                    assert.equals(objects.length, 1);
                    assert.equals(objects[0].followers.length, 0);
                });
            }
        ]);
    },