<commit_before>_ = require 'lodash'
es = require 'event-stream'
url = require 'url'
knex = require './db'
path = require 'path'
config = require './config'
dockerUtils = require './docker-utils'
PUBNUB = require 'pubnub'
Promise = require 'bluebird'
PlatformAPI = require 'resin-platform-api/request'
utils = require './utils'
tty = require './lib/tty'

{docker} = dockerUtils

PLATFORM_ENDPOINT = url.resolve(config.apiEndpoint, '/ewa/')
resinAPI = new PlatformAPI(PLATFORM_ENDPOINT)

pubnub = PUBNUB.init(config.pubnub)

# Queue up any calls to publish while we wait for the uuid to return from the sqlite db
publish = do ->
	publishQueue = []

	knex('config').select('value').where(key: 'uuid').then ([ uuid ]) ->
		uuid = uuid.value
		channel = "device-#{uuid}-logs"

		# Redefine original function
		publish = (message) ->
			pubnub.publish({ channel, message })

		# Replay queue now that we have initialised the publish function
		publish(args...) for args in publishQueue

	return -> publishQueue.push(arguments)

exports.logSystemEvent = logSystemEvent = (message) ->
	publish("[system] " + message)

exports.kill = kill = (app) ->
	logSystemEvent('Killing application ' + app.imageId)
	utils.mixpanelTrack('Application kill', app)
	updateDeviceInfo(status: 'Stopping')
	container = docker.getContainer(app.containerId)
	console.log('Stopping and deleting container:', container)
	tty.stop()
	.catch (err) ->
		console.error('Error stopping tty', err)
		return # Even if stopping the tty fails we want to finish stopping the container
	.then ->
		container.stopAsync()
	.then ->
		container.removeAsync()
	# Bluebird throws OperationalError for errors resulting in the normal execution of a promisified function.
	.catch Promise.OperationalError, (err) ->
		# Get the statusCode from the original cause and make sure statusCode its definitely a string for comparison
		# reasons.
		statusCode = '' + err.cause.statusCode
		# 304 means the container was already stopped - so we can just remove it
		if statusCode is '304'
			return container.removeAsync()
		# 404 means the container doesn't exist, precisely what we want! :D
		if statusCode is '404'
			return<commit_msg>Specify the tty app to stop.<commit_after>_ = require 'lodash'
es = require 'event-stream'
url = require 'url'
knex = require './db'
path = require 'path'
config = require './config'
dockerUtils = require './docker-utils'
PUBNUB = require 'pubnub'
Promise = require 'bluebird'
PlatformAPI = require 'resin-platform-api/request'
utils = require './utils'
tty = require './lib/tty'

{docker} = dockerUtils

PLATFORM_ENDPOINT = url.resolve(config.apiEndpoint, '/ewa/')
resinAPI = new PlatformAPI(PLATFORM_ENDPOINT)

pubnub = PUBNUB.init(config.pubnub)

# Queue up any calls to publish while we wait for the uuid to return from the sqlite db
publish = do ->
	publishQueue = []

	knex('config').select('value').where(key: 'uuid').then ([ uuid ]) ->
		uuid = uuid.value
		channel = "device-#{uuid}-logs"

		# Redefine original function
		publish = (message) ->
			pubnub.publish({ channel, message })

		# Replay queue now that we have initialised the publish function
		publish(args...) for args in publishQueue

	return -> publishQueue.push(arguments)

exports.logSystemEvent = logSystemEvent = (message) ->
	publish("[system] " + message)

exports.kill = kill = (app) ->
	logSystemEvent('Killing application ' + app.imageId)
	utils.mixpanelTrack('Application kill', app)
	updateDeviceInfo(status: 'Stopping')
	container = docker.getContainer(app.containerId)
	console.log('Stopping and deleting container:', container)
	tty.stop(app.id)
	.catch (err) ->
		console.error('Error stopping tty', err)
		return # Even if stopping the tty fails we want to finish stopping the container
	.then ->
		container.stopAsync()
	.then ->
		container.removeAsync()
	# Bluebird throws OperationalError for errors resulting in the normal execution of a promisified function.
	.catch Promise.OperationalError, (err) ->
		# Get the statusCode from the original cause and make sure statusCode its definitely a string for comparison
		# reasons.
		statusCode = '' + err.cause.statusCode
		# 304 means the container was already stopped - so we can just remove it
		if statusCode is '304'
			return container.removeAsync()
		# 404 means the container doesn't exist, precisely what we want! :D
		if statusCode is '404'
			return
{'fraction_non_alphanumeric': 0.1132161606939055, 'fraction_numerical': 0.005478201323898653, 'mean_word_length': 4.317961165048544, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 23, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5683669', 'n_tokens_mistral': 1386, 'n_tokens_neox': 1299, 'n_words': 442}