- [[localize('ui.panel.mailbox.delete_prompt')]]
-
-
`;
}
@@ -176,15 +131,19 @@ class HaPanelMailbox extends LocalizeMixin(PolymerElement) {
_messages: {
type: Array,
},
-
- currentMessage: {
- type: Object,
- },
};
}
connectedCallback() {
super.connectedCallback();
+ if (!registeredDialog) {
+ registeredDialog = true;
+ this.fire('register-dialog', {
+ dialogShowEvent: 'show-audio-message-dialog',
+ dialogTag: 'ha-dialog-show-audio-message',
+ dialogImport: () => import('./ha-dialog-show-audio-message.js'),
+ });
+ }
this.hassChanged = this.hassChanged.bind(this);
this.hass.connection.subscribeEvents(this.hassChanged, 'mailbox_updated')
.then(function (unsub) { this._unsubEvents = unsub; }.bind(this));
@@ -209,35 +168,19 @@ class HaPanelMailbox extends LocalizeMixin(PolymerElement) {
}
openMP3Dialog(event) {
- var platform = event.model.item.platform;
- this.currentMessage = event.model.item;
- this.$.mp3dialog.open();
- this.$.mp3src.src = '/api/mailbox/media/' + platform + '/' + event.model.item.sha;
- this.$.transcribe.innerText = event.model.item.message;
- this.$.mp3.load();
- this.$.mp3.play();
+ this.fire('show-audio-message-dialog', {
+ hass: this.hass,
+ message: event.model.item,
+ });
}
- _mp3Closed() {
- this.$.mp3.pause();
- }
-
- openDeleteDialog() {
- this.$.confirmdel.open();
- }
-
- deleteSelected() {
- var msg = this.currentMessage;
- this.hass.callApi('DELETE', 'mailbox/delete/' + msg.platform + '/' + msg.sha);
- this.$.mp3dialog.close();
- }
getMessages() {
const items = this.platforms.map(function (platform) {
- return this.hass.callApi('GET', 'mailbox/messages/' + platform).then(function (values) {
- var platformItems = [];
- var arrayLength = values.length;
- for (var i = 0; i < arrayLength; i++) {
- var datetime = formatDateTime(new Date(values[i].info.origtime * 1000));
+ return this.hass.callApi('GET', `mailbox/messages/${platform}`).then(function (values) {
+ const platformItems = [];
+ const arrayLength = values.length;
+ for (let i = 0; i < arrayLength; i++) {
+ const datetime = formatDateTime(new Date(values[i].info.origtime * 1000));
platformItems.push({
timestamp: datetime,
caller: values[i].info.callerid,
@@ -251,15 +194,9 @@ class HaPanelMailbox extends LocalizeMixin(PolymerElement) {
});
}.bind(this));
return Promise.all(items).then(function (platformItems) {
- var arrayLength = items.length;
- var final = [];
- for (var i = 0; i < arrayLength; i++) {
- final = final.concat(platformItems[i]);
- }
- final.sort(function (a, b) {
+ return [].concat(...platformItems).sort(function (a, b) {
return new Date(b.timestamp) - new Date(a.timestamp);
});
- return final;
});
}
diff --git a/src/util/fetch-with-auth.js b/src/util/fetch-with-auth.js
new file mode 100644
index 0000000000..d51daca750
--- /dev/null
+++ b/src/util/fetch-with-auth.js
@@ -0,0 +1,9 @@
+export const fetchWithAuth = async (auth, input, init = {}) => {
+ if (auth.expired) await auth.refreshAccessToken();
+ init.credentials = 'same-origin';
+ if (!init.headers) {
+ init.headers = {};
+ }
+ init.headers.authorization = `Bearer ${auth.accessToken}`;
+ return await fetch(input, init);
+};
diff --git a/src/util/hass-call-api.js b/src/util/hass-call-api.js
index 4d31f14054..6d6b696cf3 100644
--- a/src/util/hass-call-api.js
+++ b/src/util/hass-call-api.js
@@ -1,52 +1,57 @@
-export default function hassCallApi(host, auth, method, path, parameters) {
- var url = host + '/api/' + path;
+import { fetchWithAuth } from './fetch-with-auth.js';
- return new Promise(function (resolve, reject) {
- var req = new XMLHttpRequest();
- req.open(method, url, true);
- req.setRequestHeader('authorization', `Bearer ${auth.accessToken}`);
+/* eslint-disable no-throw-literal */
- req.onload = function () {
- let body = req.responseText;
- const contentType = req.getResponseHeader('content-type');
+export default async function hassCallApi(auth, method, path, parameters) {
+ const url = `${auth.data.hassUrl}/api/${path}`;
- if (contentType && contentType.indexOf('application/json') !== -1) {
- try {
- body = JSON.parse(req.responseText);
- } catch (err) {
- reject({
- error: 'Unable to parse JSON response',
- status_code: req.status,
- body: body,
- });
- return;
- }
- }
+ const init = {
+ method: method,
+ headers: {},
+ };
- if (req.status > 199 && req.status < 300) {
- resolve(body);
- } else {
- reject({
- error: 'Response error: ' + req.status,
- status_code: req.status,
- body: body
- });
- }
+ if (parameters) {
+ init.headers['Content-Type'] = 'application/json;charset=UTF-8';
+ init.body = JSON.stringify(parameters);
+ }
+
+ let response;
+
+ try {
+ response = await fetchWithAuth(auth, url, init);
+ } catch (err) {
+ throw {
+ error: 'Request error',
+ status_code: undefined,
+ body: undefined,
};
+ }
- req.onerror = function () {
- reject({
- error: 'Request error',
- status_code: req.status,
- body: req.responseText,
- });
- };
+ let body = null;
- if (parameters) {
- req.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
- req.send(JSON.stringify(parameters));
- } else {
- req.send();
+ const contentType = response.headers.get('content-type');
+
+ if (contentType && contentType.includes('application/json')) {
+ try {
+ body = await response.json();
+ } catch (err) {
+ throw {
+ error: 'Unable to parse JSON response',
+ status_code: err.status,
+ body: null,
+ };
}
- });
+ } else {
+ body = await response.text();
+ }
+
+ if (!response.ok) {
+ throw {
+ error: `Response error: ${response.status}`,
+ status_code: response.status,
+ body: body
+ };
+ }
+
+ return body;
}