forked from superscriptjs/superscript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
318 lines (257 loc) · 8.44 KB
/
Copy pathindex.js
File metadata and controls
318 lines (257 loc) · 8.44 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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
var util = require("util");
var events = require("events");
var EventEmitter = events.EventEmitter;
var async = require("async");
var qtypes = require("qtypes");
var _ = require("lodash");
var norm = require("node-normalizer");
var requireDir = require("require-dir");
var debug = require("debug-levels")("SS:Script");
var facts = require("sfacts");
var gTopicsSystem = require("./lib/topics/index");
var Message = require("./lib/message");
var Users = require("./lib/users");
var getreply = require("./lib/getreply");
var Utils = require("./lib/utils");
var processHelpers = require("./lib/reply/common");
var mergex = require("deepmerge");
function SuperScript(options, callback) {
EventEmitter.call(this);
var mongoose;
var self = this;
options = options || {};
// Create a new connection if non is provided.
if (options.mongoose) {
mongoose = options.mongoose;
} else {
mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/superscriptDB");
}
this._plugins = [];
this.normalize = null;
this.question = null;
Utils.mkdirSync("./plugins");
this.loadPlugins("./plugins");
this.loadPlugins(process.cwd() + "/plugins");
// this.intervalId = setInterval(this.check.bind(this), 500);
this.factSystem = options.factSystem ? options.factSystem : facts.create("systemDB");
this.topicSystem = gTopicsSystem(mongoose, this.factSystem);
// This is a kill switch for filterBySeen which is useless in the editor.
this.editMode = options.editMode || false;
// We want a place to store bot related data
this.memory = options.botfacts ? options.botfacts : this.factSystem.createUserDB("botfacts");
this.scope = {};
this.scope = _.extend(options.scope || {});
this.scope.bot = this;
this.scope.facts = this.factSystem;
this.scope.topicSystem = this.topicSystem;
this.scope.botfacts = this.memory;
this.users = new Users(mongoose, this.factSystem);
norm.loadData(function () {
self.normalize = norm;
new qtypes(function (question) {
self.question = question;
debug.verbose("System Loaded, waiting for replies");
callback(null, self);
});
});
}
var messageItorHandle = function (user, system) {
var messageItor = function (msg, next) {
var options = {
user: user,
system: system,
message: msg
};
processHelpers.getTopic(options.system.topicsSystem, system.topicName, function (err, topicData) {
if (topicData) {
options.aTopics = [];
options.aTopics.push(topicData);
}
getreply(options, function (err, replyObj) {
// Convert the reply into a message object too.
var msgString = "";
var messageOptions = {
qtypes: system.question,
norm: system.normalize,
facts: system.facts
};
if (replyObj) {
messageOptions.replyId = replyObj.replyId;
msgString = replyObj.string;
if (replyObj.clearConvo) {
messageOptions.clearConvo = replyObj.clearConvo;
}
} else {
replyObj = {};
}
new Message(msgString, messageOptions, function (replyMessageObject) {
user.updateHistory(msg, replyMessageObject, replyObj, function(err, log) {
// We send back a smaller message object to the clients.
var clientObject = {
replyId: replyObj.replyId,
createdAt: replyMessageObject.createdAt || new Date(),
string: msgString || "", // replyMessageObject.raw || "",
topicName: replyObj.topicName,
subReplies: replyObj.subReplies,
debug: log
};
var newClientObject = mergex(clientObject, replyObj.props || {});
user.save(function (err, res) {
debug.verbose(err, res);
// TODO - Seeing RangeError here. (investigate Mongoose 4.0)
return next(null, newClientObject);
});
});
});
});
});
};
return messageItor;
};
// This takes a message and breaks it into chucks to be passed though
// the sytem. We put them back together on the other end.
// FIXME: with chunking removed this is not needed.
var messageFactory = function (options, cb) {
var rawMsg = options.msg;
var normalize = options.normalize;
var messageParts = [];
var cleanMsg = normalize.clean(rawMsg).trim();
debug.verbose("IN MessageFactory", cleanMsg);
var hasExtraScope = options.extraScope ? true : false;
var messageOptions = {
qtypes: options.question,
norm: normalize,
facts: options.factSystem,
original: rawMsg,
extraScope: hasExtraScope
};
return new Message(cleanMsg, messageOptions, function (tmsg) {
var mset = _.isEmpty(tmsg) ? [] : [tmsg]
return cb(null, mset);
});
};
util.inherits(SuperScript, EventEmitter);
SuperScript.prototype.message = function (msgString, callback) {
var messageOptions = {
qtypes: this.question,
norm: this.normalize,
facts: this.factSystem
};
var message = new Message(msgString, messageOptions, function (msgObj) {
callback(null, msgObj);
});
};
// This is like doing a topicRedirect
SuperScript.prototype.directReply = function (userId, topic, msg, callback) {
debug.log("[ New DirectReply - '%s']- %s", userId, msg)
var options = {
userId: userId,
topicName: topic,
msgString: msg,
extraScope: {}
};
this._reply(options, callback);
};
// Convert msg into message object, then check for a match
SuperScript.prototype.reply = function (userId, msg, callback, extraScope) {
if (arguments.length === 2 && typeof msg === "function") {
callback = msg;
msg = userId;
userId = Math.random().toString(36).substr(2, 5);
extraScope = {};
}
debug.log("[ New Message - '%s']- %s", userId, msg)
var options = {
userId: userId,
msgString: msg,
extraScope: extraScope
};
this._reply(options, callback);
};
SuperScript.prototype._reply = function(options, callback) {
var self = this;
// Ideally these will come from a cache, but self is a exercise for a rainy day
var system = {
// getReply
topicsSystem: self.topicSystem,
plugins: self._plugins,
scope: self.scope,
messageScope: options.extraScope,
// Pass in the topic if it
topicName: options.topicName || null,
// Message
question: self.question,
normalize: self.normalize,
facts: self.factSystem,
editMode: self.editMode
};
var prop = {
currentTopic: "random",
status: 0,
conversation: 0, volley: 0, rally: 0
};
this.users.findOrCreate({ id: options.userId }, prop, function (err1, user) {
if (err1) {
debug.error(err1);
}
var opt = {
msg: options.msgString,
question: self.question,
normalize: self.normalize,
factSystem: self.factSystem,
extraScope: options.extraScope
};
messageFactory(opt, function (err, messages) {
// FIXME: `messages` will always be one now that we no longer chunk
async.mapSeries(messages, messageItorHandle(user, system), function (err2, messageArray) {
if (err2) {
debug.error(err2);
}
var reply = {};
var messageArray = Utils.cleanArray(messageArray);
if (_.isEmpty(messageArray)) {
reply.string = "";
} else if (messageArray.length === 1) {
reply = messageArray[0];
}
debug.verbose("Update and Reply to user '%s'", user.id, reply)
debug.info("[ Final Reply - '%s']- '%s'", user.id, reply.string)
return callback(err2, reply);
});
});
});
}
SuperScript.prototype.loadPlugins = function (path) {
var plugins = requireDir(path);
for (var file in plugins) {
for (var func in plugins[file]) {
debug.verbose("Loading Plugin", path, func);
this._plugins[func] = plugins[file][func];
}
}
};
SuperScript.prototype.getPlugins = function () {
return this._plugins;
};
SuperScript.prototype.getTopics = function () {
return this.topics;
};
SuperScript.prototype.getUsers = function (cb) {
this.users.find({}, "id", cb);
};
SuperScript.prototype.getUser = function (userId, cb) {
this.users.findOne({id: userId}, function (err, usr) {
cb(err, usr);
});
};
SuperScript.prototype.findOrCreateUser = function (userId, callback) {
var properties = { id: userId };
var prop = {
currentTopic: "random",
status: 0,
conversation: 0, volley: 0, rally: 0
};
this.users.findOrCreate(properties, prop, callback);
};
module.exports = SuperScript;