Skip to content

Commit 58280af

Browse files
committed
HUGE milestone. Auth token is now read from database!
Still just POC
1 parent 4b84635 commit 58280af

File tree

4 files changed

+94
-95
lines changed

4 files changed

+94
-95
lines changed

deploy.bat

+2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
REM Requires AWS CLI installed: https://aws.amazon.com/cli/
2+
REM Requires 7z installed, and 7z.exe added to your PATH
13
@echo off
24
rmdir dist\install /S /Q
35
mkdir dist\install

index.js

+41-76
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@ var dice = require('clj-fuzzy').metrics.dice;
44
var alexa = require('alexa-app');
55
var app = new alexa.app('plex');
66
var plexAPI = require('plex-api');
7-
var AWS = require('aws-sdk');
7+
var PlexPinAuth = require('plex-api-pinauth');
8+
var db = require('./lib/db.js');
89

910
var CONFIDICE_CONFIRM_THRESHOLD = 0.4;
1011

@@ -15,11 +16,14 @@ var plexOptions = {
1516
deviceName: process.env.APP_DEVICE_NAME,
1617
identifier: process.env.APP_IDENTIFIER
1718
};
19+
20+
var pinAuth = new PlexPinAuth();
1821
var plex = new plexAPI({
1922
hostname: process.env.PMS_HOSTNAME,
20-
username: process.env.PMS_USERNAME,
23+
//username: process.env.PMS_USERNAME,
2124
port: process.env.PMS_PORT,
22-
password: process.env.PMS_PASSWORD,
25+
//password: process.env.PMS_PASSWORD,
26+
authenticator: pinAuth,
2327
options: plexOptions
2428
});
2529

