1
0
Fork 0
mirror of https://github.com/openstf/stf synced 2025-10-04 10:19:30 +02:00

Fix all lib/ files with ESLint rules with 0 errors.

This commit is contained in:
Gunther Brunner 2016-01-19 20:52:38 +09:00
parent 994977ea94
commit 434f63b3a9
69 changed files with 793 additions and 764 deletions

View file

@ -48,7 +48,7 @@
"no-new-wrappers": 2, "no-new-wrappers": 2,
"no-new": 2, "no-new": 2,
"no-octal-escape": 2, "no-octal-escape": 2,
"no-octal": 2, "no-octal": 1, // TODO: accept until we use ES6 0o755 notation
"no-param-reassign": 2, "no-param-reassign": 2,
"no-process-env": 0, // `2` is recommended "no-process-env": 0, // `2` is recommended
"no-proto": 2, "no-proto": 2,
@ -62,7 +62,7 @@
"no-useless-call": 2, // `2` is recommended "no-useless-call": 2, // `2` is recommended
"no-useless-concat": 2, "no-useless-concat": 2,
"no-void": 2, "no-void": 2,
"no-warning-comments": 1, // `[0, { "terms": ["todo", "fixme", "xxx"], "location": "start" }]` is recommended "no-warning-comments": [1, { "terms": ["todo", "fixme", "@todo", "@fixme"]}], // `[0, { "terms": ["todo", "fixme", "xxx"], "location": "start" }]` is recommended
"no-with": 2, "no-with": 2,
"radix": 1, // `2` is recommended "radix": 1, // `2` is recommended
"vars-on-top": 0, // `2` is recommended TODO: review this "vars-on-top": 0, // `2` is recommended TODO: review this
@ -78,7 +78,7 @@
"no-label-var": 2, "no-label-var": 2,
"no-shadow-restricted-names": 2, "no-shadow-restricted-names": 2,
"no-shadow": 0, // TODO: 1 may be ok "no-shadow": 0, // TODO: 1 may be ok
"no-undefined": 2, "no-undefined": 1,
"no-unused-vars": 1, "no-unused-vars": 1,
"no-use-before-define": 1, // TODO: 0 or 2 may be ok, sometimes there are ciclic dependencies "no-use-before-define": 1, // TODO: 0 or 2 may be ok, sometimes there are ciclic dependencies
@ -86,7 +86,7 @@
"array-bracket-spacing": [2, "never"], // optionally set `[2, "never", {"singleValue": true, "objectsInArrays": true, "arraysInArrays": true}]` "array-bracket-spacing": [2, "never"], // optionally set `[2, "never", {"singleValue": true, "objectsInArrays": true, "arraysInArrays": true}]`
"block-spacing": [2, "always"], // optionally set `[2, "always"]` "block-spacing": [2, "always"], // optionally set `[2, "always"]`
"brace-style": [2, "stroustrup", {"allowSingleLine": false}], "brace-style": [2, "stroustrup", {"allowSingleLine": false}],
"camelcase": [2, {"properties": "always"}], // TODO: 2 might be too much "camelcase": [2, {"properties": "never"}], // TODO: 2 might be too much
"comma-spacing": [2, {"before": false, "after": true}], "comma-spacing": [2, {"before": false, "after": true}],
"comma-style": [1, "first"], // optionally set `[2, "first", {"exceptions": {"ArrayExpression": true, "ObjectExpression": true}}]` "comma-style": [1, "first"], // optionally set `[2, "first", {"exceptions": {"ArrayExpression": true, "ObjectExpression": true}}]`
"computed-property-spacing": [2, "never"], "computed-property-spacing": [2, "never"],

View file

