'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

var _bluebird = require('bluebird');

var _bluebird2 = _interopRequireDefault(_bluebird);

var _localStorageCryptoStore = require('./localStorage-crypto-store');

var _localStorageCryptoStore2 = _interopRequireDefault(_localStorageCryptoStore);

var _memoryCryptoStore = require('./memory-crypto-store');

var _memoryCryptoStore2 = _interopRequireDefault(_memoryCryptoStore);

var _indexeddbCryptoStoreBackend = require('./indexeddb-crypto-store-backend');

var IndexedDBCryptoStoreBackend = _interopRequireWildcard(_indexeddbCryptoStoreBackend);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * Internal module. indexeddb storage for e2e.
 *
 * @module
 */

/**
 * An implementation of CryptoStore, which is normally backed by an indexeddb,
 * but with fallback to MemoryCryptoStore.
 *
 * @implements {module:crypto/store/base~CryptoStore}
 */
/*
Copyright 2017 Vector Creations Ltd
Copyright 2018 New Vector Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License 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.
*/

var IndexedDBCryptoStore = function () {
    /**
     * Create a new IndexedDBCryptoStore
     *
     * @param {IDBFactory} indexedDB  global indexedDB instance
     * @param {string} dbName   name of db to connect to
     */
    function IndexedDBCryptoStore(indexedDB, dbName) {
        (0, _classCallCheck3.default)(this, IndexedDBCryptoStore);

        this._indexedDB = indexedDB;
        this._dbName = dbName;
        this._backendPromise = null;
    }

    /**
     * Ensure the database exists and is up-to-date, or fall back to
     * a local storage or in-memory store.
     *
     * @return {Promise} resolves to either an IndexedDBCryptoStoreBackend.Backend,
     * or a MemoryCryptoStore
     */


    (0, _createClass3.default)(IndexedDBCryptoStore, [{
        key: '_connect',
        value: function _connect() {
            var _this = this;

            if (this._backendPromise) {
                return this._backendPromise;
            }

            this._backendPromise = new _bluebird2.default(function (resolve, reject) {
                if (!_this._indexedDB) {
                    reject(new Error('no indexeddb support available'));
                    return;
                }

                console.log('connecting to indexeddb ' + _this._dbName);

                var req = _this._indexedDB.open(_this._dbName, IndexedDBCryptoStoreBackend.VERSION);

                req.onupgradeneeded = function (ev) {
                    var db = ev.target.result;
                    var oldVersion = ev.oldVersion;
                    IndexedDBCryptoStoreBackend.upgradeDatabase(db, oldVersion);
                };

                req.onblocked = function () {
                    console.log('can\'t yet open IndexedDBCryptoStore because it is open elsewhere');
                };

                req.onerror = function (ev) {
                    reject(ev.target.error);
                };

                req.onsuccess = function (r) {
                    var db = r.target.result;

                    console.log('connected to indexeddb ' + _this._dbName);
                    resolve(new IndexedDBCryptoStoreBackend.Backend(db));
                };
            }).catch(function (e) {
                console.warn('unable to connect to indexeddb ' + _this._dbName + (': falling back to localStorage store: ' + e));
                return new _localStorageCryptoStore2.default(global.localStorage);
            }).catch(function (e) {
                console.warn('unable to open localStorage: falling back to in-memory store: ' + e);
                return new _memoryCryptoStore2.default();
            });

            return this._backendPromise;
        }

        /**
         * Delete all data from this store.
         *
         * @returns {Promise} resolves when the store has been cleared.
         */

    }, {
        key: 'deleteAllData',
        value: function deleteAllData() {
            var _this2 = this;

            return new _bluebird2.default(function (resolve, reject) {
                if (!_this2._indexedDB) {
                    reject(new Error('no indexeddb support available'));
                    return;
                }

                console.log('Removing indexeddb instance: ' + _this2._dbName);
                var req = _this2._indexedDB.deleteDatabase(_this2._dbName);

                req.onblocked = function () {
                    console.log('can\'t yet delete IndexedDBCryptoStore because it is open elsewhere');
                };

                req.onerror = function (ev) {
                    reject(ev.target.error);
                };

                req.onsuccess = function () {
                    console.log('Removed indexeddb instance: ' + _this2._dbName);
                    resolve();
                };
            }).catch(function (e) {
                // in firefox, with indexedDB disabled, this fails with a
                // DOMError. We treat this as non-fatal, so that people can
                // still use the app.
                console.warn('unable to delete IndexedDBCryptoStore: ' + e);
            });
        }

        /**
         * Look for an existing outgoing room key request, and if none is found,
         * add a new one
         *
         * @param {module:crypto/store/base~OutgoingRoomKeyRequest} request
         *
         * @returns {Promise} resolves to
         *    {@link module:crypto/store/base~OutgoingRoomKeyRequest}: either the
         *    same instance as passed in, or the existing one.
         */

    }, {
        key: 'getOrAddOutgoingRoomKeyRequest',
        value: function getOrAddOutgoingRoomKeyRequest(request) {
            return this._connect().then(function (backend) {
                return backend.getOrAddOutgoingRoomKeyRequest(request);
            });
        }

        /**
         * Look for an existing room key request
         *
         * @param {module:crypto~RoomKeyRequestBody} requestBody
         *    existing request to look for
         *
         * @return {Promise} resolves to the matching
         *    {@link module:crypto/store/base~OutgoingRoomKeyRequest}, or null if
         *    not found
         */

    }, {
        key: 'getOutgoingRoomKeyRequest',
        value: function getOutgoingRoomKeyRequest(requestBody) {
            return this._connect().then(function (backend) {
                return backend.getOutgoingRoomKeyRequest(requestBody);
            });
        }

        /**
         * Look for room key requests by state
         *
         * @param {Array<Number>} wantedStates list of acceptable states
         *
         * @return {Promise} resolves to the a
         *    {@link module:crypto/store/base~OutgoingRoomKeyRequest}, or null if
         *    there are no pending requests in those states. If there are multiple
         *    requests in those states, an arbitrary one is chosen.
         */

    }, {
        key: 'getOutgoingRoomKeyRequestByState',
        value: function getOutgoingRoomKeyRequestByState(wantedStates) {
            return this._connect().then(function (backend) {
                return backend.getOutgoingRoomKeyRequestByState(wantedStates);
            });
        }

        /**
         * Look for an existing room key request by id and state, and update it if
         * found
         *
         * @param {string} requestId      ID of request to update
         * @param {number} expectedState  state we expect to find the request in
         * @param {Object} updates        name/value map of updates to apply
         *
         * @returns {Promise} resolves to
         *    {@link module:crypto/store/base~OutgoingRoomKeyRequest}
         *    updated request, or null if no matching row was found
         */

    }, {
        key: 'updateOutgoingRoomKeyRequest',
        value: function updateOutgoingRoomKeyRequest(requestId, expectedState, updates) {
            return this._connect().then(function (backend) {
                return backend.updateOutgoingRoomKeyRequest(requestId, expectedState, updates);
            });
        }

        /**
         * Look for an existing room key request by id and state, and delete it if
         * found
         *
         * @param {string} requestId      ID of request to update
         * @param {number} expectedState  state we expect to find the request in
         *
         * @returns {Promise} resolves once the operation is completed
         */

    }, {
        key: 'deleteOutgoingRoomKeyRequest',
        value: function deleteOutgoingRoomKeyRequest(requestId, expectedState) {
            return this._connect().then(function (backend) {
                return backend.deleteOutgoingRoomKeyRequest(requestId, expectedState);
            });
        }

        // Olm Account

        /*
         * Get the account pickle from the store.
         * This requires an active transaction. See doTxn().
         *
         * @param {*} txn An active transaction. See doTxn().
         * @param {function(string)} func Called with the account pickle
         */

    }, {
        key: 'getAccount',
        value: function getAccount(txn, func) {
            this._backendPromise.value().getAccount(txn, func);
        }

        /*
         * Write the account pickle to the store.
         * This requires an active transaction. See doTxn().
         *
         * @param {*} txn An active transaction. See doTxn().
         * @param {string} newData The new account pickle to store.
         */

    }, {
        key: 'storeAccount',
        value: function storeAccount(txn, newData) {
            this._backendPromise.value().storeAccount(txn, newData);
        }

        // Olm sessions

        /**
         * Returns the number of end-to-end sessions in the store
         * @param {*} txn An active transaction. See doTxn().
         * @param {function(int)} func Called with the count of sessions
         */

    }, {
        key: 'countEndToEndSessions',
        value: function countEndToEndSessions(txn, func) {
            this._backendPromise.value().countEndToEndSessions(txn, func);
        }

        /**
         * Retrieve a specific end-to-end session between the logged-in user
         * and another device.
         * @param {string} deviceKey The public key of the other device.
         * @param {string} sessionId The ID of the session to retrieve
         * @param {*} txn An active transaction. See doTxn().
         * @param {function(object)} func Called with A map from sessionId
         *     to Base64 end-to-end session.
         */

    }, {
        key: 'getEndToEndSession',
        value: function getEndToEndSession(deviceKey, sessionId, txn, func) {
            this._backendPromise.value().getEndToEndSession(deviceKey, sessionId, txn, func);
        }

        /**
         * Retrieve the end-to-end sessions between the logged-in user and another
         * device.
         * @param {string} deviceKey The public key of the other device.
         * @param {*} txn An active transaction. See doTxn().
         * @param {function(object)} func Called with A map from sessionId
         *     to Base64 end-to-end session.
         */

    }, {
        key: 'getEndToEndSessions',
        value: function getEndToEndSessions(deviceKey, txn, func) {
            this._backendPromise.value().getEndToEndSessions(deviceKey, txn, func);
        }

        /**
         * Store a session between the logged-in user and another device
         * @param {string} deviceKey The public key of the other device.
         * @param {string} sessionId The ID for this end-to-end session.
         * @param {string} session Base64 encoded end-to-end session.
         * @param {*} txn An active transaction. See doTxn().
         */

    }, {
        key: 'storeEndToEndSession',
        value: function storeEndToEndSession(deviceKey, sessionId, session, txn) {
            this._backendPromise.value().storeEndToEndSession(deviceKey, sessionId, session, txn);
        }

        // Inbound group saessions

        /**
         * Retrieve the end-to-end inbound group session for a given
         * server key and session ID
         * @param {string} senderCurve25519Key The sender's curve 25519 key
         * @param {string} sessionId The ID of the session
         * @param {*} txn An active transaction. See doTxn().
         * @param {function(object)} func Called with A map from sessionId
         *     to Base64 end-to-end session.
         */

    }, {
        key: 'getEndToEndInboundGroupSession',
        value: function getEndToEndInboundGroupSession(senderCurve25519Key, sessionId, txn, func) {
            this._backendPromise.value().getEndToEndInboundGroupSession(senderCurve25519Key, sessionId, txn, func);
        }

        /**
         * Fetches all inbound group sessions in the store
         * @param {*} txn An active transaction. See doTxn().
         * @param {function(object)} func Called once for each group session
         *     in the store with an object having keys {senderKey, sessionId,
         *     sessionData}, then once with null to indicate the end of the list.
         */

    }, {
        key: 'getAllEndToEndInboundGroupSessions',
        value: function getAllEndToEndInboundGroupSessions(txn, func) {
            this._backendPromise.value().getAllEndToEndInboundGroupSessions(txn, func);
        }

        /**
         * Adds an end-to-end inbound group session to the store.
         * If there already exists an inbound group session with the same
         * senderCurve25519Key and sessionID, the session will not be added.
         * @param {string} senderCurve25519Key The sender's curve 25519 key
         * @param {string} sessionId The ID of the session
         * @param {object} sessionData The session data structure
         * @param {*} txn An active transaction. See doTxn().
         */

    }, {
        key: 'addEndToEndInboundGroupSession',
        value: function addEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) {
            this._backendPromise.value().addEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn);
        }

        /**
         * Writes an end-to-end inbound group session to the store.
         * If there already exists an inbound group session with the same
         * senderCurve25519Key and sessionID, it will be overwritten.
         * @param {string} senderCurve25519Key The sender's curve 25519 key
         * @param {string} sessionId The ID of the session
         * @param {object} sessionData The session data structure
         * @param {*} txn An active transaction. See doTxn().
         */

    }, {
        key: 'storeEndToEndInboundGroupSession',
        value: function storeEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) {
            this._backendPromise.value().storeEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn);
        }

        // End-to-end device tracking

        /**
         * Store the state of all tracked devices
         * This contains devices for each user, a tracking state for each user
         * and a sync token matching the point in time the snapshot represents.
         * These all need to be written out in full each time such that the snapshot
         * is always consistent, so they are stored in one object.
         *
         * @param {Object} deviceData
         * @param {*} txn An active transaction. See doTxn().
         */

    }, {
        key: 'storeEndToEndDeviceData',
        value: function storeEndToEndDeviceData(deviceData, txn) {
            this._backendPromise.value().storeEndToEndDeviceData(deviceData, txn);
        }

        /**
         * Get the state of all tracked devices
         *
         * @param {*} txn An active transaction. See doTxn().
         * @param {function(Object)} func Function called with the
         *     device data
         */

    }, {
        key: 'getEndToEndDeviceData',
        value: function getEndToEndDeviceData(txn, func) {
            this._backendPromise.value().getEndToEndDeviceData(txn, func);
        }

        // End to End Rooms

        /**
         * Store the end-to-end state for a room.
         * @param {string} roomId The room's ID.
         * @param {object} roomInfo The end-to-end info for the room.
         * @param {*} txn An active transaction. See doTxn().
         */

    }, {
        key: 'storeEndToEndRoom',
        value: function storeEndToEndRoom(roomId, roomInfo, txn) {
            this._backendPromise.value().storeEndToEndRoom(roomId, roomInfo, txn);
        }

        /**
         * Get an object of roomId->roomInfo for all e2e rooms in the store
         * @param {*} txn An active transaction. See doTxn().
         * @param {function(Object)} func Function called with the end to end encrypted rooms
         */

    }, {
        key: 'getEndToEndRooms',
        value: function getEndToEndRooms(txn, func) {
            this._backendPromise.value().getEndToEndRooms(txn, func);
        }

        /**
         * Perform a transaction on the crypto store. Any store methods
         * that require a transaction (txn) object to be passed in may
         * only be called within a callback of either this function or
         * one of the store functions operating on the same transaction.
         *
         * @param {string} mode 'readwrite' if you need to call setter
         *     functions with this transaction. Otherwise, 'readonly'.
         * @param {string[]} stores List IndexedDBCryptoStore.STORE_*
         *     options representing all types of object that will be
         *     accessed or written to with this transaction.
         * @param {function(*)} func Function called with the
         *     transaction object: an opaque object that should be passed
         *     to store functions.
         * @return {Promise} Promise that resolves with the result of the `func`
         *     when the transaction is complete. If the backend is
         *     async (ie. the indexeddb backend) any of the callback
         *     functions throwing an exception will cause this promise to
         *     reject with that exception. On synchronous backends, the
         *     exception will propagate to the caller of the getFoo method.
         */

    }, {
        key: 'doTxn',
        value: function doTxn(mode, stores, func) {
            return this._connect().then(function (backend) {
                return backend.doTxn(mode, stores, func);
            });
        }
    }]);
    return IndexedDBCryptoStore;
}();

exports.default = IndexedDBCryptoStore;


IndexedDBCryptoStore.STORE_ACCOUNT = 'account';
IndexedDBCryptoStore.STORE_SESSIONS = 'sessions';
IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS = 'inbound_group_sessions';
IndexedDBCryptoStore.STORE_DEVICE_DATA = 'device_data';
IndexedDBCryptoStore.STORE_ROOMS = 'rooms';
//# sourceMappingURL=indexeddb-crypto-store.js.map