@@ -28,10 +32,9 @@ var plex = new plexAPI({
2832
plex.authToken = process.env.PMS_AUTHTOKEN;
2933

3034
// Connect the alexa-app to AWS Lambda
31-
//exports.handler = app.lambda();
3235
exports.handler = function(event, context) {
33-
34-
console.log("Request:", event.request);
36+
console.log("Request: ", event.request);
37+
console.log("Session: ", event.session);
3538

3639
if(event.request.intent) {
3740
if(event.request.intent.slots) {
@@ -64,87 +67,49 @@ app.launch(function(request,response) {
6467
// response.send();
6568
//};
6669

67-
app.intent('DBTestIntents', function(request, response) {
68-
AWS.config.update({
69-
region: "us-east-1",
70-
endpoint: "http://localhost:8000"
71-
});
72-
73-
var dynamodb = new AWS.DynamoDB();
74-
75-
var params = {
76-
TableName : "AlexaPlexUsers",
77-
KeySchema: [
78-
{ AttributeName: "userid", KeyType: "HASH"}, //Partition key
79-
],
80-
AttributeDefinitions: [
81-
{ AttributeName: "userid", AttributeType: "S" },
82-
],
83-
ProvisionedThroughput: {
84-
ReadCapacityUnits: 10,
85-
WriteCapacityUnits: 10
86-
}
87-
};
88-
89-
dynamodb.createTable(params, function(err, data) {
90-
if (err) {
91-
console.error("Unable to create table. Error JSON:", JSON.stringify(err, null, 2));
70+
app.intent('OnDeckIntent', function(request,response) {
71+
db.initializeUserRecord(request.data.session.user.userId).then(function(user) {
72+
console.log("All is good!");
73+
if(!user.authtoken) {
74+
response.say("You do not have an auth token. Please run setup. Note: setup doesn't exist yet!");
75+
response.send();
9276
} else {
93-
console.log("Created table. Table description JSON:", JSON.stringify(data, null, 2));
94-
}
77+
// User is authed
9578

96-
var getItemParams = {
97-
"TableName": "AlexaPlexUsers",
98-
"Key": {
99-
"userid": {
100-
"S": request.userId
79+
//pinAuth.token = user.authtoken;
80+
81+
plex.query('/library/onDeck').then(function(result) {
82+
if(result._children.length === 0) {
83+
response.say("You do not have any shows On Deck!");
84+
return response.send();
10185
}
102-
}
103-
};
10486

105-
dynamodb.getItem(getItemParams, function(err, data) {
106-
if (err) {
107-
console.error("Unable to query. Error:", JSON.stringify(err, null, 2));
108-
} else {
109-
console.log("Query succeeded.");
110-
console.log(data);
111-
//data.Items.forEach(function(item) {
112-
// console.log(" -", item.year + ": " + item.title);
113-
//});
114-
}
115-
});
116-
});
87+
var shows = [];
11788

118-
return false; // This is how you tell alexa-app that this intent is async.
119-
});
89+
for(i = 0; i < result._children.length && i < 6; i++) {
90+
shows.push(result._children[i].grandparentTitle);
91+
}
12092

121-
app.intent('OnDeckIntent', function(request,response) {
122-
plex.query('/library/onDeck').then(function(result) {
93+
var showsPhraseHyphenized = buildNaturalLangList(shows, 'and', true);
94+
var showsPhrase = buildNaturalLangList(shows, 'and');
12395

124-
if(result._children.length === 0) {
125-
response.say("You do not have any shows On Deck!");
126-
return response.send();
127-
}
96+
//console.log(result);
12897

129-
var shows = [];
98+
response.say("On deck you've got " + showsPhraseHyphenized + '.');
99+
response.card('Plex', showsPhrase + '.', 'On Deck');
100+
return response.send();
101+
}).catch(function(err) {
102+
console.log("ERROR from Plex API on Query /library/onDeck");
103+
console.log(err);
104+
response.say("I'm sorry, Plex and I don't seem to be getting along right now");
105+
return response.send();
106+
});
130107

131-
for(i = 0; i < result._children.length && i < 6; i++) {
132-
shows.push(result._children[i].grandparentTitle);
133108
}
134-
135-
var showsPhraseHyphenized = buildNaturalLangList(shows, 'and', true);
136-
var showsPhrase = buildNaturalLangList(shows, 'and');
137-
138-
//console.log(result);
139-
140-
response.say("On deck you've got " + showsPhraseHyphenized + '.');
141-
response.card('Plex', showsPhrase + '.', 'On Deck');
142-
response.send();
143109
}).catch(function(err) {
144-
console.log("ERROR from Plex API on Query /library/onDeck");
145-
console.log(err);
146-
response.say("I'm sorry, Plex and I don't seem to be getting along right now");
147-
response.send();
110+
console.error(err);
111+
response.say("There was a database error. Try again later!");
112+
response.send()
148113
});
149114

150115
return false; // This is how you tell alexa-app that this intent is async.

lib/db.js

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
var Q = require('q');
2+
var AWS = require('aws-sdk');
3+
AWS.config.update({
4+
region: process.env.AWS_REGION || "us-east-1"
5+
});
6+
7+
if(process.env.NODE_ENV == 'test') {
8+
AWS.config.update({
9+
endpoint: process.env.AWS_ENDPOINT || "http://localhost:8000"
10+
});
11+
}
12+
13+
function initializeUserRecord(userid) {
14+
var dynamodbDoc = new AWS.DynamoDB.DocumentClient();
15+
var deferred = Q.defer();
16+
17+
var getItemParams = {
18+
TableName: "AlexaPlexUsers",
19+
Key: { "userid": userid }
20+
};
21+
22+
console.log("Looking for record in DB matching userid", userid);
23+
dynamodbDoc.get(getItemParams, function(err, data) {
24+
if (err) {
25+
return deferred.reject(err);
26+
} else {
27+
if(!data.Item) {
28+
// User not in database yet. Let's create a row for them.
29+
var putParams = {
30+
TableName: "AlexaPlexUsers",
31+
Item: { userid: userid }
32+
};
33+
dynamodbDoc.put(putParams, function(err, data) {
34+
if (err) {
35+
callback(err);
36+
} else {
37+
// Inserted new user ID; all is good
38+
return deferred.fulfill(putParams.Item);
39+
}
40+
})
41+
} else {
42+
// Found existing record; all is good
43+
// TODO: set auth token from this response
44+
return deferred.fulfill(data.Item);
45+
}
46+
}
47+
});
48+
return deferred.promise;
49+
}
50+
51+
exports.initializeUserRecord = initializeUserRecord;

test/requests.test.js

-19
Original file line numberDiff line numberDiff line change
@@ -67,25 +67,6 @@ describe('Requests', function() {
6767
this.request.request.type = 'IntentRequest';
6868
});
6969

70-
// HACK: debug code
71-
describe('Temp Debug intents', function() {
72-
beforeEach(function() {
73-
this.request.request.intent.name = 'DBTestIntents';
74-
});
75-
76-
it.only('should connect to DynamoDB', function (done) {
77-
this.lambda.handler(this.request, {
78-
succeed: function (res) {
79-
console.log(res);
80-
expect(res).to.not.have.deep.property('response.outputSpeech.text');
81-
done();
82-
}, fail: function(res) {
83-
done(new Error('Lambda function failed: ' + err));
84-
}
85-
});
86-
});
87-
});
88-
8970
describe('Prompts', function() {
9071
beforeEach(function() {
9172
this.request.request.intent.name = 'OnDeckIntent';

0 commit comments

Comments
 (0)