@ -903,7 +903,7 @@ program
.description('migrates the database to the latest version') .description('migrates the database to the latest version')
.action(function() { .action(function() {
var log = logger.createLogger('cli:migrate') var log = logger.createLogger('cli:migrate')
, db = require('./db') var db = require('./db')
db.setup() db.setup()
.then(function() { .then(function() {
@ -924,21 +924,21 @@ program
, 1) , 1)
.action(function(model, options) { .action(function(model, options) {
var log = logger.createLogger('cli:generate-fake-device') var log = logger.createLogger('cli:generate-fake-device')
, fake = require('./util/fakedevice') var fake = require('./util/fakedevice')
, n = options.number var n = options.number
function next() { function nextDevice() {
return fake.generate(model) return fake.generate(model)
.then(function(serial) { .then(function(serial) {
log.info('Created fake device "%s"', serial) log.info('Created fake device "%s"', serial)
if (--n) { if (--n) {
return next() return nextDevice()
} }
}) })
} }
next() nextDevice()
.then(function() { .then(function() {
process.exit(0) process.exit(0)
}) })
@ -1069,7 +1069,7 @@ program
, 'whether to lock rotation when devices are being used') , 'whether to lock rotation when devices are being used')
.action(function(serials, options) { .action(function(serials, options) {
var log = logger.createLogger('cli:local') var log = logger.createLogger('cli:local')
, procutil = require('./util/procutil') var procutil = require('./util/procutil')
// Each forked process waits for signals to stop, and so we run over the // Each forked process waits for signals to stop, and so we run over the
// default limit of 10. So, it's not a leak, but a refactor wouldn't hurt. // default limit of 10. So, it's not a leak, but a refactor wouldn't hurt.
@ -1156,7 +1156,10 @@ program
'http://%s:%d/auth/%s/' 'http://%s:%d/auth/%s/'
, options.publicIp , options.publicIp
, options.poorxyPort , options.poorxyPort
, ({oauth2: 'oauth', saml2: 'saml'}[options.authType]) || options.authType , {
oauth2: 'oauth'
, saml2: 'saml'
}[options.authType] || options.authType
) )
, '--websocket-url', util.format( , '--websocket-url', util.format(
'http://%s:%d/' 'http://%s:%d/'

View file

@ -320,7 +320,7 @@ dbapi.saveUserAccessToken = function(email, token) {
dbapi.removeUserAccessToken = function(email, title) { dbapi.removeUserAccessToken = function(email, title) {
return db.run(r.table('accessTokens').getAll(email, { return db.run(r.table('accessTokens').getAll(email, {
index: 'email' index: 'email'
}).filter({'title': title}).delete()) }).filter({title: title}).delete())
} }
dbapi.loadAccessTokens = function(email) { dbapi.loadAccessTokens = function(email) {

View file

@ -48,7 +48,7 @@ function connect() {
// Export connection as a Promise // Export connection as a Promise
db.connect = (function() { db.connect = (function() {
var connection var connection
, queue = [] var queue = []
lifecycle.observe(function() { lifecycle.observe(function() {
if (connection) { if (connection) {

View file

@ -28,7 +28,7 @@ module.exports = function(conn) {
function createIndex(table, index, options) { function createIndex(table, index, options) {
var args = [index] var args = [index]
, rTable = r.table(table) var rTable = r.table(table)
if (options) { if (options) {
if (options.indexFunction) { if (options.indexFunction) {

View file

@ -26,8 +26,8 @@ var markdownServe = require('markdown-serve')
module.exports = function(options) { module.exports = function(options) {
var log = logger.createLogger('app') var log = logger.createLogger('app')
, app = express() var app = express()
, server = http.createServer(app) var server = http.createServer(app)
app.use('/static/wiki', markdownServe.middleware({ app.use('/static/wiki', markdownServe.middleware({
rootDirectory: pathutil.root('node_modules/stf-wiki') rootDirectory: pathutil.root('node_modules/stf-wiki')
@ -50,9 +50,9 @@ module.exports = function(options) {
})) }))
} }
else { else {
log.info('Using webpack')
// Keep webpack-related requires here, as our prebuilt package won't // Keep webpack-related requires here, as our prebuilt package won't
// have them at all. // have them at all.
log.info('Using webpack')
var webpackServerConfig = require('./../../../webpack.config').webpackServer var webpackServerConfig = require('./../../../webpack.config').webpackServer
app.use('/static/app/build', app.use('/static/app/build',
require('./middleware/webpack')(webpackServerConfig)) require('./middleware/webpack')(webpackServerConfig))
@ -115,7 +115,7 @@ module.exports = function(options) {
} }
if (options.userProfileUrl) { if (options.userProfileUrl) {
state.config.userProfileUrl = (function () { state.config.userProfileUrl = (function() {
return options.userProfileUrl return options.userProfileUrl
})() })()
} }

View file

@ -8,7 +8,7 @@ module.exports = function(options) {
if (req.query.jwt) { if (req.query.jwt) {
// Coming from auth client // Coming from auth client
var data = jwtutil.decode(req.query.jwt, options.secret) var data = jwtutil.decode(req.query.jwt, options.secret)
, redir = urlutil.removeParam(req.url, 'jwt') var redir = urlutil.removeParam(req.url, 'jwt')
if (data) { if (data) {
// Redirect once to get rid of the token // Redirect once to get rid of the token
dbapi.saveUserAfterLogin({ dbapi.saveUserAfterLogin({

View file

@ -14,9 +14,9 @@ var globalOptions = require('../../../../webpack.config').webpack
// Similar to webpack-dev-middleware, but integrates with our custom // Similar to webpack-dev-middleware, but integrates with our custom
// lifecycle, behaves more like normal express middleware, and removes // lifecycle, behaves more like normal express middleware, and removes
// all unnecessary features. // all unnecessary features.
module.exports = function(options) { module.exports = function(localOptions) {
var log = logger.createLogger('middleware:webpack') var log = logger.createLogger('middleware:webpack')
options = _.defaults(options || {}, globalOptions) var options = _.defaults(localOptions || {}, globalOptions)
var compiler = webpack(options) var compiler = webpack(options)
var fs = compiler.outputFileSystem = new MemoryFileSystem() var fs = compiler.outputFileSystem = new MemoryFileSystem()
@ -77,13 +77,12 @@ module.exports = function(options) {
if (valid) { if (valid) {
return Promise.resolve() return Promise.resolve()
} }
else {
log.info('Waiting for bundle to finish') log.info('Waiting for bundle to finish')
var resolver = Promise.defer() var resolver = Promise.defer()
queue.push(resolver) queue.push(resolver)
return resolver.promise return resolver.promise
} }
}
return function(req, res, next) { return function(req, res, next) {
var parsedUrl = url.parse(req.url) var parsedUrl = url.parse(req.url)

View file

@ -18,8 +18,8 @@ var lifecycle = require('../../util/lifecycle')
module.exports = function(options) { module.exports = function(options) {
var log = logger.createLogger('auth-ldap') var log = logger.createLogger('auth-ldap')
, app = express() var app = express()
, server = Promise.promisifyAll(http.createServer(app)) var server = Promise.promisifyAll(http.createServer(app))
lifecycle.observe(function() { lifecycle.observe(function() {
log.info('Waiting for client connections to end') log.info('Waiting for client connections to end')
@ -46,7 +46,7 @@ module.exports = function(options) {
app.use('/static/auth/ldap', serveStatic(pathutil.resource('auth/ldap'))) app.use('/static/auth/ldap', serveStatic(pathutil.resource('auth/ldap')))
app.use(function(req, res, next) { app.use(function(req, res, next) {
res.cookie('XSRF-TOKEN', req.csrfToken()); res.cookie('XSRF-TOKEN', req.csrfToken())
next() next()
}) })

View file

@ -17,8 +17,8 @@ var lifecycle = require('../../util/lifecycle')
module.exports = function(options) { module.exports = function(options) {
var log = logger.createLogger('auth-mock') var log = logger.createLogger('auth-mock')
, app = express() var app = express()
, server = Promise.promisifyAll(http.createServer(app)) var server = Promise.promisifyAll(http.createServer(app))
lifecycle.observe(function() { lifecycle.observe(function() {
log.info('Waiting for client connections to end') log.info('Waiting for client connections to end')
@ -45,7 +45,7 @@ module.exports = function(options) {
app.use('/static/auth/mock', serveStatic(pathutil.resource('auth/mock'))) app.use('/static/auth/mock', serveStatic(pathutil.resource('auth/mock')))
app.use(function(req, res, next) { app.use(function(req, res, next) {
res.cookie('XSRF-TOKEN', req.csrfToken()); res.cookie('XSRF-TOKEN', req.csrfToken())
next() next()
}) })

View file

@ -10,8 +10,8 @@ var Strategy = require('./strategy')
module.exports = function(options) { module.exports = function(options) {
var log = logger.createLogger('auth-oauth2') var log = logger.createLogger('auth-oauth2')
, app = express() var app = express()
, server = http.createServer(app) var server = http.createServer(app)
app.set('strict routing', true) app.set('strict routing', true)
app.set('case sensitive routing', true) app.set('case sensitive routing', true)

View file

@ -18,14 +18,13 @@ Strategy.prototype.userProfile = function(accessToken, callback) {
if (err) { if (err) {
return callback(err) return callback(err)
} }
else {
try { try {
return callback(null, JSON.parse(data)) return callback(null, JSON.parse(data))
} }
catch (err) { catch (err) {
return callback(err) return callback(err)
} }
}
}) })
} }

View file

@ -13,20 +13,20 @@ var jwtutil = require('../../util/jwtutil')
module.exports = function(options) { module.exports = function(options) {
var log = logger.createLogger('auth-saml2') var log = logger.createLogger('auth-saml2')
, app = express() var app = express()
, server = http.createServer(app) var server = http.createServer(app)
app.set('strict routing', true) app.set('strict routing', true)
app.set('case sensitive routing', true) app.set('case sensitive routing', true)
app.use(bodyParser.urlencoded({ extended: false })) app.use(bodyParser.urlencoded({extended: false}))
app.use(passport.initialize()) app.use(passport.initialize())
passport.serializeUser(function(user, done) { passport.serializeUser(function(user, done) {
done(null, user); done(null, user)
}); })
passport.deserializeUser(function(user, done) { passport.deserializeUser(function(user, done) {
done(null, user); done(null, user)
}); })
var verify = function(profile, done) { var verify = function(profile, done) {
return done(null, profile) return done(null, profile)

View file

@ -18,7 +18,7 @@ module.exports = syrup.serial()
return service.getAccounts({type: type}) return service.getAccounts({type: type})
.timeout(30000) .timeout(30000)
.then(function(accounts) { .then(function(accounts) {
if(accounts.indexOf(account) >= 0) { if (accounts.indexOf(account) >= 0) {
return true return true
} }
throw new Error('The account is not added') throw new Error('The account is not added')
@ -28,7 +28,7 @@ module.exports = syrup.serial()
router.on(wire.AccountCheckMessage, function(channel, message) { router.on(wire.AccountCheckMessage, function(channel, message) {
var reply = wireutil.reply(options.serial) var reply = wireutil.reply(options.serial)
log.info('Checking if account "%s" is added',message.account) log.info('Checking if account "%s" is added', message.account)
checkAccount(message.type, message.account) checkAccount(message.type, message.account)
.then(function() { .then(function() {
push.send([ push.send([
@ -55,7 +55,7 @@ module.exports = syrup.serial()
.then(function(accounts) { .then(function(accounts) {
push.send([ push.send([
channel channel
, reply.okay('success',accounts) , reply.okay('success', accounts)
]) ])
}) })
.catch(function(err) { .catch(function(err) {
@ -113,12 +113,12 @@ module.exports = syrup.serial()
router.on(wire.AccountAddMessage, function(channel, message) { router.on(wire.AccountAddMessage, function(channel, message) {
var reply = wireutil.reply(options.serial) var reply = wireutil.reply(options.serial)
var type = "com.google" var type = 'com.google'
var account = message.user + "@gmail.com"; var account = message.user + '@gmail.com'
log.info('Adding Google Account automatedly') log.info('Adding Google Account automatedly')
var version = identity.version.substring(0,3) var version = identity.version.substring(0, 3)
function automation() { function automation() {
switch (version) { switch (version) {
@ -235,8 +235,8 @@ module.exports = syrup.serial()
.then(function() { .then(function() {
return service.pressKey('enter') return service.pressKey('enter')
}) })
//case '4.3': // tested: 4.3 // case '4.3': // tested: 4.3
//case '4.4': // tested: 4.4.2 // case '4.4': // tested: 4.4.2
default: default:
return service.pressKey('tab').delay(1000) return service.pressKey('tab').delay(1000)
.then(function() { .then(function() {
@ -293,17 +293,17 @@ module.exports = syrup.serial()
.delay(5000) .delay(5000)
.then(function() { .then(function() {
// Just in case the add account menu has any button focused // Just in case the add account menu has any button focused
return touch.tap({x:0, y:0.9}) return touch.tap({x: 0, y: 0.9})
}) })
.delay(500) .delay(500)
.then(function() { .then(function() {
return automation() return automation()
}) })
.delay(3000) .delay(3000)
.then(function () { .then(function() {
return service.pressKey('home') return service.pressKey('home')
}) })
.then(function () { .then(function() {
return checkAccount(type, account) return checkAccount(type, account)
}) })
.then(function() { .then(function() {

View file

@ -51,8 +51,17 @@ module.exports = syrup.serial()
function compareIgnoreCase(a, b) { function compareIgnoreCase(a, b) {
var la = (a || '').toLowerCase() var la = (a || '').toLowerCase()
, lb = (b || '').toLowerCase() var lb = (b || '').toLowerCase()
return la === lb ? 0 : (la < lb ? -1 : 1)
if (la === lb) {
return 0
}
else if (la < lb) {
return -1
}
else {
return 1
}
} }
function updateBrowsers(data) { function updateBrowsers(data) {

View file

@ -40,7 +40,6 @@ module.exports = syrup.serial()
group.on('leave', function() { group.on('leave', function() {
plugin.removePackages() plugin.removePackages()
}) })
}) })
.return(plugin) .return(plugin)
}) })

View file

@ -18,8 +18,8 @@ module.exports = syrup.serial()
.dependency(require('./util/urlformat')) .dependency(require('./util/urlformat'))
.define(function(options, adb, router, push, group, solo, urlformat) { .define(function(options, adb, router, push, group, solo, urlformat) {
var log = logger.createLogger('device:plugins:connect') var log = logger.createLogger('device:plugins:connect')
, plugin = Object.create(null) var plugin = Object.create(null)
, activeServer = null var activeServer = null
plugin.port = options.connectPort plugin.port = options.connectPort
plugin.url = urlformat(options.connectUrlPattern, plugin.port) plugin.url = urlformat(options.connectUrlPattern, plugin.port)

View file

@ -44,7 +44,7 @@ module.exports = syrup.serial()
if (/closed/.test(err.message) && times > 1) { if (/closed/.test(err.message) && times > 1) {
return Promise.delay(delay) return Promise.delay(delay)
.then(function() { .then(function() {
return tryConnect(--times, delay * 2) return tryConnect(times - 1, delay * 2)
}) })
} }
return Promise.reject(err) return Promise.reject(err)

View file

@ -5,6 +5,115 @@ var net = require('net')
var ForwardReader = require('./reader') var ForwardReader = require('./reader')
var ForwardWriter = require('./writer') var ForwardWriter = require('./writer')
// Handles a single connection
function DestHandler(id, conn, options) {
var dest = net.connect({
host: options.targetHost
, port: options.targetPort
})
var writer = dest.pipe(new ForwardWriter(id))
// We can't just pipe to conn because we don't want to end it
// when the dest closes. Instead we'll send a special packet
// to it (which is handled by the writer).
function maybePipeManually() {
var chunk
while ((chunk = writer.read())) {
if (!conn.write(chunk)) {
break
}
}
}
function readableListener() {
maybePipeManually()
}
function drainListener() {
maybePipeManually()
}
function endListener() {
conn.removeListener('drain', drainListener)
writer.removeListener('readable', readableListener)
this.emit('end')
}
function errorListener() {
writer.end()
}
writer.on('end', endListener.bind(this))
writer.on('readable', readableListener)
dest.on('error', errorListener)
conn.on('drain', drainListener)
this.end = function() {
dest.end()
}
this.write = function(chunk) {
dest.write(chunk)
}
events.EventEmitter.call(this)
}
util.inherits(DestHandler, events.EventEmitter)
// Handles a single port
function ForwardHandler(conn, options) {
var destHandlersById = Object.create(null)
function endListener() {
this.emit('end')
}
function packetEndListener(id) {
delete destHandlersById[id]
}
function packetListener(id, packet) {
var dest = destHandlersById[id]
if (packet) {
if (!dest) {
// Let's create a new connection
dest = destHandlersById[id] = new DestHandler(id, conn, options)
dest.on('end', packetEndListener.bind(null, id))
}
dest.write(packet)
}
else {
// It's a simulated fin packet
if (dest) {
dest.end()
}
}
}
function readableListener() {
// No-op but must exist so that we get the 'end' event.
}
conn.pipe(new ForwardReader())
.on('end', endListener.bind(this))
.on('packet', packetListener)
.on('readable', readableListener)
this.options = options
this.end = function() {
conn.end()
}
events.EventEmitter.call(this)
}
util.inherits(ForwardHandler, events.EventEmitter)
// Handles multiple ports // Handles multiple ports
function ForwardManager() { function ForwardManager() {
var handlersById = Object.create(null) var handlersById = Object.create(null)
@ -61,113 +170,4 @@ function ForwardManager() {
util.inherits(ForwardManager, events.EventEmitter) util.inherits(ForwardManager, events.EventEmitter)
// Handles a single port
function ForwardHandler(conn, options) {
var destHandlersById = Object.create(null)
function endListener() {
this.emit('end')
}
function packetEndListener(id) {
delete destHandlersById[id]
}
function packetListener(id, packet) {
var dest = destHandlersById[id]
if (packet) {
if (!dest) {
// Let's create a new connection
dest = destHandlersById[id] = new DestHandler(id, conn, options)
dest.on('end', packetEndListener.bind(null, id))
}
dest.write(packet)
}
else {
// It's a simulated fin packet
if (dest) {
dest.end()
}
}
}
function readableListener() {
// No-op but must exist so that we get the 'end' event.
}
conn.pipe(new ForwardReader())
.on('end', endListener.bind(this))
.on('packet', packetListener)
.on('readable', readableListener)
this.options = options
this.end = function() {
conn.end()
}
events.EventEmitter.call(this)
}
util.inherits(ForwardHandler, events.EventEmitter)
// Handles a single connection
function DestHandler(id, conn, options) {
function endListener() {
conn.removeListener('drain', drainListener)
writer.removeListener('readable', readableListener)
this.emit('end')
}
function errorListener() {
writer.end()
}
function readableListener() {
maybePipeManually()
}
function drainListener() {
maybePipeManually()
}
// We can't just pipe to conn because we don't want to end it
// when the dest closes. Instead we'll send a special packet
// to it (which is handled by the writer).
function maybePipeManually() {
var chunk
while ((chunk = writer.read())) {
if (!conn.write(chunk)) {
break
}
}
}
var dest = net.connect({
host: options.targetHost
, port: options.targetPort
})
.on('error', errorListener)
var writer = dest.pipe(new ForwardWriter(id))
.on('end', endListener.bind(this))
.on('readable', readableListener)
conn.on('drain', drainListener)
this.end = function() {
dest.end()
}
this.write = function(chunk) {
dest.write(chunk)
}
events.EventEmitter.call(this)
}
util.inherits(DestHandler, events.EventEmitter)
module.exports = ForwardManager module.exports = ForwardManager

View file

@ -11,9 +11,9 @@ function ForwardWriter(target) {
util.inherits(ForwardWriter, stream.Transform) util.inherits(ForwardWriter, stream.Transform)
ForwardWriter.prototype._transform = function(chunk, encoding, done) { ForwardWriter.prototype._transform = function(fullChunk, encoding, done) {
var header var chunk = fullChunk
, length var header, length
do { do {
length = Math.min(MAX_PACKET_SIZE, chunk.length) length = Math.min(MAX_PACKET_SIZE, chunk.length)

View file

@ -19,8 +19,8 @@ module.exports = syrup.serial()
.dependency(require('../support/channels')) .dependency(require('../support/channels'))
.define(function(options, solo, ident, service, router, push, sub, channels) { .define(function(options, solo, ident, service, router, push, sub, channels) {
var log = logger.createLogger('device:plugins:group') var log = logger.createLogger('device:plugins:group')
, currentGroup = null var currentGroup = null
, plugin = new events.EventEmitter() var plugin = new events.EventEmitter()
plugin.get = Promise.method(function() { plugin.get = Promise.method(function() {
if (!currentGroup) { if (!currentGroup) {

View file

@ -27,7 +27,7 @@ module.exports = syrup.serial()
router.on(wire.InstallMessage, function(channel, message) { router.on(wire.InstallMessage, function(channel, message) {
var manifest = JSON.parse(message.manifest) var manifest = JSON.parse(message.manifest)
, pkg = manifest.package var pkg = manifest.package
log.info('Installing package "%s" from "%s"', pkg, message.href) log.info('Installing package "%s" from "%s"', pkg, message.href)
@ -98,8 +98,8 @@ module.exports = syrup.serial()
pushApp() pushApp()
.then(function(apk) { .then(function(apk) {
var start = 50 var start = 50
, end = 90 var end = 90
, guesstimate = start var guesstimate = start
sendProgress('installing_app', guesstimate) sendProgress('installing_app', guesstimate)
return promiseutil.periodicNotify( return promiseutil.periodicNotify(

View file

@ -13,8 +13,8 @@ module.exports = syrup.serial()
.dependency(require('./group')) .dependency(require('./group'))
.define(function(options, adb, router, push, group) { .define(function(options, adb, router, push, group) {
var log = logger.createLogger('device:plugins:logcat') var log = logger.createLogger('device:plugins:logcat')
, plugin = Object.create(null) var plugin = Object.create(null)
, activeLogcat = null var activeLogcat = null
plugin.start = function(filters) { plugin.start = function(filters) {
return group.get() return group.get()

View file

@ -13,12 +13,12 @@ module.exports = syrup.serial()
log.info('Will mute master volume during use') log.info('Will mute master volume during use')
group.on('join', function() { group.on('join', function() {
log.info('Muting master volume'); log.info('Muting master volume')
service.setMasterMute(true) service.setMasterMute(true)
}) })
group.on('leave', function() { group.on('leave', function() {
log.info('Unmuting master volume'); log.info('Unmuting master volume')
service.setMasterMute(false) service.setMasterMute(false)
}) })
} }

View file

@ -176,11 +176,13 @@ module.exports = syrup.serial()
} }
FrameProducer.prototype.nextFrame = function() { FrameProducer.prototype.nextFrame = function() {
var frame = null, chunk var frame = null
var chunk
if (this.parser) { if (this.parser) {
while ((frame = this.parser.nextFrame()) === null) { while ((frame = this.parser.nextFrame()) === null) {
if ((chunk = this.socket.stream.read())) { chunk = this.socket.stream.read()
if (chunk) {
this.parser.push(chunk) this.parser.push(chunk)
} }
else { else {
@ -243,9 +245,9 @@ module.exports = syrup.serial()
return lifecycle.fatal() return lifecycle.fatal()
} }
var match var match = /^PID: (\d+)$/.exec(line)
if ((match = /^PID: (\d+)$/.exec(line))) { if (match) {
this.pid = +match[1] this.pid = Number(match[1])
this.emit('pid', this.pid) this.emit('pid', this.pid)
} }
@ -259,7 +261,7 @@ module.exports = syrup.serial()
} }
var pidListener var pidListener
return new Promise(function(resolve/*, reject*/) { return new Promise(function(resolve) {
this.on('pid', pidListener = resolve) this.on('pid', pidListener = resolve)
}.bind(this)).bind(this) }.bind(this)).bind(this)
.timeout(2000) .timeout(2000)
@ -279,7 +281,7 @@ module.exports = syrup.serial()
if (/closed/.test(err.message) && times > 1) { if (/closed/.test(err.message) && times > 1) {
return Promise.delay(delay) return Promise.delay(delay)
.then(function() { .then(function() {
return tryConnect(--times, delay * 2) return tryConnect(times - 1, delay * 2)
}) })
} }
return Promise.reject(err) return Promise.reject(err)
@ -326,7 +328,7 @@ module.exports = syrup.serial()
socket.stream.removeListener('readable', this.readableListener) socket.stream.removeListener('readable', this.readableListener)
var endListener var endListener
return new Promise(function(resolve/*, reject*/) { return new Promise(function(resolve) {
socket.on('end', endListener = function() { socket.on('end', endListener = function() {
resolve(true) resolve(true)
}) })
@ -354,8 +356,8 @@ module.exports = syrup.serial()
} }
var signum = { var signum = {
'SIGTERM': -15 SIGTERM: -15
, 'SIGKILL': -9 , SIGKILL: -9
}[signal] }[signal]
log.info('Sending %s to minicap', signal) log.info('Sending %s to minicap', signal)
@ -478,8 +480,8 @@ module.exports = syrup.serial()
}) })
frameProducer.on('readable', function next() { frameProducer.on('readable', function next() {
var frame var frame = frameProducer.nextFrame()
if ((frame = frameProducer.nextFrame())) { if (frame) {
Promise.settle([broadcastSet.keys().map(function(id) { Promise.settle([broadcastSet.keys().map(function(id) {
return broadcastSet.get(id).onFrame(frame) return broadcastSet.get(id).onFrame(frame)
})]).then(next) })]).then(next)
@ -557,8 +559,8 @@ module.exports = syrup.serial()
} }
ws.on('message', function(data) { ws.on('message', function(data) {
var match var match = /^(on|off|(size) ([0-9]+)x([0-9]+))$/.exec(data)
if ((match = /^(on|off|(size) ([0-9]+)x([0-9]+))$/.exec(data))) { if (match) {
switch (match[2] || match[1]) { switch (match[2] || match[1]) {
case 'on': case 'on':
broadcastSet.insert(id, { broadcastSet.insert(id, {
@ -570,7 +572,8 @@ module.exports = syrup.serial()
broadcastSet.remove(id) broadcastSet.remove(id)
break break
case 'size': case 'size':
frameProducer.updateProjection(+match[3], +match[4]) frameProducer.updateProjection(
Number(match[3]), Number(match[4]))
break break
} }
} }

View file

@ -30,12 +30,17 @@ FrameParser.prototype.nextFrame = function() {
var bytesLeft = len - this.cursor var bytesLeft = len - this.cursor
if (bytesLeft >= this.frameBodyLength) { if (bytesLeft >= this.frameBodyLength) {
var completeBody = this.frameBody var completeBody
? Buffer.concat([ if (this.frameBody) {
completeBody = Buffer.concat([
this.frameBody this.frameBody
, this.chunk.slice(this.cursor, this.cursor + this.frameBodyLength) , this.chunk.slice(this.cursor, this.cursor + this.frameBodyLength)
]) ])
: this.chunk.slice(this.cursor, this.cursor + this.frameBodyLength) }
else {
completeBody = this.chunk.slice(this.cursor,
this.cursor + this.frameBodyLength)
}
this.cursor += this.frameBodyLength this.cursor += this.frameBodyLength
this.frameBodyLength = this.readFrameBytes = 0 this.frameBodyLength = this.readFrameBytes = 0
@ -46,9 +51,13 @@ FrameParser.prototype.nextFrame = function() {
else { else {
// @todo Consider/benchmark continuation frames to prevent // @todo Consider/benchmark continuation frames to prevent
// potential Buffer thrashing. // potential Buffer thrashing.
this.frameBody = this.frameBody if (this.frameBody) {
? Buffer.concat([this.frameBody, this.chunk.slice(this.cursor, len)]) this.frameBody =
: this.chunk.slice(this.cursor, len) Buffer.concat([this.frameBody, this.chunk.slice(this.cursor, len)])
}
else {
this.frameBody = this.chunk.slice(this.cursor, len)
}
this.frameBodyLength -= bytesLeft this.frameBodyLength -= bytesLeft
this.readFrameBytes += bytesLeft this.readFrameBytes += bytesLeft

View file

@ -52,60 +52,6 @@ module.exports = syrup.serial()
, port: 1100 , port: 1100
} }
function openAgent() {
log.info('Launching agent')
return stopAgent()
.timeout(15000)
.then(function() {
return devutil.ensureUnusedPort(adb, options.serial, agent.port)
.timeout(10000)
})
.then(function() {
return adb.shell(options.serial, util.format(
"export CLASSPATH='%s'; exec app_process /system/bin '%s'"
, apk.path
, apk.main
))
.timeout(10000)
})
.then(function(out) {
streamutil.talk(log, 'Agent says: "%s"', out)
})
.then(function() {
return devutil.waitForPort(adb, options.serial, agent.port)
.timeout(10000)
})
.then(function(conn) {
agent.socket = conn
agent.writer = new ms.DelimitingStream()
agent.writer.pipe(conn)
return prepareForAgentDeath(conn)
})
}
function prepareForAgentDeath(conn) {
function endListener() {
var startTime = Date.now()
log.important('Agent connection ended, attempting to relaunch')
openService()
.timeout(5000)
.then(function() {
log.important('Agent relaunched in %dms', Date.now() - startTime)
})
.catch(function(err) {
log.fatal('Agent connection could not be relaunched', err.stack)
lifecycle.fatal()
})
}
conn.once('end', endListener)
conn.on('error', function(err) {
log.fatal('Agent connection had an error', err.stack)
lifecycle.fatal()
})
}
function stopAgent() { function stopAgent() {
return devutil.killProcsByComm( return devutil.killProcsByComm(
adb adb
@ -164,34 +110,12 @@ module.exports = syrup.serial()
}) })
} }
// The APK should be up to date at this point. If it was reinstalled, the
// service should have been automatically stopped while it was happening.
// So, we should be good to go.
function openService() {
log.info('Launching service')
return callService(util.format(
"-a '%s' -n '%s'"
, apk.startIntent.action
, apk.startIntent.component
))
.then(function() {
return devutil.waitForPort(adb, options.serial, service.port)
.timeout(15000)
})
.then(function(conn) {
service.socket = conn
service.reader = conn.pipe(new ms.DelimitedStream())
service.reader.on('data', handleEnvelope)
service.writer = new ms.DelimitingStream()
service.writer.pipe(conn)
return prepareForServiceDeath(conn)
})
}
function prepareForServiceDeath(conn) { function prepareForServiceDeath(conn) {
function endListener() { function endListener() {
var startTime = Date.now() var startTime = Date.now()
log.important('Service connection ended, attempting to relaunch') log.important('Service connection ended, attempting to relaunch')
/* eslint no-use-before-define: 0 */
openService() openService()
.timeout(5000) .timeout(5000)
.then(function() { .then(function() {
@ -213,7 +137,7 @@ module.exports = syrup.serial()
function handleEnvelope(data) { function handleEnvelope(data) {
var envelope = apk.wire.Envelope.decode(data) var envelope = apk.wire.Envelope.decode(data)
, message var message
if (envelope.id !== null) { if (envelope.id !== null) {
messageResolver.resolve(envelope.id, envelope.message) messageResolver.resolve(envelope.id, envelope.message)
} }
@ -294,6 +218,92 @@ module.exports = syrup.serial()
} }
} }
// The APK should be up to date at this point. If it was reinstalled, the
// service should have been automatically stopped while it was happening.
// So, we should be good to go.
function openService() {
log.info('Launching service')
return callService(util.format(
"-a '%s' -n '%s'"
, apk.startIntent.action
, apk.startIntent.component
))
.then(function() {
return devutil.waitForPort(adb, options.serial, service.port)
.timeout(15000)
})
.then(function(conn) {
service.socket = conn
service.reader = conn.pipe(new ms.DelimitedStream())
service.reader.on('data', handleEnvelope)
service.writer = new ms.DelimitingStream()
service.writer.pipe(conn)
return prepareForServiceDeath(conn)
})
}
function prepareForAgentDeath(conn) {
function endListener() {
var startTime = Date.now()
log.important('Agent connection ended, attempting to relaunch')
openService()
.timeout(5000)
.then(function() {
log.important('Agent relaunched in %dms', Date.now() - startTime)
})
.catch(function(err) {
log.fatal('Agent connection could not be relaunched', err.stack)
lifecycle.fatal()
})
}
conn.once('end', endListener)
conn.on('error', function(err) {
log.fatal('Agent connection had an error', err.stack)
lifecycle.fatal()
})
}
function openAgent() {
log.info('Launching agent')
return stopAgent()
.timeout(15000)
.then(function() {
return devutil.ensureUnusedPort(adb, options.serial, agent.port)
.timeout(10000)
})
.then(function() {
return adb.shell(options.serial, util.format(
"export CLASSPATH='%s'; exec app_process /system/bin '%s'"
, apk.path
, apk.main
))
.timeout(10000)
})
.then(function(out) {
streamutil.talk(log, 'Agent says: "%s"', out)
})
.then(function() {
return devutil.waitForPort(adb, options.serial, agent.port)
.timeout(10000)
})
.then(function(conn) {
agent.socket = conn
agent.writer = new ms.DelimitingStream()
agent.writer.pipe(conn)
return prepareForAgentDeath(conn)
})
}
function runAgentCommand(type, cmd) {
agent.writer.write(new apk.wire.Envelope(
null
, type
, cmd.encodeNB()
).encodeNB())
}
function keyEvent(data) { function keyEvent(data) {
return runAgentCommand( return runAgentCommand(
apk.wire.MessageType.DO_KEYEVENT apk.wire.MessageType.DO_KEYEVENT
@ -326,6 +336,17 @@ module.exports = syrup.serial()
return plugin.getClipboard() return plugin.getClipboard()
} }
function runServiceCommand(type, cmd) {
var resolver = Promise.defer()
var id = Math.floor(Math.random() * 0xFFFFFF)
service.writer.write(new apk.wire.Envelope(
id
, type
, cmd.encodeNB()
).encodeNB())
return messageResolver.await(id, resolver)
}
plugin.getDisplay = function(id) { plugin.getDisplay = function(id) {
return runServiceCommand( return runServiceCommand(
apk.wire.MessageType.GET_DISPLAY apk.wire.MessageType.GET_DISPLAY
@ -651,7 +672,7 @@ module.exports = syrup.serial()
}) })
} }
plugin.getSdStatus = function () { plugin.getSdStatus = function() {
return runServiceCommand( return runServiceCommand(
apk.wire.MessageType.GET_SD_STATUS apk.wire.MessageType.GET_SD_STATUS
, new apk.wire.GetSdStatusRequest() , new apk.wire.GetSdStatusRequest()
@ -685,25 +706,6 @@ module.exports = syrup.serial()
}) })
} }
function runServiceCommand(type, cmd) {
var resolver = Promise.defer()
var id = Math.floor(Math.random() * 0xFFFFFF)
service.writer.write(new apk.wire.Envelope(
id
, type
, cmd.encodeNB()
).encodeNB())
return messageResolver.await(id, resolver)
}
function runAgentCommand(type, cmd) {
agent.writer.write(new apk.wire.Envelope(
null
, type
, cmd.encodeNB()
).encodeNB())
}
return openAgent() return openAgent()
.then(openService) .then(openService)
.then(function() { .then(function() {
@ -723,7 +725,7 @@ module.exports = syrup.serial()
, keyCode: keyutil.namedKey(message.key) , keyCode: keyutil.namedKey(message.key)
}) })
} }
catch(e) { catch (e) {
log.warn(e.message) log.warn(e.message)
} }
}) })
@ -734,7 +736,7 @@ module.exports = syrup.serial()
, keyCode: keyutil.namedKey(message.key) , keyCode: keyutil.namedKey(message.key)
}) })
} }
catch(e) { catch (e) {
log.warn(e.message) log.warn(e.message)
} }
}) })
@ -745,7 +747,7 @@ module.exports = syrup.serial()
, keyCode: keyutil.namedKey(message.key) , keyCode: keyutil.namedKey(message.key)
}) })
} }
catch(e) { catch (e) {
log.warn(e.message) log.warn(e.message)
} }
}) })

View file

@ -22,7 +22,11 @@ module.exports = syrup.serial()
.timeout(10000) .timeout(10000)
.then(function(stream) { .then(function(stream) {
var resolver = Promise.defer() var resolver = Promise.defer()
, timer var timer
function forceStop() {
stream.end()
}
function keepAliveListener(channel, message) { function keepAliveListener(channel, message) {
clearTimeout(timer) clearTimeout(timer)
@ -51,10 +55,6 @@ module.exports = syrup.serial()
resolver.reject(err) resolver.reject(err)
} }
function forceStop() {
stream.end()
}
stream.setEncoding('utf8') stream.setEncoding('utf8')
stream.on('readable', readableListener) stream.on('readable', readableListener)

View file

@ -268,7 +268,7 @@ module.exports = syrup.serial()
if (/closed/.test(err.message) && times > 1) { if (/closed/.test(err.message) && times > 1) {
return Promise.delay(delay) return Promise.delay(delay)
.then(function() { .then(function() {
return tryConnect(--times, delay * 2) return tryConnect(times - 1, delay * 2)
}) })
} }
return Promise.reject(err) return Promise.reject(err)
@ -315,7 +315,7 @@ module.exports = syrup.serial()
socket.stream.removeListener('readable', this.readableListener) socket.stream.removeListener('readable', this.readableListener)
var endListener var endListener
return new Promise(function(resolve/*, reject*/) { return new Promise(function(resolve) {
socket.on('end', endListener = function() { socket.on('end', endListener = function() {
resolve(true) resolve(true)
}) })
@ -343,8 +343,8 @@ module.exports = syrup.serial()
} }
var signum = { var signum = {
'SIGTERM': -15 SIGTERM: -15
, 'SIGKILL': -9 , SIGKILL: -9
}[signal] }[signal]
log.info('Sending %s to minitouch', signal) log.info('Sending %s to minitouch', signal)
@ -395,7 +395,7 @@ module.exports = syrup.serial()
var args = chunk.toString().split(/ /g) var args = chunk.toString().split(/ /g)
switch (args[0]) { switch (args[0]) {
case 'v': case 'v':
banner.version = +args[1] banner.version = Number(args[1])
break break
default: default:
throw new Error(util.format( throw new Error(util.format(
@ -432,7 +432,7 @@ module.exports = syrup.serial()
var args = chunk.toString().split(/ /g) var args = chunk.toString().split(/ /g)
switch (args[0]) { switch (args[0]) {
case '$': case '$':
banner.pid = +args[1] banner.pid = Number(args[1])
break break
default: default:
throw new Error(util.format( throw new Error(util.format(

View file

@ -8,9 +8,9 @@ module.exports = syrup.serial()
return data && data.flags && !!data.flags[flag] return data && data.flags && !!data.flags[flag]
} }
, get: function(flag, defaultValue) { , get: function(flag, defaultValue) {
return data && data.flags && data.flags[flag] !== void 0 return data && data.flags && typeof data.flags[flag] !== 'undefined' ?
? data.flags[flag] data.flags[flag] :
: defaultValue defaultValue
} }
} }
}) })

View file

@ -8,11 +8,11 @@ module.exports = syrup.serial()
.define(function(options, identity, data) { .define(function(options, identity, data) {
function createSlug() { function createSlug() {
var model = identity.model var model = identity.model
, name = data ? data.name.id : '' var name = data ? data.name.id : ''
return (name === '' || model.toLowerCase() === name.toLowerCase()) return (name === '' || model.toLowerCase() === name.toLowerCase()) ?
? tr.slugify(model) tr.slugify(model) :
: tr.slugify(name + ' ' + model) tr.slugify(name + ' ' + model)
} }
var defaults = { var defaults = {

View file

@ -182,15 +182,16 @@ module.exports = syrup.serial()
var decoded = jpeg.decompressSync( var decoded = jpeg.decompressSync(
connState.lastFrame, connState.frameConfig) connState.lastFrame, connState.frameConfig)
conn.writeFramebufferUpdate([ conn.writeFramebufferUpdate([{
{ xPosition: 0 xPosition: 0
, yPosition: 0 , yPosition: 0
, width: decoded.width , width: decoded.width
, height: decoded.height , height: decoded.height
, encodingType: VncConnection.ENCODING_RAW , encodingType: VncConnection.ENCODING_RAW
, data: decoded.data , data: decoded.data
} }
, { xPosition: 0 , {
xPosition: 0
, yPosition: 0 , yPosition: 0
, width: decoded.width , width: decoded.width
, height: decoded.height , height: decoded.height
@ -203,7 +204,7 @@ module.exports = syrup.serial()
} }
function vncStartListener(frameProducer) { function vncStartListener(frameProducer) {
return new Promise(function(resolve/*, reject*/) { return new Promise(function(resolve) {
connState.frameWidth = frameProducer.banner.virtualWidth connState.frameWidth = frameProducer.banner.virtualWidth
connState.frameHeight = frameProducer.banner.virtualHeight connState.frameHeight = frameProducer.banner.virtualHeight
resolve() resolve()
@ -211,7 +212,7 @@ module.exports = syrup.serial()
} }
function vncFrameListener(frame) { function vncFrameListener(frame) {
return new Promise(function(resolve/*, reject*/) { return new Promise(function(resolve) {
connState.lastFrame = frame connState.lastFrame = frame
connState.lastFrameTime = Date.now() connState.lastFrameTime = Date.now()
maybeSendFrame() maybeSendFrame()
@ -238,8 +239,10 @@ module.exports = syrup.serial()
}) })
conn.on('formatchange', function(format) { conn.on('formatchange', function(format) {
var same = os.endianness() === 'BE' var same = os.endianness() === 'BE' ===
=== Boolean(format.bigEndianFlag) Boolean(format.bigEndianFlag)
var formatOrder = (format.redShift > format.blueShift) === same
switch (format.bitsPerPixel) { switch (format.bitsPerPixel) {
case 8: case 8:
connState.frameConfig = { connState.frameConfig = {
@ -248,20 +251,19 @@ module.exports = syrup.serial()
break break
case 24: case 24:
connState.frameConfig = { connState.frameConfig = {
format: ((format.redShift > format.blueShift) === same) format: formatOrder ? jpeg.FORMAT_BGR : jpeg.FORMAT_RGB
? jpeg.FORMAT_BGR
: jpeg.FORMAT_RGB
} }
break break
case 32: case 32:
var f
if (formatOrder) {
f = format.blueShift === 0 ? jpeg.FORMAT_BGRX : jpeg.FORMAT_XBGR
}
else {
f = format.redShift === 0 ? jpeg.FORMAT_RGBX : jpeg.FORMAT_XRGB
}
connState.frameConfig = { connState.frameConfig = {
format: ((format.redShift > format.blueShift) === same) format: f
? (format.blueShift === 0
? jpeg.FORMAT_BGRX
: jpeg.FORMAT_XBGR)
: (format.redShift === 0
? jpeg.FORMAT_RGBX
: jpeg.FORMAT_XRGB)
} }
break break
} }

View file

@ -90,7 +90,8 @@ VncConnection.CLIENT_MESSAGE_CLIENTCUTTEXT = 6
VncConnection.SERVER_MESSAGE_FBUPDATE = 0 VncConnection.SERVER_MESSAGE_FBUPDATE = 0
var StateReverse = Object.create(null), State = { var StateReverse = Object.create(null)
var State = {
STATE_NEED_CLIENT_VERSION: 10 STATE_NEED_CLIENT_VERSION: 10
, STATE_NEED_CLIENT_SECURITY: 20 , STATE_NEED_CLIENT_SECURITY: 20
, STATE_NEED_CLIENT_INIT: 30 , STATE_NEED_CLIENT_INIT: 30

View file

@ -31,7 +31,7 @@ module.exports = syrup.serial()
}) })
}) })
router.on(wire.WifiGetStatusMessage, function(channel){ router.on(wire.WifiGetStatusMessage, function(channel) {
var reply = wireutil.reply(options.serial) var reply = wireutil.reply(options.serial)
log.info('Getting Wifi status') log.info('Getting Wifi status')
service.getWifiStatus() service.getWifiStatus()

View file

@ -12,7 +12,7 @@ module.exports = syrup.serial()
.dependency(require('../support/adb')) .dependency(require('../support/adb'))
.dependency(require('../support/abi')) .dependency(require('../support/abi'))
.define(function(options, adb, abi) { .define(function(options, adb, abi) {
var log = logger.createLogger('device:resources:minitouch') // jshint ignore:line logger.createLogger('device:resources:minitouch')
var resources = { var resources = {
bin: { bin: {

View file

@ -85,9 +85,9 @@ module.exports = syrup.serial()
}) })
.progressed(function() { .progressed(function() {
log.warn( log.warn(
'STFService installation is taking a long time; ' 'STFService installation is taking a long time; ' +
+ 'perhaps you have to accept 3rd party app installation ' 'perhaps you have to accept 3rd party app installation ' +
+ 'on the device?' 'on the device?'
) )
}) })
.then(function() { .then(function() {

View file

@ -7,7 +7,6 @@ module.exports = syrup.serial()
.define(function(options, properties) { .define(function(options, properties) {
var log = logger.createLogger('device:support:abi') var log = logger.createLogger('device:support:abi')
return (function() { return (function() {
function split(list) { function split(list) {
return list ? list.split(',') : [] return list ? list.split(',') : []
} }
@ -39,6 +38,5 @@ module.exports = syrup.serial()
log.info('Supports ABIs %s', abi.all.join(', ')) log.info('Supports ABIs %s', abi.all.join(', '))
return abi return abi
})() })()
}) })

View file

@ -26,7 +26,7 @@ module.exports = syrup.serial()
}) })
.then(function() { .then(function() {
// Establish always-on channels // Establish always-on channels
;[wireutil.global].forEach(function(channel) { [wireutil.global].forEach(function(channel) {
log.info('Subscribing to permanent channel "%s"', channel) log.info('Subscribing to permanent channel "%s"', channel)
sub.subscribe(channel) sub.subscribe(channel)
}) })

View file

@ -25,7 +25,7 @@ module.exports = function(options) {
var log = logger.createLogger('notify-hipchat') var log = logger.createLogger('notify-hipchat')
var client = Promise.promisifyAll(new Hipchatter(options.token)) var client = Promise.promisifyAll(new Hipchatter(options.token))
var buffer = [] var buffer = []
, timer var timer
// Input // Input
var sub = zmqutil.socket('sub') var sub = zmqutil.socket('sub')
@ -45,16 +45,6 @@ module.exports = function(options) {
sub.subscribe(channel) sub.subscribe(channel)
}) })
sub.on('message', wirerouter()
.on(wire.DeviceLogMessage, function(channel, message) {
if (message.priority >= options.priority) {
buffer.push(message)
clearTimeout(timer)
timer = setTimeout(push, 1000)
}
})
.handler())
function push() { function push() {
buffer.splice(0).forEach(function(entry) { buffer.splice(0).forEach(function(entry) {
client.notifyAsync(options.room, { client.notifyAsync(options.room, {
@ -68,12 +58,22 @@ module.exports = function(options) {
) )
, color: COLORS[entry.priority] , color: COLORS[entry.priority]
, notify: entry.priority >= options.notifyPriority , notify: entry.priority >= options.notifyPriority
, 'message_format': 'html' , message_format: 'html'
, token: options.token , token: options.token
}) })
}) })
} }
sub.on('message', wirerouter()
.on(wire.DeviceLogMessage, function(channel, message) {
if (message.priority >= options.priority) {
buffer.push(message)
clearTimeout(timer)
timer = setTimeout(push, 1000)
}
})
.handler())
log.info('Listening for %s (or higher) level log messages', log.info('Listening for %s (or higher) level log messages',
logger.LevelLabel[options.priority]) logger.LevelLabel[options.priority])

View file

@ -7,9 +7,9 @@ var logger = require('../../util/logger')
module.exports = function(options) { module.exports = function(options) {
var log = logger.createLogger('poorxy') var log = logger.createLogger('poorxy')
, app = express() var app = express()
, server = http.createServer(app) var server = http.createServer(app)
, proxy = httpProxy.createProxyServer() var proxy = httpProxy.createProxyServer()
proxy.on('error', function(err) { proxy.on('error', function(err) {
log.error('Proxy had an error', err.stack) log.error('Proxy had an error', err.stack)

View file

@ -32,12 +32,13 @@ module.exports = function(options) {
lifecycle.fatal() lifecycle.fatal()
}) })
// Device side
var devDealer = zmqutil.socket('dealer')
appDealer.on('message', function(channel, data) { appDealer.on('message', function(channel, data) {
devDealer.send([channel, data]) devDealer.send([channel, data])
}) })
// Device side
var devDealer = zmqutil.socket('dealer')
Promise.map(options.endpoints.devDealer, function(endpoint) { Promise.map(options.endpoints.devDealer, function(endpoint) {
return srv.resolve(endpoint).then(function(records) { return srv.resolve(endpoint).then(function(records) {
return srv.attempt(records, function(record) { return srv.attempt(records, function(record) {

View file

@ -154,9 +154,8 @@ module.exports = function(options) {
log.info('Found device "%s" (%s)', device.id, device.type) log.info('Found device "%s" (%s)', device.id, device.type)
var privateTracker = new EventEmitter() var privateTracker = new EventEmitter()
, willStop = false var willStop = false
, timer var timer, worker
, worker
// Wait for others to acknowledge the device // Wait for others to acknowledge the device
var register = new Promise(function(resolve) { var register = new Promise(function(resolve) {
@ -176,149 +175,12 @@ module.exports = function(options) {
privateTracker.once('register', resolve) privateTracker.once('register', resolve)
}) })
register.then(function() {
log.info('Registered device "%s"', device.id)
check()
})
// Statistics
lists.all.push(device.id)
delayedTotals()
// Will be set to false when the device is removed
_.assign(device, {
present: true
})
// When any event occurs on the added device
function deviceListener(type, updatedDevice) {
// Okay, this is a bit unnecessary but it allows us to get rid of an
// ugly switch statement and return to the original style.
privateTracker.emit(type, updatedDevice)
}
// When the added device changes
function changeListener(updatedDevice) {
register.then(function() {
log.info(
'Device "%s" is now "%s" (was "%s")'
, device.id
, updatedDevice.type
, device.type
)
_.assign(device, {
type: updatedDevice.type
})
// Tell others the device changed
push.send([
wireutil.global
, wireutil.envelope(new wire.DeviceStatusMessage(
device.id
, wireutil.toDeviceStatus(device.type)
))
])
check()
})
}
// When the added device gets removed
function removeListener() {
register.then(function() {
log.info('Lost device "%s" (%s)', device.id, device.type)
clearTimeout(timer)
flippedTracker.removeListener(device.id, deviceListener)
_.pull(lists.all, device.id)
delayedTotals()
// Tell others the device is gone
push.send([
wireutil.global
, wireutil.envelope(new wire.DeviceAbsentMessage(
device.id
))
])
_.assign(device, {
present: false
})
check()
})
}
// Check if we can do anything with the device
function check() {
clearTimeout(timer)
if (device.present) {
// We might get multiple status updates in rapid succession,
// so let's wait for a while
switch (device.type) {
case 'device':
case 'emulator':
willStop = false
timer = setTimeout(work, 100)
break
default:
willStop = true
timer = setTimeout(stop, 100)
break
}
}
else {
stop()
}
}
// Starts a device worker and keeps it alive
function work() {
return (worker = workers[device.id] = spawn())
.then(function() {
log.info('Device worker "%s" has retired', device.id)
delete workers[device.id]
worker = null
// Tell others the device is gone
push.send([
wireutil.global
, wireutil.envelope(new wire.DeviceAbsentMessage(
device.id
))
])
})
.catch(procutil.ExitError, function(err) {
if (!willStop) {
log.error(
'Device worker "%s" died with code %s'
, device.id
, err.code
)
log.info('Restarting device worker "%s"', device.id)
return Promise.delay(500)
.then(function() {
return work()
})
}
})
}
// No more work required
function stop() {
if (worker) {
log.info('Shutting down device worker "%s"', device.id)
worker.cancel()
}
}
// Spawn a device worker // Spawn a device worker
function spawn() { function spawn() {
var allocatedPorts = ports.splice(0, 4) var allocatedPorts = ports.splice(0, 4)
, proc = options.fork(device, allocatedPorts.slice()) var proc = options.fork(device, allocatedPorts.slice())
, resolver = Promise.defer() var resolver = Promise.defer()
function exitListener(code, signal) { function exitListener(code, signal) {
if (signal) { if (signal) {
@ -398,6 +260,144 @@ module.exports = function(options) {
}) })
} }
// Starts a device worker and keeps it alive
function work() {
return (worker = workers[device.id] = spawn())
.then(function() {
log.info('Device worker "%s" has retired', device.id)
delete workers[device.id]
worker = null
// Tell others the device is gone
push.send([
wireutil.global
, wireutil.envelope(new wire.DeviceAbsentMessage(
device.id
))
])
})
.catch(procutil.ExitError, function(err) {
if (!willStop) {
log.error(
'Device worker "%s" died with code %s'
, device.id
, err.code
)
log.info('Restarting device worker "%s"', device.id)
return Promise.delay(500)
.then(function() {
return work()
})
}
})
}
// No more work required
function stop() {
if (worker) {
log.info('Shutting down device worker "%s"', device.id)
worker.cancel()
}
}
// Check if we can do anything with the device
function check() {
clearTimeout(timer)
if (device.present) {
// We might get multiple status updates in rapid succession,
// so let's wait for a while
switch (device.type) {
case 'device':
case 'emulator':
willStop = false
timer = setTimeout(work, 100)
break
default:
willStop = true
timer = setTimeout(stop, 100)
break
}
}
else {
stop()
}
}
register.then(function() {
log.info('Registered device "%s"', device.id)
check()
})
// Statistics
lists.all.push(device.id)
delayedTotals()
// Will be set to false when the device is removed
_.assign(device, {
present: true
})
// When any event occurs on the added device
function deviceListener(type, updatedDevice) {
// Okay, this is a bit unnecessary but it allows us to get rid of an
// ugly switch statement and return to the original style.
privateTracker.emit(type, updatedDevice)
}
// When the added device changes
function changeListener(updatedDevice) {
register.then(function() {
log.info(
'Device "%s" is now "%s" (was "%s")'
, device.id
, updatedDevice.type
, device.type
)
_.assign(device, {
type: updatedDevice.type
})
// Tell others the device changed
push.send([
wireutil.global
, wireutil.envelope(new wire.DeviceStatusMessage(
device.id
, wireutil.toDeviceStatus(device.type)
))
])
check()
})
}
// When the added device gets removed
function removeListener() {
register.then(function() {
log.info('Lost device "%s" (%s)', device.id, device.type)
clearTimeout(timer)
flippedTracker.removeListener(device.id, deviceListener)
_.pull(lists.all, device.id)
delayedTotals()
// Tell others the device is gone
push.send([
wireutil.global
, wireutil.envelope(new wire.DeviceAbsentMessage(
device.id
))
])
_.assign(device, {
present: false
})
check()
})
}
flippedTracker.on(device.id, deviceListener) flippedTracker.on(device.id, deviceListener)
privateTracker.on('change', changeListener) privateTracker.on('change', changeListener)
privateTracker.on('remove', removeListener) privateTracker.on('remove', removeListener)

View file

@ -11,8 +11,8 @@ var manifest = require('./task/manifest')
module.exports = function(options) { module.exports = function(options) {
var log = logger.createLogger('storage:plugins:apk') var log = logger.createLogger('storage:plugins:apk')
, app = express() var app = express()
, server = http.createServer(app) var server = http.createServer(app)
app.set('strict routing', true) app.set('strict routing', true)
app.set('case sensitive routing', true) app.set('case sensitive routing', true)

View file

@ -13,8 +13,8 @@ var transform = require('./task/transform')
module.exports = function(options) { module.exports = function(options) {
var log = logger.createLogger('storage:plugins:image') var log = logger.createLogger('storage:plugins:image')
, app = express() var app = express()
, server = http.createServer(app) var server = http.createServer(app)
app.set('strict routing', true) app.set('strict routing', true)
app.set('case sensitive routing', true) app.set('case sensitive routing', true)

View file

@ -5,8 +5,8 @@ module.exports = function(raw) {
if (raw && (parsed = RE_CROP.exec(raw))) { if (raw && (parsed = RE_CROP.exec(raw))) {
return { return {
width: +parsed[1] || 0 width: Number(parsed[1]) || 0
, height: +parsed[2] || 0 , height: Number(parsed[2]) || 0
} }
} }

View file

@ -8,7 +8,7 @@ var request = require('request')
module.exports = function(path, options) { module.exports = function(path, options) {
return new Promise(function(resolve, reject) { return new Promise(function(resolve, reject) {
var res = request.get(url.resolve(options.storageUrl, path)) var res = request.get(url.resolve(options.storageUrl, path))
, ret = new stream.Readable().wrap(res) // Wrap old-style stream var ret = new stream.Readable().wrap(res) // Wrap old-style stream
res.on('response', function(res) { res.on('response', function(res) {
if (res.statusCode !== 200) { if (res.statusCode !== 200) {

View file

@ -15,8 +15,8 @@ var logger = require('../../util/logger')
module.exports = function(options) { module.exports = function(options) {
var log = logger.createLogger('storage:s3') var log = logger.createLogger('storage:s3')
, app = express() var app = express()
, server = http.createServer(app) var server = http.createServer(app)
var s3 = new AWS.S3({ var s3 = new AWS.S3({
credentials: new AWS.SharedIniFileCredentials({ credentials: new AWS.SharedIniFileCredentials({
@ -80,7 +80,7 @@ module.exports = function(options) {
var file = files[field] var file = files[field]
log.info('Uploaded "%s" to "%s"', file.name, file.path) log.info('Uploaded "%s" to "%s"', file.name, file.path)
return putObject(plugin, file) return putObject(plugin, file)
.then(function (id) { .then(function(id) {
return { return {
field: field field: field
, id: id , id: id
@ -151,5 +151,5 @@ module.exports = function(options) {
}) })
server.listen(options.port) server.listen(options.port)
console.log('Listening on port %d', options.port) log.info('Listening on port %d', options.port)
} }

View file

@ -15,9 +15,9 @@ var download = require('../../util/download')
module.exports = function(options) { module.exports = function(options) {
var log = logger.createLogger('storage:temp') var log = logger.createLogger('storage:temp')
, app = express() var app = express()
, server = http.createServer(app) var server = http.createServer(app)
, storage = new Storage() var storage = new Storage()
app.set('strict routing', true) app.set('strict routing', true)
app.set('case sensitive routing', true) app.set('case sensitive routing', true)
@ -59,9 +59,7 @@ module.exports = function(options) {
'/s/%s/%s%s' '/s/%s/%s%s'
, plugin , plugin
, file.id , file.id
, file.name , file.name ? util.format('/%s', path.basename(file.name)) : ''
? util.format('/%s', path.basename(file.name))
: ''
) )
} }
}) })
@ -115,9 +113,9 @@ module.exports = function(options) {
'/s/%s/%s%s' '/s/%s/%s%s'
, plugin , plugin
, file.id , file.id
, file.name , file.name ?
? util.format('/%s', path.basename(file.name)) util.format('/%s', path.basename(file.name)) :
: '' ''
) )
} }
}) })

View file

@ -25,12 +25,12 @@ var jwtutil = require('../../util/jwtutil')
module.exports = function(options) { module.exports = function(options) {
var log = logger.createLogger('websocket') var log = logger.createLogger('websocket')
, server = http.createServer() var server = http.createServer()
, io = socketio.listen(server, { var io = socketio.listen(server, {
serveClient: false serveClient: false
, transports: ['websocket'] , transports: ['websocket']
}) })
, channelRouter = new events.EventEmitter() var channelRouter = new events.EventEmitter()
// Output // Output
var push = zmqutil.socket('push') var push = zmqutil.socket('push')
@ -89,12 +89,14 @@ module.exports = function(options) {
io.on('connection', function(socket) { io.on('connection', function(socket) {
var req = socket.request var req = socket.request
, user = req.user var user = req.user
, channels = [] var channels = []
user.ip = socket.handshake.query.uip || req.ip user.ip = socket.handshake.query.uip || req.ip
socket.emit('socket.ip', user.ip) socket.emit('socket.ip', user.ip)
var messageListener = wirerouter()
function joinChannel(channel) { function joinChannel(channel) {
channels.push(channel) channels.push(channel)
channelRouter.on(channel, messageListener) channelRouter.on(channel, messageListener)
@ -118,7 +120,7 @@ module.exports = function(options) {
} }
} }
var messageListener = wirerouter() messageListener
.on(wire.DeviceLogMessage, function(channel, message) { .on(wire.DeviceLogMessage, function(channel, message) {
socket.emit('device.log', message) socket.emit('device.log', message)
}) })
@ -316,7 +318,7 @@ module.exports = function(options) {
return dbapi.loadDevice(data.serial) return dbapi.loadDevice(data.serial)
}) })
.then(function(device) { .then(function(device) {
if(device) { if (device) {
io.emit('device.change', { io.emit('device.change', {
important: true important: true
, data: { , data: {
@ -346,7 +348,7 @@ module.exports = function(options) {
}) })
var tokenId = util.format('%s-%s', uuid.v4(), uuid.v4()).replace(/-/g, '') var tokenId = util.format('%s-%s', uuid.v4(), uuid.v4()).replace(/-/g, '')
, title = data.title var title = data.title
return dbapi.saveUserAccessToken(user.email, { return dbapi.saveUserAccessToken(user.email, {
title: title title: title
@ -565,7 +567,7 @@ module.exports = function(options) {
) )
]) ])
}) })
.on('account.check', function(channel, responseChannel, data){ .on('account.check', function(channel, responseChannel, data) {
joinChannel(responseChannel) joinChannel(responseChannel)
push.send([ push.send([
channel channel
@ -890,7 +892,7 @@ module.exports = function(options) {
) )
]) ])
}) })
.on('fs.list', function(channel, responseChannel, data){ .on('fs.list', function(channel, responseChannel, data) {
joinChannel(responseChannel) joinChannel(responseChannel)
push.send([ push.send([
channel channel

View file

@ -2,7 +2,7 @@ var dbapi = require('../../../db/api')
module.exports = function(socket, next) { module.exports = function(socket, next) {
var req = socket.request var req = socket.request
, token = req.session.jwt var token = req.session.jwt
if (token) { if (token) {
return dbapi.loadUser(token.email) return dbapi.loadUser(token.email)
.then(function(user) { .then(function(user) {

View file

@ -4,7 +4,7 @@ module.exports = function(options) {
var session = cookieSession(options) var session = cookieSession(options)
return function(socket, next) { return function(socket, next) {
var req = socket.request var req = socket.request
, res = Object.create(null) var res = Object.create(null)
session(req, res, next) session(req, res, next)
} }
} }

View file

@ -4,13 +4,14 @@ module.exports.list = function(val) {
module.exports.size = function(val) { module.exports.size = function(val) {
var match = /^(\d+)x(\d+)$/.exec(val) var match = /^(\d+)x(\d+)$/.exec(val)
return match ? [+match[1], +match[2]] : undefined if (match) {
return [Number(match[1]), Number(match[2])]
}
} }
module.exports.range = function(from, to) { module.exports.range = function(from, to) {
var items = [] var items = []
, i for (var i = from; i <= to; ++i) {
for (i = from; i <= to; ++i) {
items.push(i) items.push(i)
} }
return items return items

View file

@ -70,7 +70,7 @@ devutil.listPidsByComm = function(adb, serial, comm, bin) {
.then(function(out) { .then(function(out) {
return new Promise(function(resolve) { return new Promise(function(resolve) {
var header = false var header = false
, pids = [] var pids = []
out.pipe(split()) out.pipe(split())
.on('data', function(chunk) { .on('data', function(chunk) {
if (header) { if (header) {
@ -79,7 +79,7 @@ devutil.listPidsByComm = function(adb, serial, comm, bin) {
else { else {
var cols = chunk.toString().split(/\s+/) var cols = chunk.toString().split(/\s+/)
if (cols.pop() === bin && users[cols[0]]) { if (cols.pop() === bin && users[cols[0]]) {
pids.push(+cols[1]) pids.push(Number(cols[1]))
} }
} }
}) })
@ -126,14 +126,14 @@ devutil.killProcsByComm = function(adb, serial, comm, bin, mode) {
devutil.makeIdentity = function(serial, properties) { devutil.makeIdentity = function(serial, properties) {
var model = properties['ro.product.model'] var model = properties['ro.product.model']
, brand = properties['ro.product.brand'] var brand = properties['ro.product.brand']
, manufacturer = properties['ro.product.manufacturer'] var manufacturer = properties['ro.product.manufacturer']
, operator = properties['gsm.sim.operator.alpha'] || var operator = properties['gsm.sim.operator.alpha'] ||
properties['gsm.operator.alpha'] properties['gsm.operator.alpha']
, version = properties['ro.build.version.release'] var version = properties['ro.build.version.release']
, sdk = properties['ro.build.version.sdk'] var sdk = properties['ro.build.version.sdk']
, abi = properties['ro.product.cpu.abi'] var abi = properties['ro.product.cpu.abi']
, product = properties['ro.product.name'] var product = properties['ro.product.name']
// Remove brand prefix for consistency // Remove brand prefix for consistency
if (model.substr(0, brand.length) === brand) { if (model.substr(0, brand.length) === brand) {

View file

@ -29,7 +29,7 @@ module.exports.decode = function(payload, secret) {
var decoded = jws.decode(payload, { var decoded = jws.decode(payload, {
json: true json: true
}) })
, exp = decoded.header.exp var exp = decoded.header.exp
if (exp && exp <= Date.now()) { if (exp && exp <= Date.now()) {
return null return null

View file

@ -7,15 +7,12 @@ var keyutil = module.exports = Object.create(null)
keyutil.parseKeyCharacterMap = function(stream) { keyutil.parseKeyCharacterMap = function(stream) {
var resolver = Promise.defer() var resolver = Promise.defer()
, state = 'type_t' var state = 'type_t'
, keymap = { var keymap = {
type: null type: null
, keys: [] , keys: []
} }
, lastKey var lastKey, lastRule, lastModifier, lastBehavior
, lastRule
, lastModifier
, lastBehavior
function fail(char, state) { function fail(char, state) {
throw new Error(util.format( throw new Error(util.format(
@ -431,8 +428,8 @@ keyutil.parseKeyCharacterMap = function(stream) {
function readableListener() { function readableListener() {
var chunk = stream.read() var chunk = stream.read()
, i = 0 var i = 0
, l = chunk.length var l = chunk.length
try { try {
while (i < l) { while (i < l) {
@ -461,7 +458,7 @@ keyutil.parseKeyCharacterMap = function(stream) {
keyutil.namedKey = function(name) { keyutil.namedKey = function(name) {
var key = adb.Keycode['KEYCODE_' + name.toUpperCase()] var key = adb.Keycode['KEYCODE_' + name.toUpperCase()]
if (key === void 0) { if (typeof key === 'undefined') {
throw new Error(util.format('Unknown key "%s"', name)) throw new Error(util.format('Unknown key "%s"', name))
} }
return key return key

View file

@ -19,7 +19,7 @@ module.exports.InvalidCredentialsError = InvalidCredentialsError
module.exports.login = function(options, username, password) { module.exports.login = function(options, username, password) {
function tryConnect() { function tryConnect() {
var resolver = Promise.defer() var resolver = Promise.defer()
, client = ldap.createClient({ var client = ldap.createClient({
url: options.url url: options.url
, timeout: options.timeout , timeout: options.timeout
, maxConnections: 1 , maxConnections: 1
@ -44,7 +44,7 @@ module.exports.login = function(options, username, password) {
function tryFind(client) { function tryFind(client) {
var resolver = Promise.defer() var resolver = Promise.defer()
, query = { var query = {
scope: options.search.scope scope: options.search.scope
, filter: new ldap.AndFilter({ , filter: new ldap.AndFilter({
filters: [ filters: [

View file

@ -28,15 +28,6 @@ Logger.LevelLabel = {
Logger.globalIdentifier = '*' Logger.globalIdentifier = '*'
Logger.createLogger = function(tag) {
return new Log(tag)
}
Logger.setGlobalIdentifier = function(identifier) {
Logger.globalIdentifier = identifier
return Logger
}
function Log(tag) { function Log(tag) {
this.tag = tag this.tag = tag
this.names = { this.names = {
@ -63,6 +54,15 @@ function Log(tag) {
util.inherits(Log, events.EventEmitter) util.inherits(Log, events.EventEmitter)
Logger.createLogger = function(tag) {
return new Log(tag)
}
Logger.setGlobalIdentifier = function(identifier) {
Logger.globalIdentifier = identifier
return Logger
}
Log.Entry = function(timestamp, priority, tag, pid, identifier, message) { Log.Entry = function(timestamp, priority, tag, pid, identifier, message) {
this.timestamp = timestamp this.timestamp = timestamp
this.priority = priority this.priority = priority
@ -129,6 +129,7 @@ Log.prototype._name = function(priority) {
return chalk[this.styles[priority]](this.names[priority]) return chalk[this.styles[priority]](this.names[priority])
} }
/* eslint no-console: 0 */
Log.prototype._write = function(entry) { Log.prototype._write = function(entry) {
console.error(this._format(entry)) console.error(this._format(entry))
this.emit('entry', entry) this.emit('entry', entry)

View file

@ -2,12 +2,13 @@ var Promise = require('bluebird')
module.exports.periodicNotify = function(promise, interval) { module.exports.periodicNotify = function(promise, interval) {
var resolver = Promise.defer() var resolver = Promise.defer()
, timer = setInterval(notify, interval)
function notify() { function notify() {
resolver.progress() resolver.progress()
} }
var timer = setInterval(notify, interval)
function resolve(value) { function resolve(value) {
resolver.resolve(value) resolver.resolve(value)
} }

View file

@ -31,11 +31,7 @@ module.exports.limit = function(limit, handler) {
var queue = [] var queue = []
var running = 0 var running = 0
function done() { /* eslint no-use-before-define: 0 */
running -= 1
maybeNext()
}
function maybeNext() { function maybeNext() {
while (running < limit && queue.length) { while (running < limit && queue.length) {
running += 1 running += 1
@ -43,6 +39,11 @@ module.exports.limit = function(limit, handler) {
} }
} }
function done() {
running -= 1
maybeNext()
}
return function() { return function() {
queue.push(arguments) queue.push(arguments)
maybeNext() maybeNext()

View file

@ -37,11 +37,11 @@ RiskyStream.prototype.expectEnd = function() {
RiskyStream.prototype.waitForEnd = function() { RiskyStream.prototype.waitForEnd = function() {
var stream = this.stream var stream = this.stream
, endListener var endListener
this.expectEnd() this.expectEnd()
return new Promise(function(resolve/*, reject*/) { return new Promise(function(resolve) {
if (stream.ended) { if (stream.ended) {
return resolve(true) return resolve(true)
} }

View file

@ -41,7 +41,7 @@ function shuffleWeighted(records) {
function pick(records, sum) { function pick(records, sum) {
var rand = Math.random() * sum var rand = Math.random() * sum
, counter = 0 var counter = 0
for (var i = 0, l = records.length; i < l; ++i) { for (var i = 0, l = records.length; i < l; ++i) {
counter += records[i].weight counter += records[i].weight
@ -117,7 +117,7 @@ srv.attempt = function(records, fn) {
} }
return fn(records[i]).catch(srv.NEXT, function() { return fn(records[i]).catch(srv.NEXT, function() {
return next(++i) return next(i + 1)
}) })
} }

View file

@ -50,7 +50,7 @@ Storage.prototype.check = function() {
Object.keys(this.files).forEach(function(id) { Object.keys(this.files).forEach(function(id) {
var file = this.files[id] var file = this.files[id]
, inactivePeriod = now - file.lastActivity var inactivePeriod = now - file.lastActivity
if (inactivePeriod >= file.timeout) { if (inactivePeriod >= file.timeout) {
this.remove(id) this.remove(id)

View file

@ -15,7 +15,7 @@ module.exports.NoSuchLineError = NoSuchLineError
module.exports.readAll = function(stream) { module.exports.readAll = function(stream) {
var resolver = Promise.defer() var resolver = Promise.defer()
, collected = new Buffer(0) var collected = new Buffer(0)
function errorListener(err) { function errorListener(err) {
resolver.reject(err) resolver.reject(err)
@ -45,7 +45,7 @@ module.exports.readAll = function(stream) {
module.exports.findLine = function(stream, re) { module.exports.findLine = function(stream, re) {
var resolver = Promise.defer() var resolver = Promise.defer()
, piped = stream.pipe(split()) var piped = stream.pipe(split())
function errorListener(err) { function errorListener(err) {
resolver.reject(err) resolver.reject(err)

View file

@ -3,9 +3,12 @@ var url = require('url')
module.exports.addParams = function(originalUrl, params) { module.exports.addParams = function(originalUrl, params) {
var parsed = url.parse(originalUrl, true) var parsed = url.parse(originalUrl, true)
parsed.search = null parsed.search = null
// TODO: change to ES6 loop
for (var key in params) { for (var key in params) {
if (params.dict.hasOwnProperty(key)) {
parsed.query[key] = params[key] parsed.query[key] = params[key]
} }
}
return url.format(parsed) return url.format(parsed)
} }

View file

@ -28,7 +28,7 @@ function normalizePassword(password) {
function encrypt(challenge, password) { function encrypt(challenge, password) {
var key = normalizePassword(password) var key = normalizePassword(password)
, iv = new Buffer(0).fill(0) var iv = new Buffer(0).fill(0)
// Note: do not call .final(), .update() is the one that gives us the // Note: do not call .final(), .update() is the one that gives us the
// desired result. // desired result.

View file

@ -14,7 +14,7 @@ module.exports.socket = function() {
;['ZMQ_TCP_KEEPALIVE', 'ZMQ_TCP_KEEPALIVE_IDLE'].forEach(function(opt) { ;['ZMQ_TCP_KEEPALIVE', 'ZMQ_TCP_KEEPALIVE_IDLE'].forEach(function(opt) {
if (process.env[opt]) { if (process.env[opt]) {
try { try {
sock.setsockopt(zmq[opt], +process.env[opt]) sock.setsockopt(zmq[opt], Number(process.env[opt]))
} }
catch (err) { catch (err) {
log.warn('ZeroMQ library too old, no support for %s', opt) log.warn('ZeroMQ library too old, no support for %s', opt)

View file

@ -53,7 +53,7 @@ ChannelManager.prototype.keepalive = function(id) {
ChannelManager.prototype.check = function(id) { ChannelManager.prototype.check = function(id) {
var channel = this.channels[id] var channel = this.channels[id]
, inactivePeriod = Date.now() - channel.lastActivity var inactivePeriod = Date.now() - channel.lastActivity
if (inactivePeriod >= channel.timeout) { if (inactivePeriod >= channel.timeout) {
this.unregister(id) this.unregister(id)

View file

@ -30,7 +30,7 @@ Router.prototype.removeListener = function(message, handler) {
Router.prototype.handler = function() { Router.prototype.handler = function() {
return function(channel, data) { return function(channel, data) {
var wrapper = wire.Envelope.decode(data) var wrapper = wire.Envelope.decode(data)
, type = wire.ReverseMessageType[wrapper.type] var type = wire.ReverseMessageType[wrapper.type]
if (type) { if (type) {
this.emit( this.emit(

View file

@ -44,7 +44,7 @@ SeqQueue.prototype.maybeConsume = function() {
var handler = this.list[this.lo] var handler = this.list[this.lo]
// Have we received it yet? // Have we received it yet?
if (handler) { if (handler) {
this.list[this.lo] = void 0 this.list[this.lo] = undefined
handler() handler()
this.lo += 1 this.lo += 1
this.waiting -= 1 this.waiting -= 1