-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
1050 lines (893 loc) · 30.8 KB
/
index.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
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
const Logger = require('./lib/logger.js').Logger;
const logLevels = require('./lib/logger.js').logLevels;
const Wit = require('./lib/wit.js').Wit;
const Promise = require('promise');
const rp = require('request-promise');
const logger = new Logger(logLevels.DEBUG);
// When not cloning the `node-wit` repo, replace the `require` like so:
// const Wit = require('node-wit').Wit;
// const Wit = require('node-wit').Wit;
// Webserver parameter
const PORT = process.env.PORT || 8445;
// Wit.ai parameters
const WIT_TOKEN = '2T7FBUGWU3EZMQI5LR6TOZ7XJT3PP47W';
// Messenger API parameters
const FB_PAGE_ID = '1626566834232499';
if (!FB_PAGE_ID) {
throw new Error('missing FB_PAGE_ID');
}
const FB_PAGE_TOKEN = 'EAAEBiRHfG04BAOEiPJrPBy2sKAuCT864cSIECn2E45NUVBUZAZCLbUGq4pAZBI72SrmZCYUSr1BZA0RPHIFXWQyKjZBe1eZAopz2iNDp4dP484AXpRSKUk4G7JcFZC4Jsv2hnbL6kFxM9pTdJI0DvfgI2efY3rtfW93VjaNcU5rfhgZDZD';
if (!FB_PAGE_TOKEN) {
throw new Error('missing FB_PAGE_TOKEN');
}
const FB_VERIFY_TOKEN = 'testbot_verify_token';
// Starting our webserver and putting it all together
var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
// Messenger API specific code
// See the Send API reference
// https://developers.facebook.com/docs/messenger-platform/send-api-reference
const fbReq = request.defaults({
uri: 'https://graph.facebook.com/me/messages',
method: 'POST',
json: true,
qs: { access_token: FB_PAGE_TOKEN },
headers: {'Content-Type': 'application/json'},
});
const fbMessage = (recipientId, msg, cb) => {
const opts = {
form: {
recipient: {
id: recipientId,
},
message: msg,
},
};
fbReq(opts, (err, resp, data) => {
if (cb) {
cb(err || data.error && data.error.message, data);
}
});
};
// See the Webhook reference
// https://developers.facebook.com/docs/messenger-platform/webhook-reference
const getFirstMessagingEntry = (body) => {
const val = body.object == 'page' &&
body.entry &&
Array.isArray(body.entry) &&
body.entry.length > 0 &&
body.entry[0] &&
body.entry[0].id === FB_PAGE_ID &&
body.entry[0].messaging &&
Array.isArray(body.entry[0].messaging) &&
body.entry[0].messaging.length > 0 &&
body.entry[0].messaging[0]
;
return val || null;
};
// Wit.ai bot specific code
// This will contain all user sessions.
// Each session has an entry:
// sessionId -> {fbid: facebookUserId, context: sessionState}
const sessions = {};
const findOrCreateSession = (fbid) => {
let sessionId;
// Let's see if we already have a session for the user fbid
Object.keys(sessions).forEach(k => {
if (sessions[k].fbid === fbid) {
// Yep, got it!
sessionId = k;
}
});
if (!sessionId) {
// No session found for user fbid, let's create a new one
sessionId = new Date().toISOString();
sessions[sessionId] = {fbid: fbid, context: {}};
}
return sessionId;
};
const firstEntityValue = (entities, entity) => {
const val = entities && entities[entity] &&
Array.isArray(entities[entity]) &&
entities[entity].length > 0 &&
entities[entity][0].value
;
if (!val) {
return null;
}
return typeof val === 'object' ? val.value : val;
};
// Our bot actions
const actions = {
say(sessionId, context, message, cb) {
// Our bot has something to say!
// Let's retrieve the Facebook user whose session belongs to
const recipientId = sessions[sessionId].fbid;
if (recipientId) {
// Yay, we found our recipient!
// Let's forward our bot response to her.
console.log("Say context:" + JSON.stringify(context));
var elements = getFBElement(context);
console.log("fb msg:" + JSON.stringify(elements));
var msg;
if (message) {
console.log("wit.ai message:", message);
msg = {
text: message,
};
fbMessage(recipientId, msg, (err, data) => {
if (err) {
console.log(
'Oops! An error occurred while forwarding the response to',
recipientId,
':',
err
);
}
});
}
if (elements) {
console.log("there's data for fb");
msg = {
attachment: {
type: "template",
payload: {
"template_type": "generic",
"elements": elements
}
}
};
fbMessage(recipientId, msg, (err, data) => {
if (err) {
console.log(
'Oops! An error occurred while forwarding the response to',
recipientId,
':',
err
);
}
});
}
if (context.defaultMsg) {
var defaultMsg = getDefaultMsg(context);
console.log("default message:", defaultMsg);
msg = {
text: defaultMsg,
};
fbMessage(recipientId, msg, (err, data) => {
if (err) {
console.log(
'Oops! An error occurred while forwarding the response to',
recipientId,
':',
err
);
}
});
}
// Let's give the wheel back to our bot
cb();
} else {
console.log('Oops! Couldn\'t find user for session:', sessionId);
// Giving the wheel back to our bot
cb();
}
},
merge(sessionId, context, entities, message, cb) {
// Retrieve the location entity and store it into a context field
const movieTitle = firstEntityValue(entities, 'wit_movieTitle');
if (movieTitle) {
context.movieTitle = movieTitle;
}
const intent = firstEntityValue(entities, 'intent');
if (intent) {
console.log('*********intent:' + intent);
context.intent = intent;
}
cb(context);
},
error(sessionId, context, error) {
console.log(error.message);
},
// You should implement your custom actions here
// See https://wit.ai/docs/quickstart
['fetch-top-movies'](sessionId, context, cb) {
// Here should go the api call, e.g.:
// context.forecast = apiCall(context.loc)
console.log('*********intent:fetch-top-movies');
getTopMovie(cb);
},
['get-response'](sessionId, context, cb) {
var intent = context.intent;
var movieTitle = context.movieTitle;
console.log('*********intent:' + intent);
console.log('movieTitle:' + movieTitle);
if (intent == 'watch') {
if (movieTitle) {
// return closest movie
context.title = getMovieInfo(movieTitle);
}
else {
// recommendation
context.title = getTopMovie(cb);
}
}
else if (intent == 'review') {
if (movieTitle) {
// review of a movie
console.log('before context:' + context);
getReview(movieTitle, cb)
}
else {
// recommendation
context.title = getTopMovie(cb);
}
}
else if (intent == 'recommendation') {
// recommendation
context.title = getTopMovie(cb);
}
else {
// recommendation
if (movieTitle) {
// Can't find intent but user typed something for a movie
getReview(movieTitle, cb)
}
else {
// No intent no movie title, just response with top movies
context.title = getTopMovie(cb);
}
}
},
['greeting'](sessionId, context, cb) {
console.log("*********indent:greeting");
getGreetingMsg(cb);
},
['get-price'](sessionId, context, cb) {
console.log("*********indent:get-price");
getPrice(context.movieTitle, cb);
},
['similar-movie'](sessionId, context, cb) {
console.log("*********indent:similar-movie");
getSimilarMovie(context.movieTitle, cb);
}
};
// Setting up our bot
const wit = new Wit(WIT_TOKEN, actions);
const app = express();
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.listen((process.env.PORT || 3000));
// Server frontpage
app.get('/', function (req, res) {
res.send('This is TestBot Server');
});
// Facebook Webhook
app.get('/webhook', function (req, res) {
if (req.query['hub.verify_token'] === FB_VERIFY_TOKEN) {
res.send(req.query['hub.challenge']);
} else {
res.send('Invalid verify token');
}
});
// Message handler
app.post('/webhook', (req, res) => {
// Parsing the Messenger API response
const messaging = getFirstMessagingEntry(req.body);
if (messaging && messaging.message && messaging.recipient.id === FB_PAGE_ID) {
// Yay! We got a new message!
// We retrieve the Facebook user ID of the sender
const sender = messaging.sender.id;
// We retrieve the user's current session, or create one if it doesn't exist
// This is needed for our bot to figure out the conversation history
const sessionId = findOrCreateSession(sender);
// We retrieve the message content
const msg = messaging.message.text;
const atts = messaging.message.attachments;
if (atts) {
// We received an attachment
// Let's reply with an automatic message
fbMessage(
sender,
'Sorry I can only process text messages for now.'
);
} else if (msg) {
// We received a text message
// Let's forward the message to the Wit.ai Bot Engine
// This will run all actions until our bot has nothing left to do
wit.runActions(
sessionId, // the user's current session
msg, // the user's message
sessions[sessionId].context, // the user's current session state
(error, context) => {
if (error) {
console.log('Oops! Got an error from Wit:', error);
} else {
// Our bot did everything it has to do.
// Now it's waiting for further messages to proceed.
console.log('Waiting for futher messages.');
// Based on the session state, you might want to reset the session.
// This depends heavily on the business logic of your bot.
// Example:
// if (context['done']) {
// delete sessions[sessionId];
// }
// Updating the user's current session state
sessions[sessionId].context = context;
}
}
);
}
}
res.sendStatus(200);
});
/*
* Postback Event
*
* This event is called when a postback is tapped on a Structured Message. Read
* more at https://developers.facebook.com/docs/messenger-platform/webhook-reference#postback
*
*/
function receivedPostback(event) {
var senderID = event.sender.id;
var recipientID = event.recipient.id;
var timeOfPostback = event.timestamp;
// The 'payload' param is a developer-defined field which is set in a postback
// button for Structured Messages.
var payload = event.postback.payload;
console.log("Received postback for user %d and page %d with payload '%s' " +
"at %d", senderID, recipientID, payload, timeOfPostback);
// When a postback is called, we'll send a message back to the sender to
// let them know it was successful
sendTextMessage(senderID, "Postback called");
}
/*
* Send a text message using the Send API.
*
*/
function sendTextMessage(recipientId, messageText) {
var messageData = {
recipient: {
id: recipientId
},
message: {
text: messageText
}
};
callSendAPI(messageData);
}
/*
* Send a button message using the Send API.
*
*/
function sendButtonMessage(recipientId) {
var messageData = {
recipient: {
id: recipientId
},
message: {
attachment: {
type: "template",
payload: {
template_type: "button",
text: "This is test text",
buttons:[{
type: "web_url",
url: "https://www.oculus.com/en-us/rift/",
title: "Open Web URL"
}, {
type: "postback",
title: "Call Postback",
payload: "Developer defined postback"
}]
}
}
}
};
callSendAPI(messageData);
}
/*
* Call the Send API. The message data goes in the body. If successful, we'll
* get the message id in a response
*
*/
function callSendAPI(messageData) {
request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: { access_token: PAGE_ACCESS_TOKEN },
method: 'POST',
json: messageData
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
var recipientId = body.recipient_id;
var messageId = body.message_id;
console.log("Successfully sent generic message with id %s to recipient %s",
messageId, recipientId);
} else {
console.error("Unable to send message.");
console.error(response);
console.error(error);
}
});
}
function getGreetingMsg(cb) {
var msg = [
"Hello! I hope you are gaving an awesome day!",
"G'day mate!",
"Hello! Today is just awesome, isn't it?",
"Hi to you :)",
"Hello there!",
"Hi there!"
];
cb({"defaultMsg": msg});
}
function sendSearchResult(text) {
console.log('send search result for ' + text);
// var search = text.substring(12, text.lenght);
var encodedSearch = encodeURIComponent(text);
console.log('type of encoded search :', typeof encodedSearch);
console.log('encoded search: ', encodedSearch);
var url_s = `http://apicache.vudu.com/api2/claimedAppId/myvudu/format/application*2Fjson/_type/contentSearch/count/1/dimensionality/any/followup/ratingsSummaries/includeComingSoon/true/includePreOrders/true/offset/0/streamable/true/titleMagic/${encodedSearch}/type/program/type/season/type/episode/type/bundle/type/bonus/type/series`;
console.log('type of url: ', typeof url_s);
request({
url: url_s,
method: 'GET'
}, function(error, response, body) {
if (error) {
console.log('*******Error sending message: ', error);
} else if (response.body) {
var sub = response.body.substring(10, response.body.length - 2);
var evaluation = eval('(' + sub + ')');
// get first search result
var contentId = evaluation.content[0].contentId[0];
var title = evaluation.content[0].title[0];
var description = evaluation.content[0].description[0];
console.log("found it! " + title + "id:" + contentId);
return contentId;
}
});
};
function getTopMovie(cb) {
var url_s = 'http://apicache.vudu.com/api2/claimedAppId/myvudu/format/application*2Fjson/_type/contentSearch/count/30/dimensionality/any/offset/0/sortBy/-watchedScore/superType/movies/type/program/type/bundle/followup/totalCount';
var contentArray = [];
rp(url_s)
.then(function (response) {
// console.log('in getTopMovie - got response:' + response);
if (response) {
var sub = response.substring(10, response.length - 2);
var evaluation = eval('(' + sub + ')');
var totalCount = evaluation.totalCount[0];
console.log('totalCount:' + totalCount);
// get first search result
if (parseInt(totalCount) <= 0 && parseInt(totalCount) > 30) {
console.log('something is wrong with getTopMovie totalCount');
}
else {
// Get random 3 top movies
var randomIndex =[];
for (var i = 0; i < 3; i++) {
var randomNum = getRandomInt(0,9) + i * 10;
randomIndex[i] = randomNum;
}
for (var i = 0; i < 3; i++) {
var randomNum = randomIndex[i];
// console.log("get top movie:" + randomNum);
var vuduContent = {};
vuduContent.contentId = evaluation.content[randomNum].contentId[0];
vuduContent.title = evaluation.content[randomNum].title[0];
vuduContent.description = evaluation.content[randomNum].description[0];
vuduContent.tomatoMeter = evaluation.content[randomNum].tomatoMeter[0];
contentArray[i] = vuduContent;
console.log("found it! " + vuduContent.title + "/id:" + vuduContent.contentId);
}
// Need to handle if there's no review
// console.log(JSON.stringify(msg));
cb({"Action": contentArray});
}
}
})
.catch(function (err) {
console.log('---*******Error sending message: ', err);
});
};
function getMovieInfo(text) {
console.log('send search result for ' + text);
// var search = text.substring(12, text.lenght);
var encodedSearch = encodeURIComponent(text);
console.log('type of encoded search :', typeof encodedSearch);
console.log('encoded search: ', encodedSearch);
var url_s = 'http://apicache.vudu.com/api2/claimedAppId/myvudu/format/application*2Fjson/_type/contentMetaSearch/phrase/'+ encodedSearch + '/includePreOrders/true/followup/totalCount';
request({
url: url_s,
method: 'GET'
}, function(error, response, body) {
if (error) {
console.log('*******Error sending message: ', error);
} else if (response.body) {
var sub = response.body.substring(10, response.body.length - 2);
var evaluation = eval('(' + sub + ')');
console.log('result:' + response.body);
// get first search result
try {
var contentId = evaluation.content[0].contentId[0];
var title = evaluation.content[0].title[0];
var description = evaluation.content[0].description[0];
// Need to handle if there's no review
console.log("found it! " + title + "/id:" + contentId);
var url_s = 'http://apicache.vudu.com/api2/claimedAppId/myvudu/format/application*2Fjson/_type/contentSearch/contentId/' + contentId ;
request({
url: url_s,
method: 'GET'
}, function(error, response, body) {
if (error) {
console.log('*******Error sending message: ', error);
} else if (response.body) {
var sub = response.body.substring(10, response.body.length - 2);
var evaluation = eval('(' + sub + ')');
var randomNum = getRandomInt(1,30);
var id = evaluation.content[randomNum].contentId[0];
var title = evaluation.content[randomNum].title[0];
var description = evaluation.content[randomNum].description[0];
console.log("found search title! " + title);
return title;
}
});
}
catch(err) {
return "Sorry! No movie found!";
}
}
});
};
function getContentSimilarSearch(vuduContent) {
console.log("called getContentSimilarSearch");
var contentId = vuduContent.contentId;
var url_s = 'http://apicache.vudu.com/api2/claimedAppId/myvudu/format/application*2Fjson/_type/contentSimilarSearch/contentId/' + contentId +'/count/10/followup/totalCount';
return rp(url_s)
.then(function (response) {
console.log('in getContentSimilarSearch - got response:' + response);
if (response) {
var sub = response.substring(10, response.length - 2);
var evaluation = eval('(' + sub + ')');
var totalCount = evaluation.totalCount[0];
// get first search result
if (parseInt(totalCount) === 0) {
console.log('cannot find a similar movie for contentId:' + contentId);
}
else {
var similarMoviesArray = [];
for (var i = 0; i < evaluation.content.length; i ++) {
var movieElement = {};
movieElement.title = evaluation.content[i].title[0];
movieElement.contentId = evaluation.content[i].contentId[0];
movieElement.releaseTime = evaluation.content[i].releaseTime[0];
movieElement.mpaaRating = evaluation.content[i].mpaaRating[0];
similarMoviesArray[i] = movieElement;
console.log( i,"-similar movie:", JSON.stringify(movieElement));
}
console.log("before the final:", similarMoviesArray);
return similarMoviesArray;
}
}
else {
console.log("getContentSimilarSearch - something went wrong");
}
})
.catch(function (err) {
console.log('*******getContentSimilarSearch-Error sending message: ', err);
});
}
function getTomatoReview(vuduContent) {
console.log("called getTomatoReview");
var contentId = vuduContent.contentId;
var url_review = 'http://apicache.vudu.com/api2/claimedAppId/myvudu/format/application*2Fjson/_type/tomatoReviewSearch/contentId/' + contentId + '/sortBy/isByTopAuthor/followup/totalCount';
console.log("About to call:", url_review);
return rp(url_review)
.then(function (response) {
console.log('in getTomatoReview - got response:' + response);
if (response) {
var sub = response.substring(10, response.length - 2);
var evaluation = eval('(' + sub + ')');
var totalCount = evaluation.totalCount[0];
console.log('totalCount:' + totalCount);
// get first search result
if (parseInt(totalCount) === 0) {
console.log('cannot find a review for contentId:' + contentId);
}
else {
var reviewArray = [];
vuduContent.reviewComment = evaluation.tomatoReview[0].comment[0];
vuduContent.reviewAuthor = evaluation.tomatoReview[0].author[0];
vuduContent.reviewSource = evaluation.tomatoReview[0].source[0];
vuduContent.reviewURL = evaluation.tomatoReview[0].url[0];
reviewArray[0] = vuduContent;
return reviewArray;
}
}
else {
console.log("getTomatoReview - something went wrong");
}
})
.catch(function (err) {
console.log('*******getTomatoReview-Error sending message: ', err);
});
}
function getReview(text, cb) {
console.log('send search result for ' + text);
// var search = text.substring(12, text.lenght);
var encodedSearch = encodeURIComponent(text);
console.log('type of encoded search :', typeof encodedSearch);
console.log('encoded search: ', encodedSearch);
var url_s = 'http://apicache.vudu.com/api2/claimedAppId/myvudu/format/application*2Fjson/_type/contentMetaSearch/phrase/'+ encodedSearch + '/includePreOrders/true/followup/totalCount/count/3';
rp(url_s)
.then(function (response) {
console.log('in GetReview - got response:' + response);
if (response) {
var sub = response.substring(10, response.length - 2);
var evaluation = eval('(' + sub + ')');
var totalCount = evaluation.totalCount[0];
console.log('totalCount:' + totalCount);
// get first search result
if (parseInt(totalCount) === 0) {
console.log('cannot find a matching movie');
}
else {
var vuduContent = {};
vuduContent.contentId = evaluation.content[0].contentId[0];
vuduContent.title = evaluation.content[0].title[0];
console.log("found it! " + vuduContent.title + "/id:" + vuduContent.contentId);
// Need to handle if there's no review
// console.log(JSON.stringify(msg));
return vuduContent;
}
}
else {
console.log("getReview - something went wrong");
}
})
.then(function (vuduContent) {
return getMovieDetail(vuduContent);
})
.then(function (vuduContent) {
return getTomatoReview(vuduContent);
})
.then(function (reviewArray) {
cb({"Action": reviewArray});
})
.catch(function (err) {
cb(setDefaultMsg());
console.log('*******Error sending message: ', err);
});
}
function setDefaultMsg() {
var msg = {
defaultMsg: [
"Sorry, I am not smart enough to understand what you are saying, do you mind trying again?",
"Sorry, a human being will look through all the messages and provide the right support.",
"Sorry, are you asking anything regarding to movies or TVs? Perhaps try different ones?"]
}
return msg;
}
function getDefaultMsg(msgDict) {
console.log("getDefaultsg:", JSON.stringify(msgDict));
var msgArray = msgDict["defaultMsg"];
if (msgArray) {
var randomNum = getRandomInt(0, msgArray.length - 1);
return msgArray[randomNum];
}
else {
console.log("something is wrong with default msg");
}
}
function getMovieDetail(vuduContent) {
console.log("called getMovieDetail");
var contentId = vuduContent.contentId;
var url_review = 'http://apicache.vudu.com/api2/claimedAppId/myvudu/format/application*2Fjson/_type/contentSearch/contentId/' + contentId + '/followup/totalCount/followup/mpaaRating';
return rp(url_review)
.then(function (response) {
console.log('in getMovieDetail - got response:' + response);
if (response) {
var sub = response.substring(10, response.length - 2);
var evaluation = eval('(' + sub + ')');
var totalCount = evaluation.totalCount[0];
console.log('totalCount:' + totalCount);
// get first search result
if (parseInt(totalCount) === 0) {
console.log('cannot find a review for contentId:' + contentId);
}
else {
vuduContent.description = evaluation.content[0].description[0] ? evaluation.content[0].description[0] : "";
vuduContent.releaseTime = evaluation.content[0].releaseTime[0] ? evaluation.content[0].releaseTime[0] : "";
vuduContent.mpaaRating = evaluation.content[0].mpaaRating[0] ? evaluation.content[0].mpaaRating[0] : "";
vuduContent.tomatoMeter = evaluation.content[0].tomatoMeter[0] ? evaluation.content[0].tomatoMeter[0] : "";
return vuduContent;
}
}
else {
console.log("getMovieDetail - something went wrong");
}
})
.catch(function (err) {
console.log('*******getMovieDetail-Error sending message: ', err);
});
}
// This should return an array
function getFBElement(contents) {
var msgArray = contents["Action"];
var outputArray = [];
if (msgArray != null) {
console.log("in getFBElement-if");
for (var i = 0; i < msgArray.length; i++) {
var vuduContent = msgArray[i];
var title = vuduContent.title;
var description = vuduContent.description;
var contentId = vuduContent.contentId;
var element = {
"title": title,
"subtitle": (description != null) ? description : "Release Date:" + vuduContent.releaseTime + " Rating:" + vuduContent.mpaaRating ,
"image_url": "http://images2.vudu.com/poster2/" + contentId + "-l",
"buttons": [{
"type": "web_url",
"url": "http://www.vudu.com/movies/#!content/" + contentId,
"title": "View Details"
}]
};
outputArray[i] = element;
}
return outputArray;
}
else {
console.log("in getFBElement-else");
// No custom action data found, could be wit.ai reply
return;
}
}
function getSimilarMovie(text, cb) {
var encodedSearch = encodeURIComponent(text);
console.log('encoded search: ', encodedSearch);
var url_s = 'http://apicache.vudu.com/api2/claimedAppId/myvudu/format/application*2Fjson/_type/contentMetaSearch/phrase/'+ encodedSearch + '/includePreOrders/true/followup/totalCount/count/3';
rp(url_s)
.then(function (response) {
console.log('in getSimilarMovie - got response:' + response);
if (response) {
var sub = response.substring(10, response.length - 2);
var evaluation = eval('(' + sub + ')');
var totalCount = evaluation.totalCount[0];
console.log('totalCount:' + totalCount);
// get first search result
if (parseInt(totalCount) === 0) {
console.log('cannot find a matching movie');
}
else {
var vuduContent = {};
vuduContent.contentId = evaluation.content[0].contentId[0];
vuduContent.title = evaluation.content[0].title[0];
console.log("found it! " + vuduContent.title + "/id:" + vuduContent.contentId);
return vuduContent;
}
}
else {
console.log("getSimilarMovie - something went wrong");
}
})
.then(function(vuduContent) {
return getContentSimilarSearch(vuduContent);
})
.then(function(similarMoviesArray) {
console.log("final then!");
console.log("final array,", similarMoviesArray);
cb({"Action": similarMoviesArray});
})
.catch(function (err) {
console.log('*******Error sending message: ', err);
});
}
function getPrice(text, cb) {
console.log('send search result for ' + text);
// var search = text.substring(12, text.lenght);
var encodedSearch = encodeURIComponent(text);
console.log('type of encoded search :', typeof encodedSearch);
console.log('encoded search: ', encodedSearch);
var url_s = 'http://apicache.vudu.com/api2/claimedAppId/myvudu/format/application*2Fjson/_type/contentMetaSearch/phrase/'+ encodedSearch + '/includePreOrders/true/followup/totalCount/count/3';
rp(url_s)
.then(function (response) {
console.log('in getPrice - got response:' + response);
if (response) {
var sub = response.substring(10, response.length - 2);
var evaluation = eval('(' + sub + ')');
var totalCount = evaluation.totalCount[0];
console.log('totalCount:' + totalCount);
// get first search result
if (parseInt(totalCount) === 0) {
console.log('cannot find a matching movie');
}
else {
var vuduContent = {};
vuduContent.contentId = evaluation.content[i].contentId[0];
vuduContent.title = evaluation.content[i].title[0];
console.log("found it! " + vuduContent.title + "/id:" + vuduContent.contentId);
// Need to handle if there's no review
// console.log(JSON.stringify(msg));
return vuduContent;
}
}
else {
console.log("getPrice - something went wrong");
}
})
.then(function(vuduContent) {
return getPriceInfo(vuduContent);
})
.then(function(vuduContent) {
cb(vuduContent);
})
.catch(function (err) {
console.log('*******Error sending message: ', err);
});
}
function getPriceInfo(vuduContent) {
console.log("called getPriceInfo");
var contentId = vuduContent.contentId;
var url_review = 'http://apicache.vudu.com/api2/claimedAppId/myvudu/format/application*2Fjson/_type/contentSearch/contentId/' + contentId + '/followup/totalCount/followup/offers';
return rp(url_review)
.then(function (response) {
console.log('in getPriceInfo - got response:' + response);
if (response) {
var sub = response.substring(10, response.length - 2);
var evaluation = eval('(' + sub + ')');
var totalCount = evaluation.totalCount[0];
console.log('totalCount:' + totalCount);
// get first search result
if (parseInt(totalCount) === 0) {
console.log('cannot find the price for contentId:' + contentId);
}
else {
var ptoArray = []; //[sdPrice, hdPrice, hdxPrice]
var ptrArray = [];
for (var i = 0; i < evaluation.content[0].contentVariants[0].contentVariant.length; i++) {