srvcttn
Version:
Headless operator for go.servicetian.com actions
113 lines (100 loc) • 3.16 kB
JavaScript
/**
* The contents of this file is free and unencumbered software released into the
* public domain. For more information, please refer to <http://unlicense.org/>
*
* @author Maxmillion McLaughlin <npm@maxmclau.com>
*/
let Nightmare = require('nightmare')
let debug = require('debug')('srvcttn')
const show = (process.env.SRVCTTN && process.env.SRVCTTN.includes('show')) || false
class Srvcttn {
constructor(seed) {
this._seed = seed || 'default'
this._instance = new Nightmare({
show: show,
gotoTimeout: 8000,
loadTimeout: 8000,
waitTimeout: 8000,
webPreferences: {
partition: `nopersist:${seed}`,
images: false
}
})
}
login(username, password) {
return new Promise((resolve, reject) => {
this._instance
.goto('https://go.servicetitan.com/')
.wait(500)
.url()
.then((url) => {
debug(`${this.pid} redirected to ${url}`)
debug(`${this.pid} will login`)
if(url == 'https://go.servicetitan.com/Auth/Login') {
let timeout = setTimeout(() => {
this.kill('timed out at login').then(reject())
}, 8000);
this._instance
.insert('form [name=Username]', username)
.insert('form [name=Password]', password)
.click('form .login-button')
.wait('div.profile')
.then(() => {
clearTimeout(timeout)
debug(`${this.pid} session required log in`)
resolve(false)
})
.catch((err) => this.kill(err).then(reject(err)))
}
else if(url == 'https://go.servicetitan.com/#/Dashboard') {
debug(`${this.pid} session previously logged in`)
resolve(true)
}
})
.catch((err) => this.kill(err).then(reject(err)))
})
}
job(id) {
return {
addTag: (tag) => {
return new Promise((resolve, reject) => {
(tag == null) ? reject(new Error('tag not specified in request')) : null
debug(`${this.pid} will attempt to add tag`)
this._instance
.goto(`https://go.servicetitan.com/#/Job/Edit/${id}`)
.wait('.edit-job-form')
.type('.tags-editor .select2-input', tag)
.type('.tags-editor .select2-input', '\u000d')
.click('form .btn-success')
.wait(200)
.wait('.job-detail-view')
.wait(200)
.then(() => {
debug(`${this.pid} did add tag ${tag} to ${id}`)
resolve()
})
.catch((err) => this.kill(err).then(reject(err)))
})
}
}
}
kill(err, callback) {
return new Promise((resolve, reject) => {
this._instance
.end()
.then(() => {
if(err) debug(`${this.pid} ${err}`)
debug(`${this.pid} was killed`)
resolve()
})
.catch((err) => {
reject(err)
process.exit(1)
})
})
}
get pid() {
return this._instance.proc.pid
}
}
module.exports = Srvcttn