-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil-file.js
executable file
·118 lines (89 loc) · 2.51 KB
/
util-file.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
const fs = require('fs')
const utilRemoteSync = require('./util-remote-sync.js')
module.exports.getConfiguration = function (callback) {
fs.readFile('user-database.json', 'utf8', function (err, data) {
if (err) {
return callback(err)
}
try {
var configuration = JSON.parse(data)
} catch (exception) {
return callback(exception)
}
callback(null, configuration)
})
}
module.exports.setConfiguration = function (configuration, callback) {
let configurationAsString = JSON.stringify(configuration, null, 4)
fs.writeFile('user-database.json', configurationAsString, function (err) {
if (err) {
callback(err)
} else {
// sync state to server
utilRemoteSync.update(process.env.TWILIO_SYNC_DOCUMENT, configuration)
.then(doc => {
callback(null, doc)
}).catch(error => {
callback(error)
})
}
})
}
module.exports.setUserState = function (identity, state, callback) {
console.log('update: ' + identity + ' - state "' + state + '"')
module.exports.getConfiguration(function (error, configuration) {
if (error) {
callback(error)
} else {
let user = module.exports.getUser(identity, configuration)
user.state = state
user.updatedAt = new Date()
configuration.users[identity] = user
module.exports.setConfiguration(configuration, function (error) {
callback(null)
})
}
})
}
module.exports.updateUserState = function (identity, event, callback) {
console.log('update: ' + identity + ' - event "' + event + '"')
module.exports.getConfiguration(function (error, configuration) {
if (error) {
callback(error)
} else {
let user = module.exports.getUser(identity, configuration)
switch (event) {
case 'endpoint_connected':
user.endpoints++
break
case 'endpoint_disconnected':
user.endpoints--
break
default:
break
}
/* no endpoints anymore, set agent offline */
if (user.endpoints === 0) {
user.state = 'unavailable'
}
/* the agent was offline and now went online, put agent to online */
if (user.endpoints === 1 && event === 'endpoint_connected') {
user.state = 'available'
}
user.updatedAt = new Date()
configuration.users[identity] = user
module.exports.setConfiguration(configuration, function (error) {
callback(null)
})
}
})
}
module.exports.getUser = function (identity, configuration) {
let user = null
if (configuration.users[identity] === undefined) {
user = { endpoints: 0, state: null }
} else {
user = configuration.users[identity]
}
return user
}