-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
executable file
·289 lines (260 loc) · 8.65 KB
/
Copy pathapp.js
File metadata and controls
executable file
·289 lines (260 loc) · 8.65 KB
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
// Requirements
require('dotenv').config()
const request = require('sync-request');
const chalk = require('chalk');
const cmd = require('node-cmd');
const express = require('express');
const path = require('path');
const app = express();
const ip = require("ip");
const commandExists = require('command-exists');
const fs = require("fs");
const jsonStringify = require('json-pretty');
const readline = require('readline');
const Logger = require("./core/Logger.js");
const logger = new Logger("Jarvis");
const http = require('http');
const https = require('https');
const TTS = require("./core/TTS.js")
// End Requirements
//Setup a readline interface for the ask function
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
/**
* The ask function is used for debugging. It will have Jarvis parse anything you type in the console.
* @example
* ask();
*/
var ask = function() {
rl.question('> ', (answer) => {
client.message(unescape(answer), {})
.then((data) => {
logic(data);
})
.catch((err) => {
logger.Error(err.message);
});
});
}
// Require Wit.ai stuff
const {
Wit,
log
} = require('node-wit');
// Set our access token to what we have in the .env file.
const client = new Wit({
accessToken: process.env.witapi
});
/**
* Replaces all instances of specified string with a replacment. If you add a third param it will also append that string to the end of whatever it replaces.
* @class String
* @function replaceAll
* @param {string} target - The string you want to replace.
* @param {string} replacment - What to replace the target string with.
* @param {string} [append] - what to append after the string that was replaced. Default value is nothing.
* @returns {string} Returns the modified string;
*/
String.prototype.replaceAll = function(target, replacement, append = "") {
let ret = this.split(target).join(replacement);
if (ret !== this.toString()) {
return ret + append;
} else {
return ret;
}
};
// Set a global path to use for plugins.
const normalizedPath = require("path").join(__dirname, "/plugins");
let modules = {};
/**
* @todo Move this to its own file.
* @class Config
* @deprecated Until further notice.
*/
var Config = {
getDataFolder: function() {
return "./plugins/" + this.name + "/";
},
createConfig: function() {
if (fs.existsSync(this.getDataFolder())) {
return;
} else {
fs.mkdirSync(this.getDataFolder());
}
},
addConfig: function(name, def) {
if (fs.existsSync(this.getDataFolder() + name + ".json")) {
return;
} else {
var fd = fs.openSync(this.getDataFolder() + this.name + ".json", 'w');
if (def === null && def === undefined) {
def = {};
}
fs.writeFile(this.getDataFolder() + this.name + ".json", jsonStringify(def), function(err) {
if (err) {
return console.log(err);
}
return;
});
}
},
getConfigValue: function(name) {
if (fs.existsSync(this.getDataFolder() + this.name + ".json")) {
var file = require(this.getDataFolder() + this.name + ".json");
return file[name];
} else {
return;
}
}
}
/**
* Oh boy this is gonna be fun. logic is the core Jarvis function. It runs all the necessary checks before calling a specific module. This requires {@link module:core/Logger}.
* @function logic
* @param {string} input - What you want Jarvis to parse.
* @requires module:core/Logger
* @example
* logic("weather today"); // Jarvis will call the weather module for this and return the weather conditions for today.
*/
let logic = function(input) {
// Output whatever input is in a JSON format.
logger.Info(JSON.stringify(input));
// Default to false.
let logicModule = false;
// Initialize an array.
let tags = []
for (i in input.entities) {
tags.push(i)
}
for (var mod in modules) {
let metRequirement = false;
let inputSplits = input._text.split(" ");
let requirements = [modules[mod].requirements.match(/\[([^)]+)\]/)[1].split(", "), modules[mod].requirements.match(/\{([^)]+)\}/)[1].split(", ")];
for (var i in inputSplits) {
for (var ii in requirements[0]) {
if (requirements[0][ii] !== "*") {
if (requirements[0][ii] == inputSplits[i]) {
for (var iii in tags) {
for (var iiii in requirements[1]) {
if (tags[iii] !== "*") {
if (tags[iii] == requirements[1][iiii]) {
// If the tag requirements and the word requirements are meet
metRequirement = true;
}
} else {
// Wildcard
metRequirement = true;
}
}
}
}
} else {
for (var iii in tags) {
for (var iiii in requirements[1]) {
if (tags[iii] !== "*") {
if (tags[iii] == requirements[1][iiii]) {
// If wildcard word and requirements are meet
metRequirement = true;
}
} else {
// Wildcard
metRequirement = true;
}
}
}
}
}
}
if (metRequirement) {
logicModule = modules[mod];
break;
}
}
if (logicModule != false) {
getLogic(logicModule, input, request).then(data => TTS(data, logger, cmd, process));
ask();
} else {
TTS("I am sorrry, but I don't understand that.", logger, cmd, process);
ask();
}
}
/**
* The function that actually runs a module's `run` function. THIS IS FOR INTERNAL USE ONLY! USE THE {@link logic} FUNCTION INSTEAD!
* @private
* @function getLogic
* @param {Object} logicModule - The export from the module. Each module is `require()`ed therefore this accepts an object.
* @param {string} input - The input string from {@link logic}. This is passed to the module for processing.
* @param {Object} request - The sync-request module.
* @returns {Promise} This is a new promise. The module will either reject or resolve the promise. This allows the module to decide when to return a value.
*/
var getLogic = function(logicModule, input, request) {
return new Promise(function(resolve, reject) {
logicModule.run(input, request, resolve, reject);
});
}
/**
* This function will convert text in speech (Text To Speech).
* @function TTS
* @param {string} text - The text to convert into a string.
* @requires module:core/Logger
*/
app.get('/', function(req, res) {
res.send(fs.readFileSync(paths.join(__dirname + '/index.html')).toString().replace("localhost",ip.address()));
});
// Local webserver for listen.py (I WANT IT GONE SO BAD!).
app.get('/:request', function(req, res) {
res.send("Pinged")
// Send input to Wit.ai
if (unescape(req.param('request')) == "favicon.ico"){
return false;
}
client.message(unescape(req.param('request')), {})
.then((data) => {
// Send what we get from Wit to the logic function.
logic(data);
})
.catch((err) => { // Handle errors.
logger.Error(err.stack);
});
})
// First ask
ask();
// Start the webserver.
app.listen(process.env.port, function() {
logger.Info('Example app listening on port ' + process.env.port + '!')
})
// Module Loading. Get the name of all files and folders in the normalizedPath.
require("fs").readdirSync(normalizedPath).forEach(function(file) {
// If file variable is a folder, do nothing.
if (fs.statSync(normalizedPath + "/" + file).isDirectory()) {
} else {
// Add the module to the modules array.
modules[file.replace(".js", "")] = require("./plugins/" + file);
// Helper variable to make subsequent stuff easier. Its just a reference to the mod we are currently loading.
var mod = modules[file.replace(".js", "")];
// If this mod doesn't have a name, error out.
if (mod.name !== null && mod.name !== undefined) {
// If this mod doesn't have a version, error out.
if (mod.version !== null && mod.version !== undefined) {
logger.Info("Loaded " + mod.name + " module.");
// If this mod has an OnLoad function, call it.
if (typeof mod.OnLoad === "function") {
mod.OnLoad();
}
} else {
logger.Error("Module " + file + " is missing a verion. Not loading module.");
// Remove mod from modules array.
delete(modules[file.replace(".js", "")]);
}
} else {
logger.Error("Module " + file + " is missing a name. Not loading module.");
// Remove mod from modules array.
delete(modules[file.replace(".js", "")]);
}
}
});
logger.Info("Local IP "+ip.address())
// If this is Travis, stop.
if (process.env.Travis) {
process.exit()
}