-id';
  const STORAGE_RECENT_TABS = 'opera-touch-recent-tabs';
  const STORAGE_UNREADED_MESSAGES = 'opera-touch-unreaded-messages';
  const STORAGE_RECENTLY_CLEARED_DATA = 'opera-touch-recently-cleared-data';

  const COMMUNICATION_PROTOCOL_VERSION = '1.9';

  const textEncoder = new TextEncoder('utf8');
  const textDecoder = new TextDecoder();

  const HISTORY_FETCHING_SETTINGS = {
    HOW_MANY_TOP_UNIQUE_DOMAINS: 100,
    HOW_MANY_DAYS_FROM_NOW: 30,
    SEND_EVERY_MINUTES_IF_CHANGED: 60,
  }

  const TABS_FETCHING_SETTINGS = {
    SEND_SNAPSHOT_EVERY_X_DIFFS: 30,
    COLLECT_DIFFS_FOR_NEXT_X_SECONDS_BEFORE_SENDING: 3600,
    HOW_LONG_WAIT_FOR_TAB_ACTIVATION: 5000,
    HOW_MANY_RECENT_TABS: 3,
    HOW_MANY_SECONDS_UNTIL_NEXT_RECENT_TABS_SENT: 3600,
  }

  const AES_KEY_SETTINGS = {
    name: 'AES-GCM',
    length: 256,
    tagLength: 128,
  };

  const RSA_OAEP_KEY_SETTINGS = {
    name: 'RSA-OAEP',
    hash: {name: 'SHA-1'},
  };

  const RSA_PSS_KEY_SETTINGS = {
    name: 'RSA-PSS',
    modulusLength: 4096,
    hash: {name: 'sha-512'},
    publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
  };

  const RSA_PKCS1_KEY_SETTINGS = {
    name: 'RSASSA-PKCS1-v1_5',
    modulusLength: 4096,
    hash: {name: 'sha-512'},
    publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
  };

  const FCM_MESSAGE_TYPES = {
    DEVICES_CONNECTED: '1',
    NEW_ENCRYPTION_KEY: '2',
    NEW_MESSAGE: '3',
    DELETED_MESSAGE: '4',
    DELETED_DEVICE: '5',
    DELETED_ALL_MESSAGES: '6',
    CLEARED_ALL_DATA: '7',
    DEVICE_NOTIFICATION: '8',
  }

  const OPERA_TOUCH_SERVER_ENDPOINTS = {
    REGISTER_ID: {
      url: '/devices',
      auth: false,
      method: 'POST',
    },
    GET_DEVICES: {
      url: '/devices',
      method: 'GET',
    },
    GET_DEVICE: {
      url: '/devices/{device_id}',
      method: 'GET',
    },
    UPDATE_DEVICE: {
      url: '/devices/{device_id}',
      method: 'PATCH',
    },
    DELETE_DEVICE: {
      url: '/devices/{device_id}',
      method: 'DELETE',
    },
    DELETE_ALL_DEVICES: {
      url: '/all-devices',
      method: 'DELETE',
    },
    PAIRING_TOKEN: {
      url: '/pairing-tokens',
      method: 'POST',
    },
    CONNECT_DEVICES: {
      url: '/connect-devices',
      method: 'POST',
    },
    NOTIFY_DEVICES: {
      url: '/notify-devices',
      method: 'POST',
    },
    CREATE_SHARED_KEY: {
      url: '/encryption-keys',
      method: 'POST',
    },
    GET_SHARED_KEY: {
      url: '/encryption-keys',
      method: 'GET',
    },
    SEND_MESSAGE: {
      url: '/messages',
      method: 'POST',
    },
    GET_MESSAGES: {
      url: '/messages?from_id={from_id}&limit={limit}&order={order}',
      method: 'GET',
    },
    GET_MESSAGE: {
      url: '/messages/{message_id}',
      method: 'GET',
    },
    DELETE_MESSAGE: {
      url: '/messages/{message_id}',
      method: 'DELETE',
    },
    DELETE_ALL_MESSAGES: {
      url: '/all-messages',
      method: 'DELETE',
    },
    GET_HISTORY: {
      url: '/history/{device_id}',
      method: 'GET',
    },
    PUT_HISTORY: {
      url: '/history',
      method: 'PUT',
    },
    GET_TABS: {
      url: '/tabs/{device_id}',
      method: 'GET',
    },
    PUT_TABS: {
      url: '/tabs',
      method: 'PUT',
    },
    PATCH_TABS: {
      url: '/tabs',
      method: 'PATCH',
    },
    GET_RECENT_TABS: {
      url: '/recent-tabs/{device_id}',
      method: 'GET',
    },
    PUT_RECENT_TABS: {
      url: '/recent-tabs',
      method: 'PUT',
    },
  };

  const nativeAPI = window.oprNativeWrapper || chrome;
  // replace nativeApi to this object if chrome is not defined:
  // {
  // storage = {
  //   local: {
  //     get: ()=>{},
  //     set: ()=>{},
  //     clear: ()=>{},
  //   },
  //   history: {
  //     search: ()=>{},
  //   },
  //   tabs: {
  //     query: ()=>{},
  //     onUpdated: ()=>{},
  //     onCreated: ()=>{},
  //     onRemoved: ()=>{},
  //     onMoved: ()=>{},
  //     onAttached: ()=>{},
  //     onActiveChanged: ()=>{},
  //   },
  //   windows: {
  //     onFocusChanged: ()=>{},
  //   },
  //   gcm: {
  //     register: ()=>{},
  //     onMessage: ()=>{},
  //   },
  //   runtime: {
  //     onConnectExternal: ()=>{},
  //   }
  // }

  const storageMock = {
    get: (list, cb) => {
      const ret = {};
      list.map(item => ret[item] = localStorage[item]);
      cb(ret);
    },
    set: (list, cb) => {
      Object.entries(list).map(([item, value]) => localStorage[item] = value);
    },
    clear: () => {},
  };

  // can be set to storage.sync if needed to store in cloud
  const storage =
      nativeAPI && nativeAPI.storage && nativeAPI.storage.local || storageMock;

  class TouchCommunication {
    constructor() {
      if (window.opr) {
        opr.operaTouchPrivate.getServerUrl(
            serverUrl => OPERA_TOUCH_SERVER_URL = serverUrl);
        if (opr.operaTouchPrivate && opr.operaTouchPrivate.getLocalName) {
          opr.operaTouchPrivate.getLocalName(
              localName => nativeAPI.registerName = localName);
        }
      }

      this.notificationType = nativeAPI.notificationType || 'fcm';

      this.initialized = new Promise(res => {
        this.resolveInitialize = res;
      });
      this.setupCommunicationBetweenExtensions();
      this.setupNativeLayer();
      this.setupFirebaseCommunication();
      this.checkRecentlyCleared();

      this.setKeys()
          .then(() => this.getUnreadedMessages())
          .then(() => this.setId())
          .then(() => this.initializationCompleted());
    }

    initializationCompleted() {
      if (this.id) {
        this.establishServerConnection();
      }
      this.resolveInitialize();
      this.setupHistorySender();
      this.setupTabsSender();
    }

    /**
     * To prevent connecting HostedApp to old Background worker instance, during
     * data clear we first clear everything, then reload hosted app
     */
    checkRecentlyCleared() {
      storage.get([STORAGE_RECENTLY_CLEARED_DATA], value => {
        if (value[STORAGE_RECENTLY_CLEARED_DATA] === '1') {
          storage.set({[STORAGE_RECENTLY_CLEARED_DATA]: '0'});
          if (window.opr && opr.operaTouchPrivate &&
              opr.operaTouchPrivate.reloadHostedApp) {
            opr.operaTouchPrivate.reloadHostedApp();
          }
        }
      });
    }

    setupHistorySender() {
      this._sendHistoryInterval = setInterval(
          this._checkAndSendHistory.bind(this),
          HISTORY_FETCHING_SETTINGS.SEND_EVERY_MINUTES_IF_CHANGED * 60 * 1000);
      this._checkAndSendHistory();
    }

    _checkValidTab(tab) {
      return /^http|^ftp/.test(tab.url) &&
          !(/^https:\/\/flow\.opera\.com/.test(tab.url)) && !tab.incognito;
    }

    _checkAndSendHistory() {
      {
        if (!this.isPaired) {
          // don't send history if not paired
          return Promise.resolve();
        }
        const startTime =
            (new Date() -
             (HISTORY_FETCHING_SETTINGS.HOW_MANY_DAYS_FROM_NOW * 24 * 60 * 60 *
              1000));

        nativeAPI.history.search(
            {text: '', startTime, maxResults: 100000}, result => {
              // sort by most often used
              const mapUniqueDomains = new Map();
              result.forEach(entry => {
                if (!this._checkValidTab(entry)) {
                  // Skip entries other that makes sense
                  return;
                }
                const url = entry.url.replace(/([^/]+\/\/[^/]+)(.*)/g, '$1');
                let count = entry.visitCount + entry.typedCount;
                let lastVisitTime = entry.lastVisitTime;
                if (mapUniqueDomains.has(entry)) {
                  const oldEntry = mapUniqueDomains.get(entry);
                  count += oldEntry.count;
                  if (oldEntry.lastVisitTime > entry.lastVisitTime) {
                    lastVisitTime = oldEntry.lastVisitTime;
                  }
                }
                mapUniqueDomains.set(entry, {
                  lastVisitTime,
                  count,
                  url,
                });
              });

              const topResults =
                  JSON.stringify([...mapUniqueDomains.values()]
                                     .sort((a, b) => a.count < b.count ? 1 : -1)
                                     .splice(
                                         0,
                                         HISTORY_FETCHING_SETTINGS
                                             .HOW_MANY_TOP_UNIQUE_DOMAINS));

              if (this.storedTopResults !== topResults) {
                this.storedTopResults = topResults;
                return this.encryptContentToServer({content: topResults})
                    .then(
                        data => this.sendRequest(
                            OPERA_TOUCH_SERVER_ENDPOINTS.PUT_HISTORY, data));
              }

            });
      }
      return Promise.resolve();
    }

    _recalculateTabsIndexes() {
      Object.values(this._tabs)
          .filter(tab => this._checkValidTab(tab))
          .sort((a, b) => {
            if (a.windowId === b.windowId) {
              return a.index > b.index ? 1 : -1;
            }
            return a.windowId > b.windowId ? 1 : -1;
          })
          .forEach((tab, index) => tab.sortedIndex = index);
    }
    _getAllTabs() {
      return new Promise(resolve => nativeAPI.tabs.query({}, result => {
        result.forEach(tab => {
          this._tabs[tab.id] = tab;
          resolve();
        });
      }));
    }

    _recentTabsUpdate(tab) {
      if (!this._checkValidTab(tab)) {
        // 1. don't send incognito tabs
        // 2. check if url is somewhat meaningful
        return 0;
      }
      const previousItem =
          this._recentTabs.findIndex(iterTab => iterTab.id === tab.id);
      if (previousItem > -1) {
        this._recentTabs.splice(previousItem, 1);
      }
      this._recentTabs.unshift(tab);
      this._recentTabs = this._recentTabs.slice(
          0, TABS_FETCHING_SETTINGS.HOW_MANY_RECENT_TABS);

      const now = Date.now();
      const cantSentBefore = this._sendRecentTabsDate +
          TABS_FETCHING_SETTINGS.HOW_MANY_SECONDS_UNTIL_NEXT_RECENT_TABS_SENT *
              1000;

      if (!this._sendRecentTabsDate || (cantSentBefore < now)) {
        this._sendRecentTabs();
      } else {
        if (!this._sendRecentTabsTimeout) {
          this._sendRecentTabsTimeout =
              setTimeout(() => this._sendRecentTabs(), cantSentBefore - now);
        }
      }
    }

    _sendRecentTabs() {
      if (!this.isPaired) {
        // don't send tabs if not paired
        return Promise.resolve();
      }
      this._sendRecentTabsDate = Date.now();
      clearTimeout(this._sendRecentTabsTimeout);
      delete this._sendRecentTabsTimeout;
      const tabsToSend = this._recentTabs.map(
          tab => (Object.assign(this._filterTabContent(tab), {id: null})));

      const jsonToSend = JSON.stringify(tabsToSend);

      if (this._lastRecentTabs !== jsonToSend) {
        // only send things different than before
        this._lastRecentTabs = jsonToSend;
        storage.set({[STORAGE_RECENT_TABS]: jsonToSend});
        return this.encryptContentToServer({content: jsonToSend})
            .then(
                data => this.sendRequest(
                    OPERA_TOUCH_SERVER_ENDPOINTS.PUT_RECENT_TABS, data));
      } else {
        // Data is the same, just resolve
        return Promise.resolve();
      }
    }

    async setupTabsSender() {
      this._tabs = {};
      this._prevTabUrlValid = {};
      this._sentDiffs = 0;
      this._recentTabs = [];
      await this._getAllTabs();
      await this._readFromStorageAsPromise([STORAGE_RECENT_TABS], response => {
        if (response[STORAGE_RECENT_TABS]) {
          this._recentTabs = JSON.parse(response[STORAGE_RECENT_TABS]);
          const tabUrlsMap =
              new Map(this._recentTabs.map((tab, index) => [tab.url, index]));
          Object.values(this._tabs).forEach(tab => {
            if (tabUrlsMap.has(tab.url)) {
              this._recentTabs[tabUrlsMap.get(tab.url)].id = tab.id;
            }
          });
        }
      });
      this._sendTabsSnapshot();

      nativeAPI.tabs.onUpdated.addListener((tabId, changeInfo) => {
        if (changeInfo.status === 'loading') {
          this._prevTabUrlValid[tabId] = this._checkValidTab(this._tabs[tabId]);
          // better remove favicon at all instead of displaying wrong one
          this._tabs[tabId] =
              Object.assign(this._tabs[tabId], {favIconUrl: ''});
        }
        const tab = this._tabs[tabId] =
            Object.assign(this._tabs[tabId], changeInfo);
        if (changeInfo.status === 'complete') {
          this._recentTabsUpdate(tab);
          const previousUrlValid =
              typeof this._prevTabUrlValid[tabId] !== 'boolean' ||
              this._prevTabUrlValid[tabId];
          delete this._prevTabUrlValid[tabId];
          if (!this._checkValidTab(tab)) {
            if (previousUrlValid) {
              this._sendTabsDiff('DELETED', tab);
            }
          } else {
            if (previousUrlValid) {
              this._sendTabsDiff('UPDATED', tab);
            } else {
              this._sendTabsDiff('CREATED', tab);
            }
          }
        }
      });
      nativeAPI.tabs.onCreated.addListener(tab => {
        // empty tab changes indexes inside windows
        // so regenerate all data
        this._getAllTabs().then(() => {
          delete this._tabs[tab.id].url;
        });
      });
      nativeAPI.tabs.onRemoved.addListener(tabId => {
        const tab = this._tabs[tabId];
        if (tab) {
          this._sendTabsDiff('DELETED', tab);
          delete this._tabs[tabId];
          this._getAllTabs();
        }
      });

      let activationTimeout;
      const onTabActivated = tabId => {

        clearTimeout(activationTimeout);
        activationTimeout = setTimeout(() => {
          const tab = this._tabs[tabId];
          if (tab) {
            this._sendTabsDiff('ACTIVATED', tab);
            this._recentTabsUpdate(tab);
          }
        }, TABS_FETCHING_SETTINGS.HOW_LONG_WAIT_FOR_TAB_ACTIVATION);
      };

      nativeAPI.tabs.onActiveChanged.addListener(onTabActivated);
      nativeAPI.windows.onFocusChanged.addListener(() => {
        nativeAPI.tabs.query({currentWindow: true, active: true}, tabs => {
          if (tabs && tabs[0] && tabs[0].id) {
            onTabActivated(tabs[0].id);
          }
        });
      });

      const onMoveTab = tabId => {
        const tab = this._tabs[tabId];
        if (tab) {
          this._sendTabsDiff('DELETED', tab);
          this._getAllTabs().then(() => {
            this._sendTabsDiff('CREATED', this._tabs[tabId]);
          });
        }
      };

      nativeAPI.tabs.onMoved.addListener(onMoveTab);
      nativeAPI.tabs.onAttached.addListener(onMoveTab);
    }

    /**
     * Filter object content from a structure like
     * { url:'', title: '', something: '', something: '' }
     * to structure that we re interested in only
     */
    _filterTabContent(obj) {
      return (
          ({id, url, title, favIconUrl, sortedIndex}) =>
              ({id, url, title, favIconUrl, sortedIndex}))(obj);
    }

    sendDesktopStateToServer() {
      if (!this.isPaired) {
        return Promise.reject();
      }
      return Promise.all([
        this._sendRecentTabs(),
        this._sendTabsSnapshot(),
        this._checkAndSendHistory(),
      ]);
    }

    _sendTabsSnapshot() {
      if (!this.isPaired) {
        // don't send tabs if not paired
        return Promise.resolve();
      }
      this._sentDiffs = 0;
      clearTimeout(this._sendTabsDiffTimeout);
      delete this._sendTabsDiffTimeout;
      this._recalculateTabsIndexes();
      const selection =
          Object.entries(this._tabs)
              .filter(([id, tab]) => this._checkValidTab(tab))
              .map(([id, tab]) => (this._filterTabContent(tab)))
              .sort((a, b) => a.sortedIndex > b.sortedIndex ? 1 : -1);
      this._atLeastOneSnapthotSent = true;

      const jsonToSend = JSON.stringify(selection);
      if (this._lastTabsSnapshot !== jsonToSend) {
        // only send things different than before
        this._lastTabsSnapshot = jsonToSend;
        return this.encryptContentToServer({content: jsonToSend})
            .then(
                data => this.sendRequest(
                    OPERA_TOUCH_SERVER_ENDPOINTS.PUT_TABS, data));
      } else {
        // Data is the same, just resolve
        return Promise.resolve();
      }
    }

    _sendTabsDiff(type, tab) {
      if (!this.isPaired || (type !== 'DELETED' && !this._checkValidTab(tab))) {
        // 1. don't send tabs if not paired
        // 2. skip tabs with urls like nativeAPI://
        return 0;
      }

      if (!this._atLeastOneSnapthotSent ||
          this._sentDiffs >
                  TABS_FETCHING_SETTINGS.SEND_SNAPSHOT_EVERY_X_DIFFS &&
              !this._sendTabsDiffTimeout) {
        // In case there is no diffs on stack and we extended their amount
        // simply send current snapshot
        this._sendTabsSnapshot();
        return;
      }
      this._recalculateTabsIndexes();
      tab = this._filterTabContent(this._tabs[tab.id]);
      if (this._sendTabsDiffTimeout) {
        this._diffsToBeSent.push({type, tab});
      } else {
        this._diffsToBeSent = [{type, tab}];
        this._sendTabsDiffTimeout = setTimeout(
            () => this._sendTabsDiffsToServer(),
            TABS_FETCHING_SETTINGS
                    .COLLECT_DIFFS_FOR_NEXT_X_SECONDS_BEFORE_SENDING *
                1000);
      }
      this._sentDiffs++;
    }

    _sendTabsDiffsToServer() {
      delete this._sendTabsDiffTimeout;
      if (this._sentDiffs >
          TABS_FETCHING_SETTINGS.SEND_SNAPSHOT_EVERY_X_DIFFS) {
        // If we collected so much that it makes no sense to
        // send diffs, just send a new snapshot
        this._sendTabsSnapshot();
      } else {
        this.encryptContentToServer(
                {content: JSON.stringify(this._diffsToBeSent)})
            .then(data => {
              this.sendRequest(OPERA_TOUCH_SERVER_ENDPOINTS.PATCH_TABS, data);
            });
      }
    }

    setupNativeLayer() {
      storage.get([STORAGE_PAIRED_DEVICES, STORAGE_GROUP_ID], stored => {
        this.isPaired = !!stored[STORAGE_PAIRED_DEVICES];
        this.groupId = stored[STORAGE_GROUP_ID] || '';
        opr.operaTouchPrivate.setIsRegistered(this.isPaired, this.groupId);
      });

      if (!(window.opr && opr.operaTouchPrivate)) {
        console.log('Missing operaTouchPrivate namespace');
      } else {
        if (opr.operaTouchPrivate.onWillGoToSleep) {
          opr.operaTouchPrivate.onWillGoToSleep.addListener(
              this.sendDesktopStateToServer.bind(this));
        }
        if (opr.operaTouchPrivate.onBrowserWillClose) {
          opr.operaTouchPrivate.onBrowserWillClose.addListener(
              this.sendDesktopStateToServer.bind(this));
        }

        if (opr.operaTouchPrivate.onResetData) {
          opr.operaTouchPrivate.onResetData.addListener(
              this._completeDataReset.bind(this));
        }

        opr.operaTouchPrivate.onShareRequested.addListener(
            (url, type, requestId) => {
              switch (type) {
                case 'PAGE_URL':
                  nativeAPI.tabs.query(
                      {currentWindow: true, active: true}, tabs => {
                        const favIconUrl = tabs[0].favIconUrl;
                        const url = tabs[0].url;
                        const title = tabs[0].title;
                        this.sendMessageToServer(
                                JSON.stringify({type: 'link'}),
                                JSON.stringify({url, title, favIconUrl}))
                            .then(() => {
                              opr.operaTouchPrivate.sendRequestResponse(
                                  requestId, true);
                            })
                            .catch(() => {
                              opr.operaTouchPrivate.sendRequestResponse(
                                  requestId, false);
                            });
                      });
                  break;
                case 'TEXT':
                  this.sendMessageToServer(
                      JSON.stringify({type: 'text'}),
                      JSON.stringify({text: url}));
                  break;
                case 'LINK_URL':
                case 'IMAGE_URL':
                  this.sendMessageToServer(
                      JSON.stringify({type: 'link'}), JSON.stringify({url}));
                  break;
              }
            });
      }
    }

    setUnreadedMessages(unreaded = false) {
      this._notifyExtensions({type: 'SET_UNREADED_MESSAGES', value: unreaded});
      storage.set({
        [STORAGE_UNREADED_MESSAGES]: unreaded,
      });
      this._unreadedMessages = unreaded;
      opr.browserSidebarPrivate.setShouldShowNotification(
          opr.browserSidebarPrivate.BrowserSidebarItemType.TOUCH, unreaded);
    }

    setupFirebaseCommunication() {
      nativeAPI.gcm.register(
          [FIREBASE_CONFIG.messagingSenderId], registerId => {
            this.gcmToken = registerId;
            console.log('registerID:' + registerId);
          });
      nativeAPI.gcm.onMessage.addListener(message => {
        console.log('GCM Message', message);
        switch (`${message.data.type}`) {
          case FCM_MESSAGE_TYPES.NEW_MESSAGE:
            this._notifyExtensions({type: 'NEW_MESSAGE_AVAILABLE'});
            if (message.data.created_by !== this.id) {
              this.setUnreadedMessages(true);
            }
            break;
          case FCM_MESSAGE_TYPES.DEVICES_CONNECTED:
            const device_ids = typeof message.data.device_ids === 'string' ?
                JSON.parse(message.data.device_ids) :
                message.data.device_ids;  // iOS has this field parsed already,
                                          // desktop not
            const connecting_to_existing_group = device_ids.length === 1;
            this._notifyExtensions({type: 'DEVICES_CONNECTING_STARTED'});

            this.getConnectedDevices(true).then(connectedDevices => {
              connectedDevices = connectedDevices.devices.filter(
                  device => device.id !== this.id);

              connectedDevices.forEach(async device => {
                const authentication_token =
                    await this._generateAuthenticationToken(
                        this._connectingDesktopToOtherDeviceToken ||
                            this._lastVerificationToken,
                        this._escapePEMKey(device.public_key), device.id,
                        device.authentication_string.match(/\d+$/)[0]);
                if (authentication_token === device.authentication_string) {
                  this._authorizedDevices =
                      Object.assign((this._authorizedDevices || {}), {
                        [device.id]: device,
                      });
                  if (!connecting_to_existing_group &&
                          !this._connectingDesktopToOtherDeviceToken ||
                      connecting_to_existing_group &&
                          device_ids[0] !== this.id) {
                    this.sendEncryptionKey(device);
                    this.setNativeSending(true, device.group_id);
                    this.sendDesktopStateToServer();
                  }
                } else {
                  // Seems authentication_token is compromised
                  this._notifyExtensions(
                      {type: 'DEVICES_COULD_NOT_CONNECT', value: device});
                  delete this._connectingDesktopToOtherDeviceToken;
                }
              })
            });
            break;

          case FCM_MESSAGE_TYPES.NEW_ENCRYPTION_KEY:
            this.getSharedKey(true).finally(() => {
              delete this._connectingDesktopToOtherDeviceToken;
            });
            break;

          case FCM_MESSAGE_TYPES.DELETED_MESSAGE:
            this._notifyExtensions(
                {type: 'FCM_MESSAGE_DELETED', value: message.data});
            break;

          case FCM_MESSAGE_TYPES.DELETED_DEVICE:
            if (message.data.id === this.id) {
              this._completeDataReset();
            } else {
              this._notifyExtensions(
                  {type: 'FCM_DEVICE_DELETED', value: message.data});
            }
            break;
          case FCM_MESSAGE_TYPES.DELETED_ALL_MESSAGES:
            this._notifyExtensions(
                {type: 'FCM_DELETED_ALL_MESSAGES', value: message.data});
            break;
          case FCM_MESSAGE_TYPES.CLEARED_ALL_DATA:
            this._completeDataReset();
            break;
          case FCM_MESSAGE_TYPES.DEVICE_NOTIFICATION:
            if (message.data && message.data.payload) {
              const payload = JSON.parse(message.data.payload);
              switch (payload.action) {
                case 'updateRequest':
                  this.sendDesktopStateToServer().then(
                      () => this.sendRequest(
                          OPERA_TOUCH_SERVER_ENDPOINTS.NOTIFY_DEVICES, {
                            target: {
                              'device_kind': 'mobile',
                            },
                            payload: JSON.stringify({'action': 'newDataSent'}),
                          }));
                  break;
                case 'connected':
                  this.getConnectedDevices(true).then(connectedDevices => {
                    const device = connectedDevices.devices.find(
                        d => d.id === payload.device_id);
                    if (device) {
                      this._notifyExtensions(
                          {type: 'DEVICES_CONNECTED', value: device});
                    }
                  });
                  break;
              }
            }
            break;
        }
      });
    }

    /**
     * Inform Native layer does buttons to share can be enabled or not
     */
    setNativeSending(isPaired, groupId = '') {
      this.isPaired = isPaired;
      this.groupId = groupId;
      opr.operaTouchPrivate.setIsRegistered(isPaired, groupId);
      storage.set({
        [STORAGE_PAIRED_DEVICES]: isPaired,
        [STORAGE_GROUP_ID]: groupId,
      });
    }

    setupCommunicationBetweenExtensions() {
      this._hostedAppPorts = [];
      nativeAPI.runtime.onConnectExternal.addListener(port => {
        this._hostedAppPorts.push(port);
        port.onDisconnect.addListener(() => {
          this._hostedAppPorts.splice(this._hostedAppPorts.indexOf(port), 1);
        });

        const wrapResponse = (serverRequest, requestData) =>
            serverRequest
                .then(response => {
                  port.postMessage({
                    type: `${requestData.type}_OK`,
                    value: response,
                    messageId: requestData.messageId,
                  });
                })
                .catch(e => {
                  port.postMessage({
                    type: `${requestData.type}_ERROR`,
                    messageId: requestData.messageId,
                    errorValue: e,
                  });
                });

        const getInitialState = () => {
          this.initialized.then(() => port.postMessage({
            type: 'INITIALIZATION_OK',
            value: this.id,
            unreadedMessages: this._unreadedMessages,
          }));
        };

        port.onMessage.addListener(data => {
          switch (data.type) {
            case 'GET_PAIRING_TOKEN':
              wrapResponse(this.getPairingToken(data.value), data);
              break;

            case 'GET_DEVICES':
              wrapResponse(this.getConnectedDevices(), data);
              break;

            case 'DELETE_DEVICE':
              wrapResponse(this.deleteDevice(data.value), data);
              break;

            case 'GET_MESSAGE':
              wrapResponse(this.getMessagesFromServer(data.value), data);
              break;

            case 'GET_MESSAGES':
              data.value = data.value || {};
              wrapResponse(
                  this.getMessagesFromServer(
                      data.value.from_id, data.value.order, data.value.limit),
                  data);
              break;

            case 'CREATE_MESSAGE':
              wrapResponse(
                  this.sendMessageToServer(
                      data.value.metadata, data.value.content),
                  data);
              break;

            case 'DELETE_MESSAGE':
              wrapResponse(this.deleteMessage(data.value), data);
              break;

            case 'DELETE_ALL_MESSAGES':
              wrapResponse(this.deleteAllMessages(data.value), data);
              break;

            case 'HOSTED_APP_SHOWN':
              this.setUnreadedMessages(false);
              break;

            case 'RESET_EVERYTHING':
              this.deleteAllDevices().finally(() => {
                this._completeDataReset();
              });
              // just to be sure call it in next 1 sec
              setTimeout(this._completeDataReset.bind(this), 1000);
              break;

            case 'GET_PARTIAL_URL':
              wrapResponse(
                  this.getPartialUrl(
                      data.value.url, data.value.byteLimit,
                      data.value.extraHeaders),
                  data);
              break;
            case 'GET_INITIAL_STATE':
              getInitialState();
              break;
          }
        });

        getInitialState();
      });
    }

    _notifyExtensions(data) {
      this._hostedAppPorts.forEach(port => {
        port.postMessage(data);
      });
    }

    _readFromStorageAsPromise(getArray, func) {
      return new Promise(resolve => {
        storage.get(getArray, stored => {
          func(stored);
          resolve();
        });
      });
    }

    getUnreadedMessages() {
      return this._readFromStorageAsPromise(
          [STORAGE_UNREADED_MESSAGES], stored => {
            this._unreadedMessages = !!stored[STORAGE_UNREADED_MESSAGES];
          });
    }


    setId() {
      return this._readFromStorageAsPromise(
          [STORAGE_ID, STORAGE_AUTH_TOKEN], stored => {
            this.id = stored[STORAGE_ID];
            this.auth_token = stored[STORAGE_AUTH_TOKEN];
          });
    }

    establishServerConnection() {
      return new Promise((resolve, reject) => {
        if (!this.id) {
          this.initialized.then(
              () => this.registerDevice().then(resolve).catch(reject));
        } else {
          this.updateDeviceFCMToken().then(resolve).catch(reject);
        }
      });
    }

    _escapePEMKey(key) {
      return key
          .replace(/\r/g, '')        // remove \r if any
          .replace(/----.*\n/g, '')  // begin remove
          .replace(/---.*$/g, '')    // end remove
          .replace(/\n/g, '');       // remove enter
    }

    makePemFromByteArray(key, isPrivate = false) {
      const base64key = base64js.fromByteArray(new Uint8Array(key));
      return [
        '-----BEGIN ',
        (isPrivate ? 'PRIVATE' : 'PUBLIC'),
        ' KEY-----\n',
        base64key.replace(/(.{64})/g, '$1\n').replace(/\n$/, ''),
        '\n-----END ',
        (isPrivate ? 'PRIVATE' : 'PUBLIC'),
        ' KEY-----',
      ].join('');
    }

    makeByteArrayFromPemKey(key) {
      return base64js.toByteArray(this._escapePEMKey(key));
    }

    setKeys() {
      let toResolve;
      const onGetDone = async function(stored) {
        const publicKeyPEM = stored[STORAGE_PUBLIC_KEY];
        const privateKeyPEM = stored[STORAGE_PRIVATE_KEY];
        this.encryptionKey = stored[STORAGE_ENCRYPTION_KEY];
        if (!this.encryptionKey) {
          await this.generateAESKey();
        } else {
          await this._importEncryptionKey();
        }
        if (publicKeyPEM && privateKeyPEM) {
          this.publicKey = this.makeByteArrayFromPemKey(publicKeyPEM);
          this.privateKey = this.makeByteArrayFromPemKey(privateKeyPEM);

          await this._importPrivateCryptoKey(privateKeyPEM);
        } else {
          await this.generateRSAKeys();
        }
        toResolve();
      }.bind(this);

      return new Promise(resolve => {
        toResolve = resolve;
        storage.get(
            [
              STORAGE_PUBLIC_KEY,
              STORAGE_PRIVATE_KEY,
              STORAGE_ENCRYPTION_KEY,
            ],
            onGetDone);
      });
    }

    async _importEncryptionKey() {
      return new Promise((resolve, reject) => {
        crypto.subtle
            .importKey(
                'jwk', JSON.parse(this.encryptionKey), AES_KEY_SETTINGS, true,
                ['encrypt', 'decrypt'])
            .then(key => {
              this.encryptionKey = key;
              resolve();
            })
            .catch(reject);
      });
    }
    async _importPrivateCryptoKey(privateKeyPEM) {
      return new Promise((resolve, reject) => {
        window.crypto.subtle
            .importKey(
                'pkcs8', this.makeByteArrayFromPemKey(privateKeyPEM),
                RSA_OAEP_KEY_SETTINGS, false, ['decrypt'])
            .then(importedKey => {
              this.privateCryptoKey = importedKey;
              resolve();
            })
            .catch(reject);
      });
    }

    registerDevice() {
      return new Promise((resolve, reject) => {
        this.sendRequest(OPERA_TOUCH_SERVER_ENDPOINTS.REGISTER_ID, {
              'name': nativeAPI.registerName || 'desktop',
              'public_key':
                  this.makePemFromByteArray(this.publicKey).replace(/\r/g, ''),
              'notification_token': `${this.notificationType}:${this.gcmToken}`,
              'kind': nativeAPI.registerKind || 'desktop',
              'client_version': COMMUNICATION_PROTOCOL_VERSION,
            })
            .then(json => {
              this.id = json.id;
              this.auth_token = json.auth_token;
              storage.set({
                [STORAGE_ID]: this.id,
                [STORAGE_AUTH_TOKEN]: this.auth_token,
              });
              resolve();
            })
            .catch(error => {
              reject();
            });
      });
    }

    updateDeviceFCMToken() {
      return new Promise((resolve, reject) => {
        this.sendRequest(OPERA_TOUCH_SERVER_ENDPOINTS.UPDATE_DEVICE, {
              'device_id': this.id,
              'notification_token': `${this.notificationType}:${this.gcmToken}`,
              'client_version': COMMUNICATION_PROTOCOL_VERSION,
            })
            .then(resolve)
            .catch(reject);
      });
    }

    getConnectedDevices(retry_empty_response = false) {
      return this.sendRequest(
          OPERA_TOUCH_SERVER_ENDPOINTS.GET_DEVICES, null, retry_empty_response);
    }

    getTabsOfDevice(device_id) {
      return this
          .sendRequest(OPERA_TOUCH_SERVER_ENDPOINTS.GET_TABS, {device_id})
          .then(this.decryptEntriesContent.bind(this))
          .then(jsonData => {
            let tabs = [];
            jsonData.entries.forEach(diff => {
              const diffContent = JSON.parse(diff.content);
              if (diff.snapshot) {
                tabs = diffContent;
              } else {
                diffContent.forEach(diffEntry => {
                  switch (diffEntry.type) {
                    case 'CREATED':
                      tabs.splice(diffEntry.tab.sortedIndex, 0, diffEntry.tab);
                      break;
                    case 'UPDATED':
                      tabs[diffEntry.tab.sortedIndex] = diffEntry.tab;
                      break;
                    case 'DELETED':
                      tabs.splice(diffEntry.tab.sortedIndex, 1);
                      break;
                  }
                });
              }
            });
            return tabs;
          });
    }

    getHistoryOfDevice(device_id) {
      return this
          .sendRequest(OPERA_TOUCH_SERVER_ENDPOINTS.GET_HISTORY, {device_id})
          .then(this.decryptEntriesContent.bind(this))
          // For now we have only one entry on list
          .then(jsonData => JSON.parse(jsonData.entries[0].content));
    }

    getRecentTabsOfDevice(device_id) {
      return this
          .sendRequest(
              OPERA_TOUCH_SERVER_ENDPOINTS.GET_RECENT_TABS, {device_id})
          .then(this.decryptEntriesContent.bind(this))
          // For now we have only one entry on list
          .then(jsonData => JSON.parse(jsonData.entries[0].content));
    }

    async getPairingToken(fallback = false) {
      if (!this.id) {
        await this.establishServerConnection();
      }

      this._lastVerificationToken = this._generateVerificationToken();
      this._lastVerificationTokenTimestamp = Date.now();

      return this
          ._generateAuthenticationToken(
              this._lastVerificationToken,
              this._escapePEMKey(this.makePemFromByteArray(this.publicKey)),
              this.id, this._lastVerificationTokenTimestamp)
          .then(
              authentication_string => this.sendRequest(
                  OPERA_TOUCH_SERVER_ENDPOINTS.PAIRING_TOKEN,
                  {fallback, authentication_string}))
          .then(json => {
            json.token += ['$', this._lastVerificationToken].join('');
            json.id = this.id;
            return json;
          });
    }

    async connectDeviceByToken(token) {
      if (!this.id) {
        await this.establishServerConnection();
      }

      const [real_token, verificationToken] = token.split('$');
      const timestamp = Date.now();
      this._connectingDesktopToOtherDeviceToken = verificationToken;

      return this
          ._generateAuthenticationToken(
              verificationToken,
              this._escapePEMKey(this.makePemFromByteArray(this.publicKey)),
              this.id, timestamp)
          .then(
              authentication_string => this.sendRequest(
                  OPERA_TOUCH_SERVER_ENDPOINTS.CONNECT_DEVICES,
                  {token: real_token, authentication_string}));
    }

    /**
     * encrypt and send message to server,
     * if metadata.type === FILE then different enconding will be applied to
     * content
     * TODO: currently not implemented FILE type
     */
    sendMessageToServer(metadata, content, encrypt = true) {
      let returnObject;
      const jsonToSend = {metadata, content: content, iv: 'empty'};

      if (typeof jsonToSend.metadata === 'object') {
        jsonToSend.metadata = JSON.stringify(jsonToSend.metadata);
      }
      if (typeof jsonToSend.content === 'object') {
        jsonToSend.content = JSON.stringify(jsonToSend.content);
      }

      if (!encrypt) {
        returnObject = Promise.resolve(jsonToSend);
      } else {
        returnObject = this.encryptMessageToServer(jsonToSend);
      }
      return returnObject.then(
          encrypted_content =>
              this.sendRequest(
                      OPERA_TOUCH_SERVER_ENDPOINTS.SEND_MESSAGE,
                      encrypted_content)
                  .then(json => {
                    opr.statsPrivate.recordAction(
                        'Touch.MsgSentCount', opr.statsPrivate.Priority.NORMAL);
                    return json;
                  }));
    }

    deleteMessage(id) {
      return this.sendRequest(
          OPERA_TOUCH_SERVER_ENDPOINTS.DELETE_MESSAGE, {message_id: id});
    }

    deleteAllMessages() {
      return this.sendRequest(
          OPERA_TOUCH_SERVER_ENDPOINTS.DELETE_ALL_MESSAGES, {});
    }

    deleteDevice(id) {
      return this.sendRequest(
          OPERA_TOUCH_SERVER_ENDPOINTS.DELETE_DEVICE, {device_id: id});
    }

    deleteAllDevices() {
      return this.sendRequest(
          OPERA_TOUCH_SERVER_ENDPOINTS.DELETE_ALL_DEVICES, {});
    }

    getMessageFromServer(id) {
      return this
          .sendRequest(
              OPERA_TOUCH_SERVER_ENDPOINTS.GET_MESSAGE, {message_id: id})
          .then(this.decryptMessageFromServer.bind(this));
    }
    getMessagesFromServer(from_id = 0, order = 'asc', limit = 10) {
      return this
          .sendRequest(
              OPERA_TOUCH_SERVER_ENDPOINTS.GET_MESSAGES,
              {from_id, order, limit})
          .then(async json => {
            json.messages = await Promise.all(
                json.messages.map(this.decryptMessageFromServer.bind(this)));
            return json;
          });
    }

    /**
     * encrypt message to server
     */
    encryptMessageToServer(json) {
      const iv = window.crypto.getRandomValues(new Uint8Array(16));
      json.iv = base64js.fromByteArray(iv);
      let content = json.content;
      if (json.metadata && json.metadata.type === 'FILE') {
        // TODO: handle sending FILE type here
        content =
            base64js.toByteArray(json.content);  // handle it as pure base64data
      } else {
        content = textEncoder.encode(json.content);  // handle it as Utf8 data
      }

      return this._encryptData(textEncoder.encode(json.metadata), iv)
          .then(metadata => {
            json.metadata = metadata;
            return this._encryptData(content, iv);
          })
          .then(content => {
            json.content = content;
            return json;
          });
    }

    encryptContentToServer(json) {
      const iv = window.crypto.getRandomValues(new Uint8Array(16));
      json.iv = base64js.fromByteArray(iv);

      return this._encryptData(textEncoder.encode(json.content), iv)
          .then(content => {
            json.content = content;
            return json;
          });
    }

    /**
     * encrypt dataArrayBuffer using given iv
     */
    _encryptData(dataArrayBuffer, iv) {
      return crypto.subtle
          .encrypt(
              Object.assign(AES_KEY_SETTINGS, {iv}), this.encryptionKey,
              dataArrayBuffer)
          .then(
              encrypted_data =>
                  base64js.fromByteArray(new Uint8Array(encrypted_data)));
    }

    _generateVerificationToken() {
      const selectChars =
          '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
      const randomValues = crypto.getRandomValues(new Uint8Array(8));
      let result = '';
      randomValues.map(i => result += selectChars[i % selectChars.length]);
      return result;
    }

    _generateAuthenticationToken(
        verificationToken, publicKey, deviceId, timestamp) {
      return crypto.subtle
          .digest('SHA-512', textEncoder.encode([
            verificationToken,
            publicKey,
            deviceId,
            timestamp,
          ].join('')))
          .then(
              hash => [base64js.fromByteArray(new Uint8Array(hash)), '$',
                       timestamp]
                          .join(''));
    }

    /**
     * content decrypted to base64
     */
    decryptMessageFromServer(jsonData) {
      return new Promise(async resolve => {
        await this._decryptContent(jsonData);
        await this._decryptMetadata(jsonData);
        resolve(jsonData);
      });
    }

    async decryptEntriesContent(jsonData) {
      jsonData.entries = await Promise.all(
          jsonData.entries.map(this._decryptContent.bind(this)));
      return jsonData;
    }

    _decryptMetadata(jsonData) {
      return crypto.subtle
          .decrypt(
              Object.assign(AES_KEY_SETTINGS, {
                iv: base64js.toByteArray(jsonData.iv),
              }),
              this.encryptionKey, base64js.toByteArray(jsonData.metadata))
          .then(decrypted => {
            jsonData.metadata = textDecoder.decode(decrypted);
            return jsonData;
          });
    }

    _decryptContent(jsonData) {
      return crypto.subtle
          .decrypt(
              Object.assign(AES_KEY_SETTINGS, {
                iv: base64js.toByteArray(jsonData.iv),
              }),
              this.encryptionKey, base64js.toByteArray(jsonData.content))
          .then(decrypted => {
            if (jsonData.metadata && jsonData.metadata.type === 'file') {
              jsonData.content =
                  base64js.fromByteArray(new Uint8Array(decrypted));
            } else {
              jsonData.content = textDecoder.decode(decrypted);
            }
            return jsonData;
          });
    }

    /**
     * Recipient should contain public key and id to send to
     */
    sendEncryptionKey(recipient) {
      return crypto.subtle.exportKey('raw', this.encryptionKey)
          .then(
              rawKey =>
                  window.crypto.subtle
                      .importKey(
                          'spki',
                          this.makeByteArrayFromPemKey(recipient.public_key),
                          RSA_OAEP_KEY_SETTINGS, false, ['encrypt'])
                      .then(
                          importedKey =>
                              window.crypto.subtle
                                  .encrypt(
                                      RSA_OAEP_KEY_SETTINGS, importedKey,
                                      rawKey)
                                  .then(encoded_key => {
                                    const jsonToSend = {
                                      device_id: recipient.id,
                                      content: base64js.fromByteArray(
                                          new Uint8Array(encoded_key)),
                                    };
                                    return jsonToSend;
                                  })
                                  .then(json => this.signContent(json))
                                  .then(
                                      json => this.sendRequest(
                                          OPERA_TOUCH_SERVER_ENDPOINTS
                                              .CREATE_SHARED_KEY,
                                          json))));
    }

    signContent(json) {
      return crypto.subtle
          .importKey(
              'pkcs8', this.privateKey, RSA_PKCS1_KEY_SETTINGS, false, ['sign'])
          .then(
              key => crypto.subtle.sign(
                  RSA_PKCS1_KEY_SETTINGS, key,
                  textEncoder.encode(json.content)))
          .then(signature => {
            json.signature = base64js.fromByteArray(new Uint8Array(signature));
            return json;
          });
    }

    verifyContent(json, publicKey) {
      return new Promise((verified, nonverified) => {
        this.verifyContentByAlgorithm(json, publicKey, RSA_PKCS1_KEY_SETTINGS)
            .then(verified)
            .catch(() => {
              this.verifyContentByAlgorithm(
                      json, publicKey, RSA_PSS_KEY_SETTINGS)
                  .then(verified)
                  .catch(nonverified);
            });
      });
    }

    verifyContentByAlgorithm(json, publicKey, algorithm) {
      publicKey = this.makeByteArrayFromPemKey(publicKey);

      return crypto.subtle
          .importKey('spki', publicKey, algorithm, false, ['verify'])
          .then(
              key => crypto.subtle.verify(
                  algorithm, key, base64js.toByteArray(json.signature),
                  textEncoder.encode(json.content)));
    }


    getSharedKey(retry_empty_response = false) {
      return this
          .sendRequest(
              OPERA_TOUCH_SERVER_ENDPOINTS.GET_SHARED_KEY, null,
              retry_empty_response)
          .then(json => {
            const encryption_device =
                this._authorizedDevices[json.encrypted_by];
            if (!encryption_device) {
              throw new Error('Encrypted key by not trusted device');
            } else {
              return this.verifyContent(json, encryption_device.public_key)
                  .then(
                      verified =>
                          crypto.subtle
                              .decrypt(
                                  RSA_OAEP_KEY_SETTINGS, this.privateCryptoKey,
                                  base64js.toByteArray(json.content))
                              .then(
                                  decoded_raw_key => crypto.subtle.importKey(
                                      'raw', decoded_raw_key, AES_KEY_SETTINGS,
                                      true, ['encrypt', 'decrypt']))
                              .then(this._storeEncryptionKey.bind(this))
                              .then(() => {
                                this.sendRequest(
                                    OPERA_TOUCH_SERVER_ENDPOINTS.NOTIFY_DEVICES,
                                    {
                                      payload: JSON.stringify({
                                        'action': 'connected',
                                        'device_id': this.id,
                                      }),
                                    });
                                this._notifyExtensions({
                                  type: 'DEVICES_CONNECTED',
                                  value: encryption_device,
                                });
                                this.setNativeSending(
                                    true, encryption_device.group_id);
                                this.sendDesktopStateToServer();
                              }))
                  .catch(() => {
                    this._completeDataReset();
                    throw new Error('Signature could not be verified');
                  });
            }
          });
    }

    _extractPartialData(xhrObject, url) {
      return {
        url, data: xhrObject.responseText,
            type: xhrObject.getResponseHeader('content-type'),
            headers: xhrObject.getAllResponseHeaders(),
            responseURL: xhrObject.responseURL,
      }
    }

    getPartialUrl(url, byteLimit = 1024, extraHeaders = {}) {
      return new Promise((onSuccess, onError) => {
        const oReq = new XMLHttpRequest();
        let overlength = false;
        const wrapResponse = e => this._extractPartialData(e.target, url);
        const updateProgress = e => {
          if (!overlength && e.loaded >= byteLimit) {
            overlength = true;
            onSuccess(wrapResponse(e));
            oReq.abort();
          }
        };
        const transferCanceled = e => {
          if (!overlength) {
            onError(wrapResponse(e));
          }
        };

        oReq.addEventListener('progress', updateProgress, false);
        oReq.addEventListener('load', e => onSuccess(wrapResponse(e)), false);
        oReq.addEventListener('abort', transferCanceled, false);
        oReq.addEventListener('error', e => onError(wrapResponse(e)), false);
        oReq.open('GET', url);
        Object.entries(extraHeaders)
            .forEach(([param, value]) => x.setRequestHeader(param, value));
        oReq.send();
      });
    }

    sendRequest(endpoint, data, retry_empty_response = false) {
      let url = OPERA_TOUCH_SERVER_URL + endpoint.url;

      if (/{.*}/.test(endpoint.url)) {
        url = url.replace(/{([^}]*)}/g, (a, key) => {
          const temp = data[key];
          delete data[key];
          return temp;
        })
      }

      if (endpoint.method === 'GET' && data) {
        Object.entries(data).forEach(([param, value]) => {
          url = url.replace(`{${param}}`, value);
        });
      }

      const requestOptions = {
        method: endpoint.method,
        body: endpoint.method !== 'GET' && JSON.stringify(data) ||
            undefined,  // GET request need to have undefined body!
        headers: new Headers({
          'Content-Type': 'application/json',
        }),
      };

      const fetch_retry = (url, options, n) =>
          fetch(url, options)
              .then(response => {
                if (!/^2\d\d$/.test(String(response.status))) {
                  if (String(response.status) === '401') {
                    this._completeDataReset();
                  } else {
                    throw {
                      message: 'Non 2xx response, retrying',
                      status: response.status,
                    };
                  }
                }
                return response;
              })
              .then(response => response.json())
              .then(responseJson => {
                if (retry_empty_response && Array.isArray(responseJson) &&
                    responseJson.length === 0) {
                  throw {
                    message:
                        'Empty response, but should not be empty, retrying',
                  }
                }
                return responseJson;
              })
              .catch(error => {
                if (n === 1) {
                  throw error;
                }
                return (new Promise(resolve => setTimeout(resolve, 1000)))
                    .then(() => fetch_retry(url, options, n - 1));
              });

      // By default we sign every request, unless we explicitly not want to
      if (typeof endpoint.auth === 'undefined' || endpoint.auth) {
        this.signMessage(requestOptions);
      }
      return fetch_retry(url, requestOptions, 3);
    }

    async generateRSAKeys() {
      return new Promise(resolve => {
        crypto.subtle
            .generateKey(RSA_PSS_KEY_SETTINGS, true, ['sign', 'verify'])
            .then(signKey => {

              Promise
                  .all([
                    crypto.subtle.exportKey('spki', signKey.publicKey),
                    crypto.subtle.exportKey('pkcs8', signKey.privateKey),
                  ])
                  .then(([publicKey, privateKey]) => {

                    this.publicKey = publicKey;
                    this.privateKey = privateKey;

                    const publicKeyPEM = this.makePemFromByteArray(publicKey);
                    const privateKeyPEM =
                        this.makePemFromByteArray(privateKey, true);

                    storage.set({
                      [STORAGE_PRIVATE_KEY]: privateKeyPEM,
                      [STORAGE_PUBLIC_KEY]: publicKeyPEM,
                    });

                    this._importPrivateCryptoKey(privateKeyPEM).then(resolve);
                  });
            });
      });
    }

    async generateAESKey() {
      return new Promise((resolve, reject) => {
        window.crypto.subtle
            .generateKey(AES_KEY_SETTINGS, true, ['encrypt', 'decrypt'])
            .then(this._storeEncryptionKey.bind(this))
            .then(resolve)
            .catch(problem => {
              reject();
              console.log('Could not generate encryption key!:', problem);
            });
      });
    }

    _storeEncryptionKey(encryptionKey) {
      this.encryptionKey = encryptionKey;
      return crypto.subtle.exportKey('jwk', encryptionKey).then(exported => {
        storage.set({
          [STORAGE_ENCRYPTION_KEY]: JSON.stringify(exported),
        });
      });
    }

    /*
     * SHA256 is generated from request body so we need that,
     * Authorization header is also added here
     */
    signMessage(requestOptions) {
      requestOptions.headers.append('Authorization', `${this.auth_token}`);
    }

    _completeDataReset() {
      storage.clear();
      storage.set(
          {[STORAGE_RECENTLY_CLEARED_DATA]: '1'}, () => location.reload());
    }
  }

  window.OperaTouchCommunication = new TouchCommunication();
}
