Skip to content
Snippets Groups Projects
api.py 1.74 KiB
Newer Older
# Copyright (c) 2019 Nico Alt
# SPDX-License-Identifier: AGPL-3.0-only
# License-Filename: LICENSE.md
Nico's avatar
Nico committed
import os
Nico's avatar
Nico committed
from threading import Thread
from briar_wrapper.api_thread import ApiThread
from briar_wrapper.constants import BRIAR_AUTH_TOKEN, BRIAR_DB
Nico's avatar
Nico committed
from briar_wrapper.models.socket_listener import SocketListener
Nico's avatar
Nico committed
    auth_token = None
    socket_listener = None

    _api_thread = None
Nico's avatar
Nico committed

    def __init__(self, headless_jar):
        self._api_thread = ApiThread(self, headless_jar)
    @staticmethod
    def has_account():
Nico's avatar
Nico committed
        return os.path.isfile(BRIAR_DB)
Nico's avatar
Nico committed
    def is_running(self):
        return self._api_thread.is_running()
Nico's avatar
Nico committed

    def login(self, password, callback):
Nico's avatar
Nico committed
        self._start_and_watch(callback)
        startup_thread = Thread(target=self._api_thread.login,
                                args=(password,), daemon=True)
Nico's avatar
Nico committed
        startup_thread.start()
    def register(self, credentials, callback):
Nico's avatar
Nico committed
        if len(credentials) != 2:
            raise Exception("Can't process credentials")
        self._start_and_watch(callback)
        startup_thread = Thread(target=self._api_thread.register,
                                args=(credentials,), daemon=True)
Nico's avatar
Nico committed
        startup_thread.start()
        self._api_thread.stop()
Nico's avatar
Nico committed

    def _start_and_watch(self, callback):
        self._api_thread.start()
        self._api_thread.watch(callback)
Nico's avatar
Nico committed

    def on_successful_startup(self, callback):
        self._load_auth_token()
        self.socket_listener = SocketListener(self)
        callback(True)

Nico's avatar
Nico committed
    def _load_auth_token(self):
        if not Api.has_account():
            raise Exception("Can't load authentication token")
        with open(BRIAR_AUTH_TOKEN, 'r') as file:
Nico's avatar
Nico committed
            self.auth_token = file.read()