'use strict';

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

var _stringify = require('babel-runtime/core-js/json/stringify');

var _stringify2 = _interopRequireDefault(_stringify);

var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

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

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

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

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _bluebird = require('bluebird');

var _bluebird2 = _interopRequireDefault(_bluebird);

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

var _memoryCryptoStore2 = _interopRequireDefault(_memoryCryptoStore);

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

/**
 * Internal module. Partial localStorage backed storage for e2e.
 * This is not a full crypto store, just the in-memory store with
 * some things backed by localStorage. It exists because indexedDB
 * is broken in Firefox private mode or set to, "will not remember
 * history".
 *
 * @module
 */

/*
Copyright 2017, 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 E2E_PREFIX = "crypto.";
var KEY_END_TO_END_ACCOUNT = E2E_PREFIX + "account";
var KEY_DEVICE_DATA = E2E_PREFIX + "device_data";
var KEY_INBOUND_SESSION_PREFIX = E2E_PREFIX + "inboundgroupsessions/";
var KEY_ROOMS_PREFIX = E2E_PREFIX + "rooms/";

function keyEndToEndSessions(deviceKey) {
    return E2E_PREFIX + "sessions/" + deviceKey;
}

function keyEndToEndInboundGroupSession(senderKey, sessionId) {
    return KEY_INBOUND_SESSION_PREFIX + senderKey + "/" + sessionId;
}

function keyEndToEndRoomsPrefix(roomId) {
    return KEY_ROOMS_PREFIX + roomId;
}

/**
 * @implements {module:crypto/store/base~CryptoStore}
 */

var LocalStorageCryptoStore = function (_MemoryCryptoStore) {
    (0, _inherits3.default)(LocalStorageCryptoStore, _MemoryCryptoStore);

    function LocalStorageCryptoStore(webStore) {
        (0, _classCallCheck3.default)(this, LocalStorageCryptoStore);

        var _this = (0, _possibleConstructorReturn3.default)(this, (LocalStorageCryptoStore.__proto__ || (0, _getPrototypeOf2.default)(LocalStorageCryptoStore)).call(this));

        _this.store = webStore;
        return _this;
    }

    // Olm Sessions

    (0, _createClass3.default)(LocalStorageCryptoStore, [{
        key: 'countEndToEndSessions',
        value: function countEndToEndSessions(txn, func) {
            var count = 0;
            for (var i = 0; i < this.store.length; ++i) {
                if (this.store.key(i).startsWith(keyEndToEndSessions(''))) ++count;
            }
            func(count);
        }
    }, {
        key: '_getEndToEndSessions',
        value: function _getEndToEndSessions(deviceKey, txn, func) {
            return getJsonItem(this.store, keyEndToEndSessions(deviceKey));
        }
    }, {
        key: 'getEndToEndSession',
        value: function getEndToEndSession(deviceKey, sessionId, txn, func) {
            var sessions = this._getEndToEndSessions(deviceKey);
            func(sessions[sessionId] || {});
        }
    }, {
        key: 'getEndToEndSessions',
        value: function getEndToEndSessions(deviceKey, txn, func) {
            func(this._getEndToEndSessions(deviceKey) || {});
        }
    }, {
        key: 'storeEndToEndSession',
        value: function storeEndToEndSession(deviceKey, sessionId, session, txn) {
            var sessions = this._getEndToEndSessions(deviceKey) || {};
            sessions[sessionId] = session;
            setJsonItem(this.store, keyEndToEndSessions(deviceKey), sessions);
        }

        // Inbound Group Sessions

    }, {
        key: 'getEndToEndInboundGroupSession',
        value: function getEndToEndInboundGroupSession(senderCurve25519Key, sessionId, txn, func) {
            func(getJsonItem(this.store, keyEndToEndInboundGroupSession(senderCurve25519Key, sessionId)));
        }
    }, {
        key: 'getAllEndToEndInboundGroupSessions',
        value: function getAllEndToEndInboundGroupSessions(txn, func) {
            for (var i = 0; i < this.store.length; ++i) {
                var key = this.store.key(i);
                if (key.startsWith(KEY_INBOUND_SESSION_PREFIX)) {
                    // we can't use split, as the components we are trying to split out
                    // might themselves contain '/' characters. We rely on the
                    // senderKey being a (32-byte) curve25519 key, base64-encoded
                    // (hence 43 characters long).

                    func({
                        senderKey: key.substr(KEY_INBOUND_SESSION_PREFIX.length, 43),
                        sessionId: key.substr(KEY_INBOUND_SESSION_PREFIX.length + 44),
                        sessionData: getJsonItem(this.store, key)
                    });
                }
            }
            func(null);
        }
    }, {
        key: 'addEndToEndInboundGroupSession',
        value: function addEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) {
            var existing = getJsonItem(this.store, keyEndToEndInboundGroupSession(senderCurve25519Key, sessionId));
            if (!existing) {
                this.storeEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn);
            }
        }
    }, {
        key: 'storeEndToEndInboundGroupSession',
        value: function storeEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) {
            setJsonItem(this.store, keyEndToEndInboundGroupSession(senderCurve25519Key, sessionId), sessionData);
        }
    }, {
        key: 'getEndToEndDeviceData',
        value: function getEndToEndDeviceData(txn, func) {
            func(getJsonItem(this.store, KEY_DEVICE_DATA));
        }
    }, {
        key: 'storeEndToEndDeviceData',
        value: function storeEndToEndDeviceData(deviceData, txn) {
            setJsonItem(this.store, KEY_DEVICE_DATA, deviceData);
        }
    }, {
        key: 'storeEndToEndRoom',
        value: function storeEndToEndRoom(roomId, roomInfo, txn) {
            setJsonItem(this.store, keyEndToEndRoomsPrefix(roomId), roomInfo);
        }
    }, {
        key: 'getEndToEndRooms',
        value: function getEndToEndRooms(txn, func) {
            var result = {};
            var prefix = keyEndToEndRoomsPrefix('');

            for (var i = 0; i < this.store.length; ++i) {
                var key = this.store.key(i);
                if (key.startsWith(prefix)) {
                    var roomId = key.substr(prefix.length);
                    result[roomId] = getJsonItem(this.store, key);
                }
            }
            func(result);
        }

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

    }, {
        key: 'deleteAllData',
        value: function deleteAllData() {
            this.store.removeItem(KEY_END_TO_END_ACCOUNT);
            return _bluebird2.default.resolve();
        }

        // Olm account

    }, {
        key: 'getAccount',
        value: function getAccount(txn, func) {
            var account = getJsonItem(this.store, KEY_END_TO_END_ACCOUNT);
            func(account);
        }
    }, {
        key: 'storeAccount',
        value: function storeAccount(txn, newData) {
            setJsonItem(this.store, KEY_END_TO_END_ACCOUNT, newData);
        }
    }, {
        key: 'doTxn',
        value: function doTxn(mode, stores, func) {
            return _bluebird2.default.resolve(func(null));
        }
    }]);
    return LocalStorageCryptoStore;
}(_memoryCryptoStore2.default);

exports.default = LocalStorageCryptoStore;


function getJsonItem(store, key) {
    try {
        // if the key is absent, store.getItem() returns null, and
        // JSON.parse(null) === null, so this returns null.
        return JSON.parse(store.getItem(key));
    } catch (e) {
        console.log("Error: Failed to get key %s: %s", key, e.stack || e);
        console.log(e.stack);
    }
    return null;
}

function setJsonItem(store, key, val) {
    store.setItem(key, (0, _stringify2.default)(val));
}
//# sourceMappingURL=localStorage-crypto-store.js.map