diff --git a/.eslintrc b/.eslintrc
index 58edaf12..488864b8 100644
--- a/.eslintrc
+++ b/.eslintrc
@@ -48,7 +48,7 @@
"no-new-wrappers": 2,
"no-new": 2,
"no-octal-escape": 2,
- "no-octal": 2,
+ "no-octal": 1, // TODO: accept until we use ES6 0o755 notation
"no-param-reassign": 2,
"no-process-env": 0, // `2` is recommended
"no-proto": 2,
@@ -62,7 +62,7 @@
"no-useless-call": 2, // `2` is recommended
"no-useless-concat": 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,
"radix": 1, // `2` is recommended
"vars-on-top": 0, // `2` is recommended TODO: review this
@@ -78,7 +78,7 @@
"no-label-var": 2,
"no-shadow-restricted-names": 2,
"no-shadow": 0, // TODO: 1 may be ok
- "no-undefined": 2,
+ "no-undefined": 1,
"no-unused-vars": 1,
"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}]`
"block-spacing": [2, "always"], // optionally set `[2, "always"]`
"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-style": [1, "first"], // optionally set `[2, "first", {"exceptions": {"ArrayExpression": true, "ObjectExpression": true}}]`
"computed-property-spacing": [2, "never"],
diff --git a/lib/cli.js b/lib/cli.js
index 30a61b94..bdb0bb18 100644
--- a/lib/cli.js
+++ b/lib/cli.js
@@ -903,7 +903,7 @@ program
.description('migrates the database to the latest version')
.action(function() {
var log = logger.createLogger('cli:migrate')
- , db = require('./db')
+ var db = require('./db')
db.setup()
.then(function() {
@@ -924,21 +924,21 @@ program
, 1)
.action(function(model, options) {
var log = logger.createLogger('cli:generate-fake-device')
- , fake = require('./util/fakedevice')
- , n = options.number
+ var fake = require('./util/fakedevice')
+ var n = options.number
- function next() {
+ function nextDevice() {
return fake.generate(model)
.then(function(serial) {
log.info('Created fake device "%s"', serial)
if (--n) {
- return next()
+ return nextDevice()
}
})
}
- next()
+ nextDevice()
.then(function() {
process.exit(0)
})
@@ -1069,7 +1069,7 @@ program
, 'whether to lock rotation when devices are being used')
.action(function(serials, options) {
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
// 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/'
, options.publicIp
, options.poorxyPort
- , ({oauth2: 'oauth', saml2: 'saml'}[options.authType]) || options.authType
+ , {
+ oauth2: 'oauth'
+ , saml2: 'saml'
+ }[options.authType] || options.authType
)
, '--websocket-url', util.format(
'http://%s:%d/'
diff --git a/lib/db/api.js b/lib/db/api.js
index 1979d05a..59c801f0 100644
--- a/lib/db/api.js
+++ b/lib/db/api.js
@@ -320,7 +320,7 @@ dbapi.saveUserAccessToken = function(email, token) {
dbapi.removeUserAccessToken = function(email, title) {
return db.run(r.table('accessTokens').getAll(email, {
index: 'email'
- }).filter({'title': title}).delete())
+ }).filter({title: title}).delete())
}
dbapi.loadAccessTokens = function(email) {
diff --git a/lib/db/index.js b/lib/db/index.js
index 7e1214ae..a8986e8a 100644
--- a/lib/db/index.js
+++ b/lib/db/index.js
@@ -48,7 +48,7 @@ function connect() {
// Export connection as a Promise
db.connect = (function() {
var connection
- , queue = []
+ var queue = []
lifecycle.observe(function() {
if (connection) {
diff --git a/lib/db/setup.js b/lib/db/setup.js
index ff9c885c..aee1c7db 100644
--- a/lib/db/setup.js
+++ b/lib/db/setup.js
@@ -28,7 +28,7 @@ module.exports = function(conn) {
function createIndex(table, index, options) {
var args = [index]
- , rTable = r.table(table)
+ var rTable = r.table(table)
if (options) {
if (options.indexFunction) {
diff --git a/lib/units/app/index.js b/lib/units/app/index.js
index 13d10071..e355bd90 100644
--- a/lib/units/app/index.js
+++ b/lib/units/app/index.js
@@ -26,8 +26,8 @@ var markdownServe = require('markdown-serve')
module.exports = function(options) {
var log = logger.createLogger('app')
- , app = express()
- , server = http.createServer(app)
+ var app = express()
+ var server = http.createServer(app)
app.use('/static/wiki', markdownServe.middleware({
rootDirectory: pathutil.root('node_modules/stf-wiki')
@@ -50,9 +50,9 @@ module.exports = function(options) {
}))
}
else {
+ log.info('Using webpack')
// Keep webpack-related requires here, as our prebuilt package won't
// have them at all.
- log.info('Using webpack')
var webpackServerConfig = require('./../../../webpack.config').webpackServer
app.use('/static/app/build',
require('./middleware/webpack')(webpackServerConfig))
@@ -115,7 +115,7 @@ module.exports = function(options) {
}
if (options.userProfileUrl) {
- state.config.userProfileUrl = (function () {
+ state.config.userProfileUrl = (function() {
return options.userProfileUrl
})()
}
diff --git a/lib/units/app/middleware/auth.js b/lib/units/app/middleware/auth.js
index 92984c5c..e960f4f3 100644
--- a/lib/units/app/middleware/auth.js
+++ b/lib/units/app/middleware/auth.js
@@ -8,7 +8,7 @@ module.exports = function(options) {
if (req.query.jwt) {
// Coming from auth client
var data = jwtutil.decode(req.query.jwt, options.secret)
- , redir = urlutil.removeParam(req.url, 'jwt')
+ var redir = urlutil.removeParam(req.url, 'jwt')
if (data) {
// Redirect once to get rid of the token
dbapi.saveUserAfterLogin({
diff --git a/lib/units/app/middleware/webpack.js b/lib/units/app/middleware/webpack.js
index f3ccce45..e8d4a682 100644
--- a/lib/units/app/middleware/webpack.js
+++ b/lib/units/app/middleware/webpack.js
@@ -14,9 +14,9 @@ var globalOptions = require('../../../../webpack.config').webpack
// Similar to webpack-dev-middleware, but integrates with our custom
// lifecycle, behaves more like normal express middleware, and removes
// all unnecessary features.
-module.exports = function(options) {
+module.exports = function(localOptions) {
var log = logger.createLogger('middleware:webpack')
- options = _.defaults(options || {}, globalOptions)
+ var options = _.defaults(localOptions || {}, globalOptions)
var compiler = webpack(options)
var fs = compiler.outputFileSystem = new MemoryFileSystem()
@@ -77,12 +77,11 @@ module.exports = function(options) {
if (valid) {
return Promise.resolve()
}
- else {
- log.info('Waiting for bundle to finish')
- var resolver = Promise.defer()
- queue.push(resolver)
- return resolver.promise
- }
+
+ log.info('Waiting for bundle to finish')
+ var resolver = Promise.defer()
+ queue.push(resolver)
+ return resolver.promise
}
return function(req, res, next) {
diff --git a/lib/units/auth/ldap.js b/lib/units/auth/ldap.js
index bbe3a079..3d36f4a3 100644
--- a/lib/units/auth/ldap.js
+++ b/lib/units/auth/ldap.js
@@ -18,8 +18,8 @@ var lifecycle = require('../../util/lifecycle')
module.exports = function(options) {
var log = logger.createLogger('auth-ldap')
- , app = express()
- , server = Promise.promisifyAll(http.createServer(app))
+ var app = express()
+ var server = Promise.promisifyAll(http.createServer(app))
lifecycle.observe(function() {
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(function(req, res, next) {
- res.cookie('XSRF-TOKEN', req.csrfToken());
+ res.cookie('XSRF-TOKEN', req.csrfToken())
next()
})
diff --git a/lib/units/auth/mock.js b/lib/units/auth/mock.js
index d0025ec4..6ec72a4c 100644
--- a/lib/units/auth/mock.js
+++ b/lib/units/auth/mock.js
@@ -17,8 +17,8 @@ var lifecycle = require('../../util/lifecycle')
module.exports = function(options) {
var log = logger.createLogger('auth-mock')
- , app = express()
- , server = Promise.promisifyAll(http.createServer(app))
+ var app = express()
+ var server = Promise.promisifyAll(http.createServer(app))
lifecycle.observe(function() {
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(function(req, res, next) {
- res.cookie('XSRF-TOKEN', req.csrfToken());
+ res.cookie('XSRF-TOKEN', req.csrfToken())
next()
})
diff --git a/lib/units/auth/oauth2/index.js b/lib/units/auth/oauth2/index.js
index 6931bdfc..f8cd83c7 100644
--- a/lib/units/auth/oauth2/index.js
+++ b/lib/units/auth/oauth2/index.js
@@ -10,8 +10,8 @@ var Strategy = require('./strategy')
module.exports = function(options) {
var log = logger.createLogger('auth-oauth2')
- , app = express()
- , server = http.createServer(app)
+ var app = express()
+ var server = http.createServer(app)
app.set('strict routing', true)
app.set('case sensitive routing', true)
diff --git a/lib/units/auth/oauth2/strategy.js b/lib/units/auth/oauth2/strategy.js
index 9f36041f..76a6f95a 100644
--- a/lib/units/auth/oauth2/strategy.js
+++ b/lib/units/auth/oauth2/strategy.js
@@ -18,13 +18,12 @@ Strategy.prototype.userProfile = function(accessToken, callback) {
if (err) {
return callback(err)
}
- else {
- try {
- return callback(null, JSON.parse(data))
- }
- catch (err) {
- return callback(err)
- }
+
+ try {
+ return callback(null, JSON.parse(data))
+ }
+ catch (err) {
+ return callback(err)
}
})
}
diff --git a/lib/units/auth/saml2.js b/lib/units/auth/saml2.js
index a27144c6..f3c273f2 100644
--- a/lib/units/auth/saml2.js
+++ b/lib/units/auth/saml2.js
@@ -13,20 +13,20 @@ var jwtutil = require('../../util/jwtutil')
module.exports = function(options) {
var log = logger.createLogger('auth-saml2')
- , app = express()
- , server = http.createServer(app)
+ var app = express()
+ var server = http.createServer(app)
app.set('strict routing', true)
app.set('case sensitive routing', true)
- app.use(bodyParser.urlencoded({ extended: false }))
+ app.use(bodyParser.urlencoded({extended: false}))
app.use(passport.initialize())
passport.serializeUser(function(user, done) {
- done(null, user);
- });
+ done(null, user)
+ })
passport.deserializeUser(function(user, done) {
- done(null, user);
- });
+ done(null, user)
+ })
var verify = function(profile, done) {
return done(null, profile)
diff --git a/lib/units/device/plugins/account.js b/lib/units/device/plugins/account.js
index 4faab5fc..025ad74e 100644
--- a/lib/units/device/plugins/account.js
+++ b/lib/units/device/plugins/account.js
@@ -18,7 +18,7 @@ module.exports = syrup.serial()
return service.getAccounts({type: type})
.timeout(30000)
.then(function(accounts) {
- if(accounts.indexOf(account) >= 0) {
+ if (accounts.indexOf(account) >= 0) {
return true
}
throw new Error('The account is not added')
@@ -28,7 +28,7 @@ module.exports = syrup.serial()
router.on(wire.AccountCheckMessage, function(channel, message) {
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)
.then(function() {
push.send([
@@ -55,7 +55,7 @@ module.exports = syrup.serial()
.then(function(accounts) {
push.send([
channel
- , reply.okay('success',accounts)
+ , reply.okay('success', accounts)
])
})
.catch(function(err) {
@@ -113,12 +113,12 @@ module.exports = syrup.serial()
router.on(wire.AccountAddMessage, function(channel, message) {
var reply = wireutil.reply(options.serial)
- var type = "com.google"
- var account = message.user + "@gmail.com";
+ var type = 'com.google'
+ var account = message.user + '@gmail.com'
log.info('Adding Google Account automatedly')
- var version = identity.version.substring(0,3)
+ var version = identity.version.substring(0, 3)
function automation() {
switch (version) {
@@ -235,8 +235,8 @@ module.exports = syrup.serial()
.then(function() {
return service.pressKey('enter')
})
- //case '4.3': // tested: 4.3
- //case '4.4': // tested: 4.4.2
+ // case '4.3': // tested: 4.3
+ // case '4.4': // tested: 4.4.2
default:
return service.pressKey('tab').delay(1000)
.then(function() {
@@ -293,17 +293,17 @@ module.exports = syrup.serial()
.delay(5000)
.then(function() {
// 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)
.then(function() {
return automation()
})
.delay(3000)
- .then(function () {
+ .then(function() {
return service.pressKey('home')
})
- .then(function () {
+ .then(function() {
return checkAccount(type, account)
})
.then(function() {
diff --git a/lib/units/device/plugins/browser.js b/lib/units/device/plugins/browser.js
index f21197f5..afb397e2 100644
--- a/lib/units/device/plugins/browser.js
+++ b/lib/units/device/plugins/browser.js
@@ -51,8 +51,17 @@ module.exports = syrup.serial()
function compareIgnoreCase(a, b) {
var la = (a || '').toLowerCase()
- , lb = (b || '').toLowerCase()
- return la === lb ? 0 : (la < lb ? -1 : 1)
+ var lb = (b || '').toLowerCase()
+
+ if (la === lb) {
+ return 0
+ }
+ else if (la < lb) {
+ return -1
+ }
+ else {
+ return 1
+ }
}
function updateBrowsers(data) {
diff --git a/lib/units/device/plugins/cleanup.js b/lib/units/device/plugins/cleanup.js
index 5f5021e6..00b4a33a 100644
--- a/lib/units/device/plugins/cleanup.js
+++ b/lib/units/device/plugins/cleanup.js
@@ -40,7 +40,6 @@ module.exports = syrup.serial()
group.on('leave', function() {
plugin.removePackages()
})
-
})
.return(plugin)
})
diff --git a/lib/units/device/plugins/connect.js b/lib/units/device/plugins/connect.js
index 7dd06965..d058b176 100644
--- a/lib/units/device/plugins/connect.js
+++ b/lib/units/device/plugins/connect.js
@@ -18,8 +18,8 @@ module.exports = syrup.serial()
.dependency(require('./util/urlformat'))
.define(function(options, adb, router, push, group, solo, urlformat) {
var log = logger.createLogger('device:plugins:connect')
- , plugin = Object.create(null)
- , activeServer = null
+ var plugin = Object.create(null)
+ var activeServer = null
plugin.port = options.connectPort
plugin.url = urlformat(options.connectUrlPattern, plugin.port)
diff --git a/lib/units/device/plugins/forward/index.js b/lib/units/device/plugins/forward/index.js
index 1c8a1307..4b481656 100644
--- a/lib/units/device/plugins/forward/index.js
+++ b/lib/units/device/plugins/forward/index.js
@@ -44,7 +44,7 @@ module.exports = syrup.serial()
if (/closed/.test(err.message) && times > 1) {
return Promise.delay(delay)
.then(function() {
- return tryConnect(--times, delay * 2)
+ return tryConnect(times - 1, delay * 2)
})
}
return Promise.reject(err)
diff --git a/lib/units/device/plugins/forward/util/manager.js b/lib/units/device/plugins/forward/util/manager.js
index b38af51b..dea09e81 100644
--- a/lib/units/device/plugins/forward/util/manager.js
+++ b/lib/units/device/plugins/forward/util/manager.js
@@ -5,6 +5,115 @@ var net = require('net')
var ForwardReader = require('./reader')
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
function ForwardManager() {
var handlersById = Object.create(null)
@@ -61,113 +170,4 @@ function ForwardManager() {
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
diff --git a/lib/units/device/plugins/forward/util/writer.js b/lib/units/device/plugins/forward/util/writer.js
index b6a01c7d..02e740c3 100644
--- a/lib/units/device/plugins/forward/util/writer.js
+++ b/lib/units/device/plugins/forward/util/writer.js
@@ -11,9 +11,9 @@ function ForwardWriter(target) {
util.inherits(ForwardWriter, stream.Transform)
-ForwardWriter.prototype._transform = function(chunk, encoding, done) {
- var header
- , length
+ForwardWriter.prototype._transform = function(fullChunk, encoding, done) {
+ var chunk = fullChunk
+ var header, length
do {
length = Math.min(MAX_PACKET_SIZE, chunk.length)
diff --git a/lib/units/device/plugins/group.js b/lib/units/device/plugins/group.js
index c69b0e78..50e62b31 100644
--- a/lib/units/device/plugins/group.js
+++ b/lib/units/device/plugins/group.js
@@ -19,8 +19,8 @@ module.exports = syrup.serial()
.dependency(require('../support/channels'))
.define(function(options, solo, ident, service, router, push, sub, channels) {
var log = logger.createLogger('device:plugins:group')
- , currentGroup = null
- , plugin = new events.EventEmitter()
+ var currentGroup = null
+ var plugin = new events.EventEmitter()
plugin.get = Promise.method(function() {
if (!currentGroup) {
diff --git a/lib/units/device/plugins/install.js b/lib/units/device/plugins/install.js
index fd0ab9af..894fbe2f 100644
--- a/lib/units/device/plugins/install.js
+++ b/lib/units/device/plugins/install.js
@@ -27,7 +27,7 @@ module.exports = syrup.serial()
router.on(wire.InstallMessage, function(channel, message) {
var manifest = JSON.parse(message.manifest)
- , pkg = manifest.package
+ var pkg = manifest.package
log.info('Installing package "%s" from "%s"', pkg, message.href)
@@ -98,8 +98,8 @@ module.exports = syrup.serial()
pushApp()
.then(function(apk) {
var start = 50
- , end = 90
- , guesstimate = start
+ var end = 90
+ var guesstimate = start
sendProgress('installing_app', guesstimate)
return promiseutil.periodicNotify(
diff --git a/lib/units/device/plugins/logcat.js b/lib/units/device/plugins/logcat.js
index 76a49b87..c63f2083 100644
--- a/lib/units/device/plugins/logcat.js
+++ b/lib/units/device/plugins/logcat.js
@@ -13,8 +13,8 @@ module.exports = syrup.serial()
.dependency(require('./group'))
.define(function(options, adb, router, push, group) {
var log = logger.createLogger('device:plugins:logcat')
- , plugin = Object.create(null)
- , activeLogcat = null
+ var plugin = Object.create(null)
+ var activeLogcat = null
plugin.start = function(filters) {
return group.get()
diff --git a/lib/units/device/plugins/mute.js b/lib/units/device/plugins/mute.js
index fd23c75b..6ff54675 100644
--- a/lib/units/device/plugins/mute.js
+++ b/lib/units/device/plugins/mute.js
@@ -13,12 +13,12 @@ module.exports = syrup.serial()
log.info('Will mute master volume during use')
group.on('join', function() {
- log.info('Muting master volume');
+ log.info('Muting master volume')
service.setMasterMute(true)
})
group.on('leave', function() {
- log.info('Unmuting master volume');
+ log.info('Unmuting master volume')
service.setMasterMute(false)
})
}
diff --git a/lib/units/device/plugins/screen/stream.js b/lib/units/device/plugins/screen/stream.js
index f8a6f25d..9d2c7383 100644
--- a/lib/units/device/plugins/screen/stream.js
+++ b/lib/units/device/plugins/screen/stream.js
@@ -176,11 +176,13 @@ module.exports = syrup.serial()
}
FrameProducer.prototype.nextFrame = function() {
- var frame = null, chunk
+ var frame = null
+ var chunk
if (this.parser) {
while ((frame = this.parser.nextFrame()) === null) {
- if ((chunk = this.socket.stream.read())) {
+ chunk = this.socket.stream.read()
+ if (chunk) {
this.parser.push(chunk)
}
else {
@@ -243,9 +245,9 @@ module.exports = syrup.serial()
return lifecycle.fatal()
}
- var match
- if ((match = /^PID: (\d+)$/.exec(line))) {
- this.pid = +match[1]
+ var match = /^PID: (\d+)$/.exec(line)
+ if (match) {
+ this.pid = Number(match[1])
this.emit('pid', this.pid)
}
@@ -259,7 +261,7 @@ module.exports = syrup.serial()
}
var pidListener
- return new Promise(function(resolve/*, reject*/) {
+ return new Promise(function(resolve) {
this.on('pid', pidListener = resolve)
}.bind(this)).bind(this)
.timeout(2000)
@@ -279,7 +281,7 @@ module.exports = syrup.serial()
if (/closed/.test(err.message) && times > 1) {
return Promise.delay(delay)
.then(function() {
- return tryConnect(--times, delay * 2)
+ return tryConnect(times - 1, delay * 2)
})
}
return Promise.reject(err)
@@ -326,7 +328,7 @@ module.exports = syrup.serial()
socket.stream.removeListener('readable', this.readableListener)
var endListener
- return new Promise(function(resolve/*, reject*/) {
+ return new Promise(function(resolve) {
socket.on('end', endListener = function() {
resolve(true)
})
@@ -354,8 +356,8 @@ module.exports = syrup.serial()
}
var signum = {
- 'SIGTERM': -15
- , 'SIGKILL': -9
+ SIGTERM: -15
+ , SIGKILL: -9
}[signal]
log.info('Sending %s to minicap', signal)
@@ -478,8 +480,8 @@ module.exports = syrup.serial()
})
frameProducer.on('readable', function next() {
- var frame
- if ((frame = frameProducer.nextFrame())) {
+ var frame = frameProducer.nextFrame()
+ if (frame) {
Promise.settle([broadcastSet.keys().map(function(id) {
return broadcastSet.get(id).onFrame(frame)
})]).then(next)
@@ -557,8 +559,8 @@ module.exports = syrup.serial()
}
ws.on('message', function(data) {
- var match
- if ((match = /^(on|off|(size) ([0-9]+)x([0-9]+))$/.exec(data))) {
+ var match = /^(on|off|(size) ([0-9]+)x([0-9]+))$/.exec(data)
+ if (match) {
switch (match[2] || match[1]) {
case 'on':
broadcastSet.insert(id, {
@@ -570,7 +572,8 @@ module.exports = syrup.serial()
broadcastSet.remove(id)
break
case 'size':
- frameProducer.updateProjection(+match[3], +match[4])
+ frameProducer.updateProjection(
+ Number(match[3]), Number(match[4]))
break
}
}
diff --git a/lib/units/device/plugins/screen/util/frameparser.js b/lib/units/device/plugins/screen/util/frameparser.js
index 585a7554..3f0de8ca 100644
--- a/lib/units/device/plugins/screen/util/frameparser.js
+++ b/lib/units/device/plugins/screen/util/frameparser.js
@@ -30,12 +30,17 @@ FrameParser.prototype.nextFrame = function() {
var bytesLeft = len - this.cursor
if (bytesLeft >= this.frameBodyLength) {
- var completeBody = this.frameBody
- ? Buffer.concat([
- this.frameBody
+ var completeBody
+ if (this.frameBody) {
+ completeBody = Buffer.concat([
+ this.frameBody
, 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.frameBodyLength = this.readFrameBytes = 0
@@ -46,9 +51,13 @@ FrameParser.prototype.nextFrame = function() {
else {
// @todo Consider/benchmark continuation frames to prevent
// potential Buffer thrashing.
- this.frameBody = this.frameBody
- ? Buffer.concat([this.frameBody, this.chunk.slice(this.cursor, len)])
- : this.chunk.slice(this.cursor, len)
+ if (this.frameBody) {
+ this.frameBody =
+ Buffer.concat([this.frameBody, this.chunk.slice(this.cursor, len)])
+ }
+ else {
+ this.frameBody = this.chunk.slice(this.cursor, len)
+ }
this.frameBodyLength -= bytesLeft
this.readFrameBytes += bytesLeft
diff --git a/lib/units/device/plugins/service.js b/lib/units/device/plugins/service.js
index 91b3a32a..dee0df23 100644
--- a/lib/units/device/plugins/service.js
+++ b/lib/units/device/plugins/service.js
@@ -52,6 +52,219 @@ module.exports = syrup.serial()
, port: 1100
}
+ function stopAgent() {
+ return devutil.killProcsByComm(
+ adb
+ , options.serial
+ , 'stf.agent'
+ , 'stf.agent'
+ )
+ }
+
+ function callService(intent) {
+ return adb.shell(options.serial, util.format(
+ 'am startservice --user 0 %s'
+ , intent
+ ))
+ .timeout(15000)
+ .then(function(out) {
+ return streamutil.findLine(out, /^Error/)
+ .finally(function() {
+ out.end()
+ })
+ .timeout(10000)
+ .then(function(line) {
+ if (line.indexOf('--user') !== -1) {
+ return adb.shell(options.serial, util.format(
+ 'am startservice %s'
+ , intent
+ ))
+ .timeout(15000)
+ .then(function() {
+ return streamutil.findLine(out, /^Error/)
+ .finally(function() {
+ out.end()
+ })
+ .timeout(10000)
+ .then(function(line) {
+ throw new Error(util.format(
+ 'Service had an error: "%s"'
+ , line
+ ))
+ })
+ .catch(streamutil.NoSuchLineError, function() {
+ return true
+ })
+ })
+ }
+ else {
+ throw new Error(util.format(
+ 'Service had an error: "%s"'
+ , line
+ ))
+ }
+ })
+ .catch(streamutil.NoSuchLineError, function() {
+ return true
+ })
+ })
+ }
+
+ function prepareForServiceDeath(conn) {
+ function endListener() {
+ var startTime = Date.now()
+ log.important('Service connection ended, attempting to relaunch')
+
+ /* eslint no-use-before-define: 0 */
+ openService()
+ .timeout(5000)
+ .then(function() {
+ log.important('Service relaunched in %dms', Date.now() - startTime)
+ })
+ .catch(function(err) {
+ log.fatal('Service connection could not be relaunched', err.stack)
+ lifecycle.fatal()
+ })
+ }
+
+ conn.once('end', endListener)
+
+ conn.on('error', function(err) {
+ log.fatal('Service connection had an error', err.stack)
+ lifecycle.fatal()
+ })
+ }
+
+ function handleEnvelope(data) {
+ var envelope = apk.wire.Envelope.decode(data)
+ var message
+ if (envelope.id !== null) {
+ messageResolver.resolve(envelope.id, envelope.message)
+ }
+ else {
+ switch (envelope.type) {
+ case apk.wire.MessageType.EVENT_AIRPLANE_MODE:
+ message = apk.wire.AirplaneModeEvent.decode(envelope.message)
+ push.send([
+ wireutil.global
+ , wireutil.envelope(new wire.AirplaneModeEvent(
+ options.serial
+ , message.enabled
+ ))
+ ])
+ plugin.emit('airplaneModeChange', message)
+ break
+ case apk.wire.MessageType.EVENT_BATTERY:
+ message = apk.wire.BatteryEvent.decode(envelope.message)
+ push.send([
+ wireutil.global
+ , wireutil.envelope(new wire.BatteryEvent(
+ options.serial
+ , message.status
+ , message.health
+ , message.source
+ , message.level
+ , message.scale
+ , message.temp
+ , message.voltage
+ ))
+ ])
+ plugin.emit('batteryChange', message)
+ break
+ case apk.wire.MessageType.EVENT_BROWSER_PACKAGE:
+ message = apk.wire.BrowserPackageEvent.decode(envelope.message)
+ plugin.emit('browserPackageChange', message)
+ break
+ case apk.wire.MessageType.EVENT_CONNECTIVITY:
+ message = apk.wire.ConnectivityEvent.decode(envelope.message)
+ push.send([
+ wireutil.global
+ , wireutil.envelope(new wire.ConnectivityEvent(
+ options.serial
+ , message.connected
+ , message.type
+ , message.subtype
+ , message.failover
+ , message.roaming
+ ))
+ ])
+ plugin.emit('connectivityChange', message)
+ break
+ case apk.wire.MessageType.EVENT_PHONE_STATE:
+ message = apk.wire.PhoneStateEvent.decode(envelope.message)
+ push.send([
+ wireutil.global
+ , wireutil.envelope(new wire.PhoneStateEvent(
+ options.serial
+ , message.state
+ , message.manual
+ , message.operator
+ ))
+ ])
+ plugin.emit('phoneStateChange', message)
+ break
+ case apk.wire.MessageType.EVENT_ROTATION:
+ message = apk.wire.RotationEvent.decode(envelope.message)
+ push.send([
+ wireutil.global
+ , wireutil.envelope(new wire.RotationEvent(
+ options.serial
+ , message.rotation
+ ))
+ ])
+ plugin.emit('rotationChange', message)
+ break
+ }
+ }
+ }
+
+ // 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()
@@ -83,215 +296,12 @@ module.exports = syrup.serial()
})
}
- 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() {
- return devutil.killProcsByComm(
- adb
- , options.serial
- , 'stf.agent'
- , 'stf.agent'
- )
- }
-
- function callService(intent) {
- return adb.shell(options.serial, util.format(
- 'am startservice --user 0 %s'
- , intent
- ))
- .timeout(15000)
- .then(function(out) {
- return streamutil.findLine(out, /^Error/)
- .finally(function() {
- out.end()
- })
- .timeout(10000)
- .then(function(line) {
- if (line.indexOf('--user') !== -1) {
- return adb.shell(options.serial, util.format(
- 'am startservice %s'
- , intent
- ))
- .timeout(15000)
- .then(function() {
- return streamutil.findLine(out, /^Error/)
- .finally(function() {
- out.end()
- })
- .timeout(10000)
- .then(function(line) {
- throw new Error(util.format(
- 'Service had an error: "%s"'
- , line
- ))
- })
- .catch(streamutil.NoSuchLineError, function() {
- return true
- })
- })
- }
- else {
- throw new Error(util.format(
- 'Service had an error: "%s"'
- , line
- ))
- }
- })
- .catch(streamutil.NoSuchLineError, function() {
- return true
- })
- })
- }
-
- // 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 endListener() {
- var startTime = Date.now()
- log.important('Service connection ended, attempting to relaunch')
- openService()
- .timeout(5000)
- .then(function() {
- log.important('Service relaunched in %dms', Date.now() - startTime)
- })
- .catch(function(err) {
- log.fatal('Service connection could not be relaunched', err.stack)
- lifecycle.fatal()
- })
- }
-
- conn.once('end', endListener)
-
- conn.on('error', function(err) {
- log.fatal('Service connection had an error', err.stack)
- lifecycle.fatal()
- })
- }
-
- function handleEnvelope(data) {
- var envelope = apk.wire.Envelope.decode(data)
- , message
- if (envelope.id !== null) {
- messageResolver.resolve(envelope.id, envelope.message)
- }
- else {
- switch (envelope.type) {
- case apk.wire.MessageType.EVENT_AIRPLANE_MODE:
- message = apk.wire.AirplaneModeEvent.decode(envelope.message)
- push.send([
- wireutil.global
- , wireutil.envelope(new wire.AirplaneModeEvent(
- options.serial
- , message.enabled
- ))
- ])
- plugin.emit('airplaneModeChange', message)
- break
- case apk.wire.MessageType.EVENT_BATTERY:
- message = apk.wire.BatteryEvent.decode(envelope.message)
- push.send([
- wireutil.global
- , wireutil.envelope(new wire.BatteryEvent(
- options.serial
- , message.status
- , message.health
- , message.source
- , message.level
- , message.scale
- , message.temp
- , message.voltage
- ))
- ])
- plugin.emit('batteryChange', message)
- break
- case apk.wire.MessageType.EVENT_BROWSER_PACKAGE:
- message = apk.wire.BrowserPackageEvent.decode(envelope.message)
- plugin.emit('browserPackageChange', message)
- break
- case apk.wire.MessageType.EVENT_CONNECTIVITY:
- message = apk.wire.ConnectivityEvent.decode(envelope.message)
- push.send([
- wireutil.global
- , wireutil.envelope(new wire.ConnectivityEvent(
- options.serial
- , message.connected
- , message.type
- , message.subtype
- , message.failover
- , message.roaming
- ))
- ])
- plugin.emit('connectivityChange', message)
- break
- case apk.wire.MessageType.EVENT_PHONE_STATE:
- message = apk.wire.PhoneStateEvent.decode(envelope.message)
- push.send([
- wireutil.global
- , wireutil.envelope(new wire.PhoneStateEvent(
- options.serial
- , message.state
- , message.manual
- , message.operator
- ))
- ])
- plugin.emit('phoneStateChange', message)
- break
- case apk.wire.MessageType.EVENT_ROTATION:
- message = apk.wire.RotationEvent.decode(envelope.message)
- push.send([
- wireutil.global
- , wireutil.envelope(new wire.RotationEvent(
- options.serial
- , message.rotation
- ))
- ])
- plugin.emit('rotationChange', message)
- break
- }
- }
+ function runAgentCommand(type, cmd) {
+ agent.writer.write(new apk.wire.Envelope(
+ null
+ , type
+ , cmd.encodeNB()
+ ).encodeNB())
}
function keyEvent(data) {
@@ -326,6 +336,17 @@ module.exports = syrup.serial()
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) {
return runServiceCommand(
apk.wire.MessageType.GET_DISPLAY
@@ -651,7 +672,7 @@ module.exports = syrup.serial()
})
}
- plugin.getSdStatus = function () {
+ plugin.getSdStatus = function() {
return runServiceCommand(
apk.wire.MessageType.GET_SD_STATUS
, 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()
.then(openService)
.then(function() {
@@ -723,7 +725,7 @@ module.exports = syrup.serial()
, keyCode: keyutil.namedKey(message.key)
})
}
- catch(e) {
+ catch (e) {
log.warn(e.message)
}
})
@@ -734,7 +736,7 @@ module.exports = syrup.serial()
, keyCode: keyutil.namedKey(message.key)
})
}
- catch(e) {
+ catch (e) {
log.warn(e.message)
}
})
@@ -745,7 +747,7 @@ module.exports = syrup.serial()
, keyCode: keyutil.namedKey(message.key)
})
}
- catch(e) {
+ catch (e) {
log.warn(e.message)
}
})
diff --git a/lib/units/device/plugins/shell.js b/lib/units/device/plugins/shell.js
index a5673a6e..93493d07 100644
--- a/lib/units/device/plugins/shell.js
+++ b/lib/units/device/plugins/shell.js
@@ -22,7 +22,11 @@ module.exports = syrup.serial()
.timeout(10000)
.then(function(stream) {
var resolver = Promise.defer()
- , timer
+ var timer
+
+ function forceStop() {
+ stream.end()
+ }
function keepAliveListener(channel, message) {
clearTimeout(timer)
@@ -51,10 +55,6 @@ module.exports = syrup.serial()
resolver.reject(err)
}
- function forceStop() {
- stream.end()
- }
-
stream.setEncoding('utf8')
stream.on('readable', readableListener)
diff --git a/lib/units/device/plugins/touch/index.js b/lib/units/device/plugins/touch/index.js
index 90dd6a64..043323a8 100644
--- a/lib/units/device/plugins/touch/index.js
+++ b/lib/units/device/plugins/touch/index.js
@@ -268,7 +268,7 @@ module.exports = syrup.serial()
if (/closed/.test(err.message) && times > 1) {
return Promise.delay(delay)
.then(function() {
- return tryConnect(--times, delay * 2)
+ return tryConnect(times - 1, delay * 2)
})
}
return Promise.reject(err)
@@ -315,7 +315,7 @@ module.exports = syrup.serial()
socket.stream.removeListener('readable', this.readableListener)
var endListener
- return new Promise(function(resolve/*, reject*/) {
+ return new Promise(function(resolve) {
socket.on('end', endListener = function() {
resolve(true)
})
@@ -343,8 +343,8 @@ module.exports = syrup.serial()
}
var signum = {
- 'SIGTERM': -15
- , 'SIGKILL': -9
+ SIGTERM: -15
+ , SIGKILL: -9
}[signal]
log.info('Sending %s to minitouch', signal)
@@ -395,7 +395,7 @@ module.exports = syrup.serial()
var args = chunk.toString().split(/ /g)
switch (args[0]) {
case 'v':
- banner.version = +args[1]
+ banner.version = Number(args[1])
break
default:
throw new Error(util.format(
@@ -432,7 +432,7 @@ module.exports = syrup.serial()
var args = chunk.toString().split(/ /g)
switch (args[0]) {
case '$':
- banner.pid = +args[1]
+ banner.pid = Number(args[1])
break
default:
throw new Error(util.format(
diff --git a/lib/units/device/plugins/util/flags.js b/lib/units/device/plugins/util/flags.js
index 16879079..45fee2a2 100644
--- a/lib/units/device/plugins/util/flags.js
+++ b/lib/units/device/plugins/util/flags.js
@@ -8,9 +8,9 @@ module.exports = syrup.serial()
return data && data.flags && !!data.flags[flag]
}
, get: function(flag, defaultValue) {
- return data && data.flags && data.flags[flag] !== void 0
- ? data.flags[flag]
- : defaultValue
+ return data && data.flags && typeof data.flags[flag] !== 'undefined' ?
+ data.flags[flag] :
+ defaultValue
}
}
})
diff --git a/lib/units/device/plugins/util/urlformat.js b/lib/units/device/plugins/util/urlformat.js
index b85c6e3d..4a473e5e 100644
--- a/lib/units/device/plugins/util/urlformat.js
+++ b/lib/units/device/plugins/util/urlformat.js
@@ -8,11 +8,11 @@ module.exports = syrup.serial()
.define(function(options, identity, data) {
function createSlug() {
var model = identity.model
- , name = data ? data.name.id : ''
+ var name = data ? data.name.id : ''
- return (name === '' || model.toLowerCase() === name.toLowerCase())
- ? tr.slugify(model)
- : tr.slugify(name + ' ' + model)
+ return (name === '' || model.toLowerCase() === name.toLowerCase()) ?
+ tr.slugify(model) :
+ tr.slugify(name + ' ' + model)
}
var defaults = {
diff --git a/lib/units/device/plugins/vnc/index.js b/lib/units/device/plugins/vnc/index.js
index e95b1c54..e6a6fd25 100644
--- a/lib/units/device/plugins/vnc/index.js
+++ b/lib/units/device/plugins/vnc/index.js
@@ -182,15 +182,16 @@ module.exports = syrup.serial()
var decoded = jpeg.decompressSync(
connState.lastFrame, connState.frameConfig)
- conn.writeFramebufferUpdate([
- { xPosition: 0
+ conn.writeFramebufferUpdate([{
+ xPosition: 0
, yPosition: 0
, width: decoded.width
, height: decoded.height
, encodingType: VncConnection.ENCODING_RAW
, data: decoded.data
}
- , { xPosition: 0
+ , {
+ xPosition: 0
, yPosition: 0
, width: decoded.width
, height: decoded.height
@@ -203,7 +204,7 @@ module.exports = syrup.serial()
}
function vncStartListener(frameProducer) {
- return new Promise(function(resolve/*, reject*/) {
+ return new Promise(function(resolve) {
connState.frameWidth = frameProducer.banner.virtualWidth
connState.frameHeight = frameProducer.banner.virtualHeight
resolve()
@@ -211,7 +212,7 @@ module.exports = syrup.serial()
}
function vncFrameListener(frame) {
- return new Promise(function(resolve/*, reject*/) {
+ return new Promise(function(resolve) {
connState.lastFrame = frame
connState.lastFrameTime = Date.now()
maybeSendFrame()
@@ -238,8 +239,10 @@ module.exports = syrup.serial()
})
conn.on('formatchange', function(format) {
- var same = os.endianness() === 'BE'
- === Boolean(format.bigEndianFlag)
+ var same = os.endianness() === 'BE' ===
+ Boolean(format.bigEndianFlag)
+ var formatOrder = (format.redShift > format.blueShift) === same
+
switch (format.bitsPerPixel) {
case 8:
connState.frameConfig = {
@@ -248,20 +251,19 @@ module.exports = syrup.serial()
break
case 24:
connState.frameConfig = {
- format: ((format.redShift > format.blueShift) === same)
- ? jpeg.FORMAT_BGR
- : jpeg.FORMAT_RGB
+ format: formatOrder ? jpeg.FORMAT_BGR : jpeg.FORMAT_RGB
}
break
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 = {
- format: ((format.redShift > format.blueShift) === same)
- ? (format.blueShift === 0
- ? jpeg.FORMAT_BGRX
- : jpeg.FORMAT_XBGR)
- : (format.redShift === 0
- ? jpeg.FORMAT_RGBX
- : jpeg.FORMAT_XRGB)
+ format: f
}
break
}
diff --git a/lib/units/device/plugins/vnc/util/connection.js b/lib/units/device/plugins/vnc/util/connection.js
index 82bbef49..49283667 100644
--- a/lib/units/device/plugins/vnc/util/connection.js
+++ b/lib/units/device/plugins/vnc/util/connection.js
@@ -90,7 +90,8 @@ VncConnection.CLIENT_MESSAGE_CLIENTCUTTEXT = 6
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_SECURITY: 20
, STATE_NEED_CLIENT_INIT: 30
diff --git a/lib/units/device/plugins/wifi.js b/lib/units/device/plugins/wifi.js
index ebae0cbc..1f43781f 100644
--- a/lib/units/device/plugins/wifi.js
+++ b/lib/units/device/plugins/wifi.js
@@ -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)
log.info('Getting Wifi status')
service.getWifiStatus()
diff --git a/lib/units/device/resources/minitouch.js b/lib/units/device/resources/minitouch.js
index 2b25d04a..f891ffaa 100644
--- a/lib/units/device/resources/minitouch.js
+++ b/lib/units/device/resources/minitouch.js
@@ -12,7 +12,7 @@ module.exports = syrup.serial()
.dependency(require('../support/adb'))
.dependency(require('../support/abi'))
.define(function(options, adb, abi) {
- var log = logger.createLogger('device:resources:minitouch') // jshint ignore:line
+ logger.createLogger('device:resources:minitouch')
var resources = {
bin: {
diff --git a/lib/units/device/resources/service.js b/lib/units/device/resources/service.js
index 657f82a8..bc3f7372 100644
--- a/lib/units/device/resources/service.js
+++ b/lib/units/device/resources/service.js
@@ -85,9 +85,9 @@ module.exports = syrup.serial()
})
.progressed(function() {
log.warn(
- 'STFService installation is taking a long time; '
- + 'perhaps you have to accept 3rd party app installation '
- + 'on the device?'
+ 'STFService installation is taking a long time; ' +
+ 'perhaps you have to accept 3rd party app installation ' +
+ 'on the device?'
)
})
.then(function() {
diff --git a/lib/units/device/support/abi.js b/lib/units/device/support/abi.js
index 104f13b0..e7fd59f0 100644
--- a/lib/units/device/support/abi.js
+++ b/lib/units/device/support/abi.js
@@ -7,7 +7,6 @@ module.exports = syrup.serial()
.define(function(options, properties) {
var log = logger.createLogger('device:support:abi')
return (function() {
-
function split(list) {
return list ? list.split(',') : []
}
@@ -39,6 +38,5 @@ module.exports = syrup.serial()
log.info('Supports ABIs %s', abi.all.join(', '))
return abi
-
})()
})
diff --git a/lib/units/device/support/sub.js b/lib/units/device/support/sub.js
index 99882c53..6e1d26a2 100644
--- a/lib/units/device/support/sub.js
+++ b/lib/units/device/support/sub.js
@@ -26,7 +26,7 @@ module.exports = syrup.serial()
})
.then(function() {
// Establish always-on channels
- ;[wireutil.global].forEach(function(channel) {
+ [wireutil.global].forEach(function(channel) {
log.info('Subscribing to permanent channel "%s"', channel)
sub.subscribe(channel)
})
diff --git a/lib/units/notify/hipchat.js b/lib/units/notify/hipchat.js
index c7b9127e..62a07461 100644
--- a/lib/units/notify/hipchat.js
+++ b/lib/units/notify/hipchat.js
@@ -25,7 +25,7 @@ module.exports = function(options) {
var log = logger.createLogger('notify-hipchat')
var client = Promise.promisifyAll(new Hipchatter(options.token))
var buffer = []
- , timer
+ var timer
// Input
var sub = zmqutil.socket('sub')
@@ -45,6 +45,25 @@ module.exports = function(options) {
sub.subscribe(channel)
})
+ function push() {
+ buffer.splice(0).forEach(function(entry) {
+ client.notifyAsync(options.room, {
+ message: util.format(
+ '%s/%s %d [%s] %s'
+ , logger.LevelLabel[entry.priority]
+ , entry.tag
+ , entry.pid
+ , entry.identifier
+ , entry.message
+ )
+ , color: COLORS[entry.priority]
+ , notify: entry.priority >= options.notifyPriority
+ , message_format: 'html'
+ , token: options.token
+ })
+ })
+ }
+
sub.on('message', wirerouter()
.on(wire.DeviceLogMessage, function(channel, message) {
if (message.priority >= options.priority) {
@@ -55,25 +74,6 @@ module.exports = function(options) {
})
.handler())
- function push() {
- buffer.splice(0).forEach(function(entry) {
- client.notifyAsync(options.room, {
- message: util.format(
- '%s/%s %d [%s] %s'
- , logger.LevelLabel[entry.priority]
- , entry.tag
- , entry.pid
- , entry.identifier
- , entry.message
- )
- , color: COLORS[entry.priority]
- , notify: entry.priority >= options.notifyPriority
- , 'message_format': 'html'
- , token: options.token
- })
- })
- }
-
log.info('Listening for %s (or higher) level log messages',
logger.LevelLabel[options.priority])
diff --git a/lib/units/poorxy/index.js b/lib/units/poorxy/index.js
index 36106443..1141d1b1 100644
--- a/lib/units/poorxy/index.js
+++ b/lib/units/poorxy/index.js
@@ -7,9 +7,9 @@ var logger = require('../../util/logger')
module.exports = function(options) {
var log = logger.createLogger('poorxy')
- , app = express()
- , server = http.createServer(app)
- , proxy = httpProxy.createProxyServer()
+ var app = express()
+ var server = http.createServer(app)
+ var proxy = httpProxy.createProxyServer()
proxy.on('error', function(err) {
log.error('Proxy had an error', err.stack)
diff --git a/lib/units/processor/index.js b/lib/units/processor/index.js
index c30c9cb2..7b022d91 100644
--- a/lib/units/processor/index.js
+++ b/lib/units/processor/index.js
@@ -32,12 +32,13 @@ module.exports = function(options) {
lifecycle.fatal()
})
+ // Device side
+ var devDealer = zmqutil.socket('dealer')
+
appDealer.on('message', function(channel, data) {
devDealer.send([channel, data])
})
- // Device side
- var devDealer = zmqutil.socket('dealer')
Promise.map(options.endpoints.devDealer, function(endpoint) {
return srv.resolve(endpoint).then(function(records) {
return srv.attempt(records, function(record) {
diff --git a/lib/units/provider/index.js b/lib/units/provider/index.js
index 0109738c..e87adaf6 100644
--- a/lib/units/provider/index.js
+++ b/lib/units/provider/index.js
@@ -154,9 +154,8 @@ module.exports = function(options) {
log.info('Found device "%s" (%s)', device.id, device.type)
var privateTracker = new EventEmitter()
- , willStop = false
- , timer
- , worker
+ var willStop = false
+ var timer, worker
// Wait for others to acknowledge the device
var register = new Promise(function(resolve) {
@@ -176,6 +175,155 @@ module.exports = function(options) {
privateTracker.once('register', resolve)
})
+
+ // Spawn a device worker
+ function spawn() {
+ var allocatedPorts = ports.splice(0, 4)
+ var proc = options.fork(device, allocatedPorts.slice())
+ var resolver = Promise.defer()
+
+ function exitListener(code, signal) {
+ if (signal) {
+ log.warn(
+ 'Device worker "%s" was killed with signal %s, assuming ' +
+ 'deliberate action and not restarting'
+ , device.id
+ , signal
+ )
+ resolver.resolve()
+ }
+ else if (code === 0) {
+ log.info('Device worker "%s" stopped cleanly', device.id)
+ resolver.resolve()
+ }
+ else {
+ resolver.reject(new procutil.ExitError(code))
+ }
+ }
+
+ function errorListener(err) {
+ log.error(
+ 'Device worker "%s" had an error: %s'
+ , device.id
+ , err.message
+ )
+ }
+
+ function messageListener(message) {
+ switch (message) {
+ case 'ready':
+ _.pull(lists.waiting, device.id)
+ lists.ready.push(device.id)
+ break
+ default:
+ log.warn(
+ 'Unknown message from device worker "%s": "%s"'
+ , device.id
+ , message
+ )
+ break
+ }
+ }
+
+ proc.on('exit', exitListener)
+ proc.on('error', errorListener)
+ proc.on('message', messageListener)
+
+ lists.waiting.push(device.id)
+
+ return resolver.promise
+ .finally(function() {
+ log.info('Cleaning up device worker "%s"', device.id)
+
+ proc.removeListener('exit', exitListener)
+ proc.removeListener('error', errorListener)
+ proc.removeListener('message', messageListener)
+
+ // Return used ports to the main pool
+ Array.prototype.push.apply(ports, allocatedPorts)
+
+ // Update lists
+ _.pull(lists.ready, device.id)
+ _.pull(lists.waiting, device.id)
+ })
+ .cancellable()
+ .catch(Promise.CancellationError, function() {
+ log.info('Gracefully killing device worker "%s"', device.id)
+ return procutil.gracefullyKill(proc, options.killTimeout)
+ })
+ .catch(Promise.TimeoutError, function(err) {
+ log.error(
+ 'Device worker "%s" did not stop in time: %s'
+ , device.id
+ , err.message
+ )
+ })
+ }
+
+ // 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()
@@ -250,154 +398,6 @@ module.exports = function(options) {
})
}
- // 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
- function spawn() {
- var allocatedPorts = ports.splice(0, 4)
- , proc = options.fork(device, allocatedPorts.slice())
- , resolver = Promise.defer()
-
- function exitListener(code, signal) {
- if (signal) {
- log.warn(
- 'Device worker "%s" was killed with signal %s, assuming ' +
- 'deliberate action and not restarting'
- , device.id
- , signal
- )
- resolver.resolve()
- }
- else if (code === 0) {
- log.info('Device worker "%s" stopped cleanly', device.id)
- resolver.resolve()
- }
- else {
- resolver.reject(new procutil.ExitError(code))
- }
- }
-
- function errorListener(err) {
- log.error(
- 'Device worker "%s" had an error: %s'
- , device.id
- , err.message
- )
- }
-
- function messageListener(message) {
- switch (message) {
- case 'ready':
- _.pull(lists.waiting, device.id)
- lists.ready.push(device.id)
- break
- default:
- log.warn(
- 'Unknown message from device worker "%s": "%s"'
- , device.id
- , message
- )
- break
- }
- }
-
- proc.on('exit', exitListener)
- proc.on('error', errorListener)
- proc.on('message', messageListener)
-
- lists.waiting.push(device.id)
-
- return resolver.promise
- .finally(function() {
- log.info('Cleaning up device worker "%s"', device.id)
-
- proc.removeListener('exit', exitListener)
- proc.removeListener('error', errorListener)
- proc.removeListener('message', messageListener)
-
- // Return used ports to the main pool
- Array.prototype.push.apply(ports, allocatedPorts)
-
- // Update lists
- _.pull(lists.ready, device.id)
- _.pull(lists.waiting, device.id)
- })
- .cancellable()
- .catch(Promise.CancellationError, function() {
- log.info('Gracefully killing device worker "%s"', device.id)
- return procutil.gracefullyKill(proc, options.killTimeout)
- })
- .catch(Promise.TimeoutError, function(err) {
- log.error(
- 'Device worker "%s" did not stop in time: %s'
- , device.id
- , err.message
- )
- })
- }
-
flippedTracker.on(device.id, deviceListener)
privateTracker.on('change', changeListener)
privateTracker.on('remove', removeListener)
diff --git a/lib/units/storage/plugins/apk/index.js b/lib/units/storage/plugins/apk/index.js
index 9cf23976..3d1f93ba 100644
--- a/lib/units/storage/plugins/apk/index.js
+++ b/lib/units/storage/plugins/apk/index.js
@@ -11,8 +11,8 @@ var manifest = require('./task/manifest')
module.exports = function(options) {
var log = logger.createLogger('storage:plugins:apk')
- , app = express()
- , server = http.createServer(app)
+ var app = express()
+ var server = http.createServer(app)
app.set('strict routing', true)
app.set('case sensitive routing', true)
diff --git a/lib/units/storage/plugins/image/index.js b/lib/units/storage/plugins/image/index.js
index 3a809d69..b35e8832 100644
--- a/lib/units/storage/plugins/image/index.js
+++ b/lib/units/storage/plugins/image/index.js
@@ -13,8 +13,8 @@ var transform = require('./task/transform')
module.exports = function(options) {
var log = logger.createLogger('storage:plugins:image')
- , app = express()
- , server = http.createServer(app)
+ var app = express()
+ var server = http.createServer(app)
app.set('strict routing', true)
app.set('case sensitive routing', true)
diff --git a/lib/units/storage/plugins/image/param/crop.js b/lib/units/storage/plugins/image/param/crop.js
index f719850f..a260dd6b 100644
--- a/lib/units/storage/plugins/image/param/crop.js
+++ b/lib/units/storage/plugins/image/param/crop.js
@@ -5,8 +5,8 @@ module.exports = function(raw) {
if (raw && (parsed = RE_CROP.exec(raw))) {
return {
- width: +parsed[1] || 0
- , height: +parsed[2] || 0
+ width: Number(parsed[1]) || 0
+ , height: Number(parsed[2]) || 0
}
}
diff --git a/lib/units/storage/plugins/image/task/get.js b/lib/units/storage/plugins/image/task/get.js
index 6633d999..8fe09c0c 100644
--- a/lib/units/storage/plugins/image/task/get.js
+++ b/lib/units/storage/plugins/image/task/get.js
@@ -8,7 +8,7 @@ var request = require('request')
module.exports = function(path, options) {
return new Promise(function(resolve, reject) {
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) {
if (res.statusCode !== 200) {
diff --git a/lib/units/storage/s3.js b/lib/units/storage/s3.js
index 7581bee5..f690494d 100644
--- a/lib/units/storage/s3.js
+++ b/lib/units/storage/s3.js
@@ -15,8 +15,8 @@ var logger = require('../../util/logger')
module.exports = function(options) {
var log = logger.createLogger('storage:s3')
- , app = express()
- , server = http.createServer(app)
+ var app = express()
+ var server = http.createServer(app)
var s3 = new AWS.S3({
credentials: new AWS.SharedIniFileCredentials({
@@ -80,7 +80,7 @@ module.exports = function(options) {
var file = files[field]
log.info('Uploaded "%s" to "%s"', file.name, file.path)
return putObject(plugin, file)
- .then(function (id) {
+ .then(function(id) {
return {
field: field
, id: id
@@ -151,5 +151,5 @@ module.exports = function(options) {
})
server.listen(options.port)
- console.log('Listening on port %d', options.port)
+ log.info('Listening on port %d', options.port)
}
diff --git a/lib/units/storage/temp.js b/lib/units/storage/temp.js
index 58345afc..4e337c90 100644
--- a/lib/units/storage/temp.js
+++ b/lib/units/storage/temp.js
@@ -15,9 +15,9 @@ var download = require('../../util/download')
module.exports = function(options) {
var log = logger.createLogger('storage:temp')
- , app = express()
- , server = http.createServer(app)
- , storage = new Storage()
+ var app = express()
+ var server = http.createServer(app)
+ var storage = new Storage()
app.set('strict routing', true)
app.set('case sensitive routing', true)
@@ -59,9 +59,7 @@ module.exports = function(options) {
'/s/%s/%s%s'
, plugin
, file.id
- , file.name
- ? util.format('/%s', path.basename(file.name))
- : ''
+ , file.name ? util.format('/%s', path.basename(file.name)) : ''
)
}
})
@@ -115,9 +113,9 @@ module.exports = function(options) {
'/s/%s/%s%s'
, plugin
, file.id
- , file.name
- ? util.format('/%s', path.basename(file.name))
- : ''
+ , file.name ?
+ util.format('/%s', path.basename(file.name)) :
+ ''
)
}
})
diff --git a/lib/units/websocket/index.js b/lib/units/websocket/index.js
index 89d91b82..06a0b47f 100644
--- a/lib/units/websocket/index.js
+++ b/lib/units/websocket/index.js
@@ -25,12 +25,12 @@ var jwtutil = require('../../util/jwtutil')
module.exports = function(options) {
var log = logger.createLogger('websocket')
- , server = http.createServer()
- , io = socketio.listen(server, {
+ var server = http.createServer()
+ var io = socketio.listen(server, {
serveClient: false
, transports: ['websocket']
})
- , channelRouter = new events.EventEmitter()
+ var channelRouter = new events.EventEmitter()
// Output
var push = zmqutil.socket('push')
@@ -89,12 +89,14 @@ module.exports = function(options) {
io.on('connection', function(socket) {
var req = socket.request
- , user = req.user
- , channels = []
+ var user = req.user
+ var channels = []
user.ip = socket.handshake.query.uip || req.ip
socket.emit('socket.ip', user.ip)
+ var messageListener = wirerouter()
+
function joinChannel(channel) {
channels.push(channel)
channelRouter.on(channel, messageListener)
@@ -118,7 +120,7 @@ module.exports = function(options) {
}
}
- var messageListener = wirerouter()
+ messageListener
.on(wire.DeviceLogMessage, function(channel, message) {
socket.emit('device.log', message)
})
@@ -316,7 +318,7 @@ module.exports = function(options) {
return dbapi.loadDevice(data.serial)
})
.then(function(device) {
- if(device) {
+ if (device) {
io.emit('device.change', {
important: true
, data: {
@@ -346,7 +348,7 @@ module.exports = function(options) {
})
var tokenId = util.format('%s-%s', uuid.v4(), uuid.v4()).replace(/-/g, '')
- , title = data.title
+ var title = data.title
return dbapi.saveUserAccessToken(user.email, {
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)
push.send([
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)
push.send([
channel
diff --git a/lib/units/websocket/middleware/auth.js b/lib/units/websocket/middleware/auth.js
index bebcb451..37e36cb2 100644
--- a/lib/units/websocket/middleware/auth.js
+++ b/lib/units/websocket/middleware/auth.js
@@ -2,7 +2,7 @@ var dbapi = require('../../../db/api')
module.exports = function(socket, next) {
var req = socket.request
- , token = req.session.jwt
+ var token = req.session.jwt
if (token) {
return dbapi.loadUser(token.email)
.then(function(user) {
diff --git a/lib/units/websocket/middleware/cookie-session.js b/lib/units/websocket/middleware/cookie-session.js
index 14132828..0a044b87 100644
--- a/lib/units/websocket/middleware/cookie-session.js
+++ b/lib/units/websocket/middleware/cookie-session.js
@@ -4,7 +4,7 @@ module.exports = function(options) {
var session = cookieSession(options)
return function(socket, next) {
var req = socket.request
- , res = Object.create(null)
+ var res = Object.create(null)
session(req, res, next)
}
}
diff --git a/lib/util/cliutil.js b/lib/util/cliutil.js
index 12d90612..5b619638 100644
--- a/lib/util/cliutil.js
+++ b/lib/util/cliutil.js
@@ -4,13 +4,14 @@ module.exports.list = function(val) {
module.exports.size = function(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) {
var items = []
- , i
- for (i = from; i <= to; ++i) {
+ for (var i = from; i <= to; ++i) {
items.push(i)
}
return items
diff --git a/lib/util/devutil.js b/lib/util/devutil.js
index fa6da22d..f2643b14 100644
--- a/lib/util/devutil.js
+++ b/lib/util/devutil.js
@@ -70,7 +70,7 @@ devutil.listPidsByComm = function(adb, serial, comm, bin) {
.then(function(out) {
return new Promise(function(resolve) {
var header = false
- , pids = []
+ var pids = []
out.pipe(split())
.on('data', function(chunk) {
if (header) {
@@ -79,7 +79,7 @@ devutil.listPidsByComm = function(adb, serial, comm, bin) {
else {
var cols = chunk.toString().split(/\s+/)
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) {
var model = properties['ro.product.model']
- , brand = properties['ro.product.brand']
- , manufacturer = properties['ro.product.manufacturer']
- , operator = properties['gsm.sim.operator.alpha'] ||
+ var brand = properties['ro.product.brand']
+ var manufacturer = properties['ro.product.manufacturer']
+ var operator = properties['gsm.sim.operator.alpha'] ||
properties['gsm.operator.alpha']
- , version = properties['ro.build.version.release']
- , sdk = properties['ro.build.version.sdk']
- , abi = properties['ro.product.cpu.abi']
- , product = properties['ro.product.name']
+ var version = properties['ro.build.version.release']
+ var sdk = properties['ro.build.version.sdk']
+ var abi = properties['ro.product.cpu.abi']
+ var product = properties['ro.product.name']
// Remove brand prefix for consistency
if (model.substr(0, brand.length) === brand) {
diff --git a/lib/util/jwtutil.js b/lib/util/jwtutil.js
index 35d1f5a4..d241116f 100644
--- a/lib/util/jwtutil.js
+++ b/lib/util/jwtutil.js
@@ -29,7 +29,7 @@ module.exports.decode = function(payload, secret) {
var decoded = jws.decode(payload, {
json: true
})
- , exp = decoded.header.exp
+ var exp = decoded.header.exp
if (exp && exp <= Date.now()) {
return null
diff --git a/lib/util/keyutil.js b/lib/util/keyutil.js
index dd8f63a3..cf494c91 100644
--- a/lib/util/keyutil.js
+++ b/lib/util/keyutil.js
@@ -7,15 +7,12 @@ var keyutil = module.exports = Object.create(null)
keyutil.parseKeyCharacterMap = function(stream) {
var resolver = Promise.defer()
- , state = 'type_t'
- , keymap = {
+ var state = 'type_t'
+ var keymap = {
type: null
, keys: []
}
- , lastKey
- , lastRule
- , lastModifier
- , lastBehavior
+ var lastKey, lastRule, lastModifier, lastBehavior
function fail(char, state) {
throw new Error(util.format(
@@ -431,8 +428,8 @@ keyutil.parseKeyCharacterMap = function(stream) {
function readableListener() {
var chunk = stream.read()
- , i = 0
- , l = chunk.length
+ var i = 0
+ var l = chunk.length
try {
while (i < l) {
@@ -461,7 +458,7 @@ keyutil.parseKeyCharacterMap = function(stream) {
keyutil.namedKey = function(name) {
var key = adb.Keycode['KEYCODE_' + name.toUpperCase()]
- if (key === void 0) {
+ if (typeof key === 'undefined') {
throw new Error(util.format('Unknown key "%s"', name))
}
return key
diff --git a/lib/util/ldaputil.js b/lib/util/ldaputil.js
index a13bb97d..36b9bc2e 100644
--- a/lib/util/ldaputil.js
+++ b/lib/util/ldaputil.js
@@ -19,7 +19,7 @@ module.exports.InvalidCredentialsError = InvalidCredentialsError
module.exports.login = function(options, username, password) {
function tryConnect() {
var resolver = Promise.defer()
- , client = ldap.createClient({
+ var client = ldap.createClient({
url: options.url
, timeout: options.timeout
, maxConnections: 1
@@ -44,7 +44,7 @@ module.exports.login = function(options, username, password) {
function tryFind(client) {
var resolver = Promise.defer()
- , query = {
+ var query = {
scope: options.search.scope
, filter: new ldap.AndFilter({
filters: [
diff --git a/lib/util/logger.js b/lib/util/logger.js
index f8afb90f..76671556 100644
--- a/lib/util/logger.js
+++ b/lib/util/logger.js
@@ -28,6 +28,32 @@ Logger.LevelLabel = {
Logger.globalIdentifier = '*'
+function Log(tag) {
+ this.tag = tag
+ this.names = {
+ 1: 'DBG'
+ , 2: 'VRB'
+ , 3: 'INF'
+ , 4: 'IMP'
+ , 5: 'WRN'
+ , 6: 'ERR'
+ , 7: 'FTL'
+ }
+ this.styles = {
+ 1: 'grey'
+ , 2: 'cyan'
+ , 3: 'green'
+ , 4: 'magenta'
+ , 5: 'yellow'
+ , 6: 'red'
+ , 7: 'red'
+ }
+ this.localIdentifier = null
+ events.EventEmitter.call(this)
+}
+
+util.inherits(Log, events.EventEmitter)
+
Logger.createLogger = function(tag) {
return new Log(tag)
}
@@ -37,32 +63,6 @@ Logger.setGlobalIdentifier = function(identifier) {
return Logger
}
-function Log(tag) {
- this.tag = tag
- this.names = {
- 1: 'DBG'
- , 2: 'VRB'
- , 3: 'INF'
- , 4: 'IMP'
- , 5: 'WRN'
- , 6: 'ERR'
- , 7: 'FTL'
- }
- this.styles = {
- 1: 'grey'
- , 2: 'cyan'
- , 3: 'green'
- , 4: 'magenta'
- , 5: 'yellow'
- , 6: 'red'
- , 7: 'red'
- }
- this.localIdentifier = null
- events.EventEmitter.call(this)
-}
-
-util.inherits(Log, events.EventEmitter)
-
Log.Entry = function(timestamp, priority, tag, pid, identifier, message) {
this.timestamp = timestamp
this.priority = priority
@@ -129,6 +129,7 @@ Log.prototype._name = function(priority) {
return chalk[this.styles[priority]](this.names[priority])
}
+/* eslint no-console: 0 */
Log.prototype._write = function(entry) {
console.error(this._format(entry))
this.emit('entry', entry)
diff --git a/lib/util/promiseutil.js b/lib/util/promiseutil.js
index 12087755..21f969da 100644
--- a/lib/util/promiseutil.js
+++ b/lib/util/promiseutil.js
@@ -2,12 +2,13 @@ var Promise = require('bluebird')
module.exports.periodicNotify = function(promise, interval) {
var resolver = Promise.defer()
- , timer = setInterval(notify, interval)
function notify() {
resolver.progress()
}
+ var timer = setInterval(notify, interval)
+
function resolve(value) {
resolver.resolve(value)
}
diff --git a/lib/util/requtil.js b/lib/util/requtil.js
index 79d85210..f242f3a6 100644
--- a/lib/util/requtil.js
+++ b/lib/util/requtil.js
@@ -31,11 +31,7 @@ module.exports.limit = function(limit, handler) {
var queue = []
var running = 0
- function done() {
- running -= 1
- maybeNext()
- }
-
+ /* eslint no-use-before-define: 0 */
function maybeNext() {
while (running < limit && queue.length) {
running += 1
@@ -43,6 +39,11 @@ module.exports.limit = function(limit, handler) {
}
}
+ function done() {
+ running -= 1
+ maybeNext()
+ }
+
return function() {
queue.push(arguments)
maybeNext()
diff --git a/lib/util/riskystream.js b/lib/util/riskystream.js
index 0f8dae2b..a3c67d22 100644
--- a/lib/util/riskystream.js
+++ b/lib/util/riskystream.js
@@ -37,11 +37,11 @@ RiskyStream.prototype.expectEnd = function() {
RiskyStream.prototype.waitForEnd = function() {
var stream = this.stream
- , endListener
+ var endListener
this.expectEnd()
- return new Promise(function(resolve/*, reject*/) {
+ return new Promise(function(resolve) {
if (stream.ended) {
return resolve(true)
}
diff --git a/lib/util/srv.js b/lib/util/srv.js
index 7bb2bd68..0a785952 100644
--- a/lib/util/srv.js
+++ b/lib/util/srv.js
@@ -41,7 +41,7 @@ function shuffleWeighted(records) {
function pick(records, sum) {
var rand = Math.random() * sum
- , counter = 0
+ var counter = 0
for (var i = 0, l = records.length; i < l; ++i) {
counter += records[i].weight
@@ -117,7 +117,7 @@ srv.attempt = function(records, fn) {
}
return fn(records[i]).catch(srv.NEXT, function() {
- return next(++i)
+ return next(i + 1)
})
}
diff --git a/lib/util/storage.js b/lib/util/storage.js
index ec8fd7d1..05cabc14 100644
--- a/lib/util/storage.js
+++ b/lib/util/storage.js
@@ -50,7 +50,7 @@ Storage.prototype.check = function() {
Object.keys(this.files).forEach(function(id) {
var file = this.files[id]
- , inactivePeriod = now - file.lastActivity
+ var inactivePeriod = now - file.lastActivity
if (inactivePeriod >= file.timeout) {
this.remove(id)
diff --git a/lib/util/streamutil.js b/lib/util/streamutil.js
index 8b11bc2a..4c6fb284 100644
--- a/lib/util/streamutil.js
+++ b/lib/util/streamutil.js
@@ -15,7 +15,7 @@ module.exports.NoSuchLineError = NoSuchLineError
module.exports.readAll = function(stream) {
var resolver = Promise.defer()
- , collected = new Buffer(0)
+ var collected = new Buffer(0)
function errorListener(err) {
resolver.reject(err)
@@ -45,7 +45,7 @@ module.exports.readAll = function(stream) {
module.exports.findLine = function(stream, re) {
var resolver = Promise.defer()
- , piped = stream.pipe(split())
+ var piped = stream.pipe(split())
function errorListener(err) {
resolver.reject(err)
diff --git a/lib/util/urlutil.js b/lib/util/urlutil.js
index 64073bcb..153375ed 100644
--- a/lib/util/urlutil.js
+++ b/lib/util/urlutil.js
@@ -3,8 +3,11 @@ var url = require('url')
module.exports.addParams = function(originalUrl, params) {
var parsed = url.parse(originalUrl, true)
parsed.search = null
+ // TODO: change to ES6 loop
for (var key in params) {
- parsed.query[key] = params[key]
+ if (params.dict.hasOwnProperty(key)) {
+ parsed.query[key] = params[key]
+ }
}
return url.format(parsed)
}
diff --git a/lib/util/vncauth.js b/lib/util/vncauth.js
index 711d12df..1b9ec5d9 100644
--- a/lib/util/vncauth.js
+++ b/lib/util/vncauth.js
@@ -28,7 +28,7 @@ function normalizePassword(password) {
function encrypt(challenge, 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
// desired result.
diff --git a/lib/util/zmqutil.js b/lib/util/zmqutil.js
index c8e2e312..e551ee1d 100644
--- a/lib/util/zmqutil.js
+++ b/lib/util/zmqutil.js
@@ -14,7 +14,7 @@ module.exports.socket = function() {
;['ZMQ_TCP_KEEPALIVE', 'ZMQ_TCP_KEEPALIVE_IDLE'].forEach(function(opt) {
if (process.env[opt]) {
try {
- sock.setsockopt(zmq[opt], +process.env[opt])
+ sock.setsockopt(zmq[opt], Number(process.env[opt]))
}
catch (err) {
log.warn('ZeroMQ library too old, no support for %s', opt)
diff --git a/lib/wire/channelmanager.js b/lib/wire/channelmanager.js
index 0fb15b78..9d8aa8a6 100644
--- a/lib/wire/channelmanager.js
+++ b/lib/wire/channelmanager.js
@@ -53,7 +53,7 @@ ChannelManager.prototype.keepalive = function(id) {
ChannelManager.prototype.check = function(id) {
var channel = this.channels[id]
- , inactivePeriod = Date.now() - channel.lastActivity
+ var inactivePeriod = Date.now() - channel.lastActivity
if (inactivePeriod >= channel.timeout) {
this.unregister(id)
diff --git a/lib/wire/router.js b/lib/wire/router.js
index 7805fdd2..840ebfd0 100644
--- a/lib/wire/router.js
+++ b/lib/wire/router.js
@@ -30,7 +30,7 @@ Router.prototype.removeListener = function(message, handler) {
Router.prototype.handler = function() {
return function(channel, data) {
var wrapper = wire.Envelope.decode(data)
- , type = wire.ReverseMessageType[wrapper.type]
+ var type = wire.ReverseMessageType[wrapper.type]
if (type) {
this.emit(
diff --git a/lib/wire/seqqueue.js b/lib/wire/seqqueue.js
index 6670e51a..410b3b36 100644
--- a/lib/wire/seqqueue.js
+++ b/lib/wire/seqqueue.js
@@ -44,7 +44,7 @@ SeqQueue.prototype.maybeConsume = function() {
var handler = this.list[this.lo]
// Have we received it yet?
if (handler) {
- this.list[this.lo] = void 0
+ this.list[this.lo] = undefined
handler()
this.lo += 1
this.waiting -= 1