summaryrefslogtreecommitdiffstats
path: root/htdocs/amazon.js
blob: 05704f170fb8f4b856c8ee7e227ffbde573a52df (plain)
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
/*
 * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *     http://aws.amazon.com/apache2.0/
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */
AMAZON = function() {

var afb;
var alexaWs;

var base = {
  base: "api",
  token: "HELLO",
};

// GUID generator for generating device serial number.
function guid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
}

/*********************************************/
/****                                     ****/
/****             AMAZON_cbl              ****/
/****                                     ****/
/*********************************************/
var AMAZON_Cbl;
{
  const amazonHostUrl = "https://api.amazon.com";
  const amazonCodePairUrl = amazonHostUrl + "/auth/O2/create/codepair";
  const amazonTokenUrl    = amazonHostUrl + "/auth/O2/token";
  const deviceSerialNumber = guid();
  var clientID = localStorage.getItem("client_id");
  var productID = localStorage.getItem("product_id");
  var alexaVAAddress = localStorage.getItem("alexa_va_address");
  var alexaVAConnected = false;
  var alexaVAAddressInput;
  var clientIDInput;
  var productIDInput;

  AMAZON_Cbl = function() {
    // Alexa VA Address
    const alexaVAAddressInput = document.getElementById('alexa-va-address');
    alexaVAAddress = alexaVAAddressInput.value;
    connectToAlexaVA(alexaVAAddress);

    alexaVAAddressInput.addEventListener("change",(evt) => {
      var newAlexaVAAddress = alexaVAAddressInput.value;
      if (alexaVAAddress != newAlexaVAAddress) {
        connectToAlexaVA(newAlexaVAAddress);
        localStorage.setItem("alexa_va_address", newAlexaVAAddress);
      }
    });

    // Client ID
    const clientIDInput = document.getElementById('client-id');
    clientIDInput.addEventListener("change",(evt) => {
      var newClientID = clientIDInput.value;
      if (clientID != newClientID) {
        clientID = newClientID;
        localStorage.setItem("client_id", newClientID);
      }
    });

    // Product ID
    const productIDInput = document.getElementById('product-id');
    productIDInput.addEventListener("change",(evt) => {
      var newProductID = productIDInput.value;
      if (productID != newProductID) {
        productID = newProductID;
        localStorage.setItem("product_id", newProductID);
      }
    });
  }

  function connectToAlexaVA(address) {
    base.host = address;
    afb = new AFB(base, "secret");

    function onopen() {
      console.log("Connected to Alexa VA");
      alexaVAConnected = true;
    }

    function onabort() {
      console.log("Alexa VA connection aborted.");
      alexaVAConnected = false;
    }

    alexaWs = new afb.ws(onopen, onabort);
  }

  function sendRequest(httpReq, paramsJson, url, responseCb) {
    httpReq.onreadystatechange = responseCb;
    var paramsQueryString = Object.keys(paramsJson).map(key => key + '=' + paramsJson[key]).join('&');
    httpReq.open("POST", url, true);
    httpReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    httpReq.send(paramsQueryString);
  }

  //**********************************************
  // Generic function to call VA binder
  //***********************************************
  function callVABinder(voiceAgent, verb, query) {
    console.log(voiceAgent.api, verb, query);

    // ws.call return a Promise
    return alexaWs.call(voiceAgent.api + '/' + verb, query)
      .then(function (res) {
        log.reply(res);
        count++;
        return res;
      })
      .catch(function (err) {
        log.reply(err);
        count++;
        throw err;
      });
  };

  function updateAccessToken(voiceAgent, tokenResponseJson) {
    if (alexaVAAddress === undefined || alexaVAAddress === null) {
      console.log("No Alexa VA. So not updating the access token.");
      return;
    }

    // store the access and refresh tokens.
    if (typeof(Storage) !== "undefined") {
      localStorage.setItem("access_token", tokenResponseJson["access_token"]);
      localStorage.setItem("refresh_token", tokenResponseJson["refresh_token"]);
    }

    // Set the auth token
    if (alexaVAConnected) {
      // Set new token
      const query = {"token": tokenResponseJson["access_token"]};
      callVABinder(voiceAgent, 'setAuthToken', query);
    }

    // Refresh the token as soon as it expires.
    setTimeout(refreshToken, tokenResponseJson["expires_in"] * 1000);
  }

  function refreshToken(voiceAgent) {
    if (voiceAgent == "undefined") {
      console.log("Error: VoiceAgent undefined");
      return;
    }

    var refreshToken = localStorage.getItem("refresh_token");
    if (refreshToken == null) {
      console.log("Error: No refresh token");
      return;
    }

    var paramsJson = {
      "grant_type":"refresh_token",
      "refresh_token":refreshToken,
      "client_id":clientID,
    };

    const tokenRefreshReq = new XMLHttpRequest();
    sendRequest(tokenRefreshReq, paramsJson, amazonTokenUrl, function() {
      if (tokenRefreshReq.readyState == 4) {
        if (tokenRefreshReq.status == 200) {
          console.log("Got access token " + tokenRefreshReq.responseText);
          var tokenResponseJson = JSON.parse(tokenRefreshReq.responseText);
          updateAccessToken(voiceAgent, tokenResponseJson);
        } else {
          console.log("Failed to refresh access token: " + tokenRefreshReq.responseText);
        }
      }
    });
  }

  function displayUserCodeAndURI(authResponseJson) {
    const modal = document.getElementById('login-with-amazon');
    const cblStatusDiv = document.createElement("div");
    const cblStatusMsg = document.createElement("p");
    const blank = "_blank";

    var cblPage = authResponseJson["verification_uri"] + "?cbl-code=" + authResponseJson["user_code"]
    var msg = "To use Alexa,you must sign in to Amazon.<br> Go to " +
        "<a href=" + cblPage + "  target="+ blank+ " >" +
        cblPage + "</a>";
    cblStatusMsg.innerHTML = msg;
    cblStatusDiv.appendChild(cblStatusMsg);
    modal.appendChild(cblStatusDiv);

    const closeBtn = document.createElement("button");
    closeBtn.addEventListener('click', (evt) => {
      modal.close();
    });
    closeBtn.style = "margin: 10px";
    closeBtn.innerHTML = "Close";
    modal.appendChild(closeBtn);
  }

  function hideLoginUI() {
    const loginDiv = document.getElementById('login-area');
    loginDiv.style.display = "none";
  }

  function login(voiceAgent) {
    if (voiceAgent == undefined) {
      console.log("Error: VoiceAgent undefined");
      return;
    }

    const modal = document.getElementById('login-with-amazon');
    const submitBtn = document.getElementById('submit-btn');
    const cancelBtn = document.getElementById('cancel-btn');
    submitBtn.addEventListener('click', (evt) => {
      console.log("Alexa Destination address set to: " + alexaVAAddress);
      startLoginProcess(voiceAgent);
    });

    cancelBtn.addEventListener('click', (evt) => {
      modal.close();
    });

    const alexaVAAddressInput = document.getElementById('alexa-va-address');
    alexaVAAddressInput.value = alexaVAAddress;

    const clientIDInput = document.getElementById('client-id');
    clientIDInput.value = clientID;

    const productIDInput = document.getElementById('product-id');
    productIDInput.value = productID;

    modal.showModal();
  }

  function startLoginProcess(voiceAgent) {
    if (clientID == null || productID == null || alexaVAAddress == null) {
      console.log("Required information missing to start login process.");
      return;
    }

    var reqJson = {
      "response_type": "device_code",
      "client_id": clientID,
      "scope":"alexa:all",
      "scope_data": JSON.stringify({
        "alexa:all": {
          "productID":productID,
          "productInstanceAttributes" : {
            "deviceSerialNumber": deviceSerialNumber
          }
        }
      })
    };

    const authReq = new XMLHttpRequest();
    var tokenUrl = amazonTokenUrl;
    sendRequest(authReq, reqJson, amazonCodePairUrl, function() {
      if (authReq.readyState == 4) {
        if (authReq.status == 200) {
          var authResponse = JSON.parse(authReq.responseText);
          console.log("Got auth codepair " + authReq.responseText);
          hideLoginUI();
          displayUserCodeAndURI(authResponse);
          var maxTokenReqCnt = authResponse["expires_in"] / authResponse["interval"];
          var tokenReqFuncId = setTimeout(function tokenReqFunc() {
            var reqJson = {
              "grant_type":"device_code",
              "device_code":authResponse["device_code"],
              "user_code":authResponse["user_code"]
            };
            const tokenReq = new XMLHttpRequest();
            sendRequest(tokenReq, reqJson, tokenUrl, function() {
              if (tokenReq.readyState == 4) {
                if (tokenReq.status == 200) {
                  console.log("Got access token " + tokenReq.responseText);
                  var tokenResponseJson = JSON.parse(tokenReq.responseText);
                  updateAccessToken(voiceAgent, tokenResponseJson);
                }
                else {
                  maxTokenReqCnt--;
                  console.log("Retrying... " + tokenReq.responseText);
                  setTimeout(tokenReqFunc, authResponse["interval"] * 1000);
                }
              }
            });
          }, authResponse["interval"] * 1000);
          // Cancel if max token request attempts are reached.
          if (maxTokenReqCnt == 0) {
            console.log("Reached max token request attemps limit.");
          }
        } else {
          console.log(authReq.status);
        }
      }
    });
  }

  AMAZON_Cbl.prototype = {
    login: login,
    refreshToken: refreshToken,
  };
}
/*********************************************/
/****                                     ****/
/****                                     ****/
/****                                     ****/
/*********************************************/
return {
  cbl: AMAZON_Cbl
};
};