view sat_frontends/quick_frontend/ @ 3029:457ae6381e2a

doc: replaced deprecated installation link in INSTALL
author Goffi <>
date Wed, 14 Aug 2019 08:08:25 +0200
parents ab2696e34d29
children 9d0df638c8b4
line wrap: on
line source

#!/usr/bin/env python2
# -*- coding: utf-8 -*-

# helper class for making a SAT frontend
# Copyright (C) 2009-2019 Jérôme Poisson (

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# GNU Affero General Public License for more details.

# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <>.

from sat.core.i18n import _
from sat.core import log as logging

log = logging.getLogger(__name__)
from sat_frontends.primitivus.constants import Const as C

class ProfileRecord(object):
    """Class which manage data for one profile"""

    def __init__(self, profile=None, login=None, password=None):
        self._profile = profile
        self._login = login
        self._password = password

    def profile(self):
        return self._profile

    def profile(self, value):
        self._profile = value
        # if we change the profile,
        # we must have no login/password until backend give them
        self._login = self._password = None

    def login(self):
        return self._login

    def login(self, value):
        self._login = value

    def password(self):
        return self._password

    def password(self, value):
        self._password = value

class QuickProfileManager(object):
    """Class with manage profiles creation/deletion/connection"""

    def __init__(self, host, autoconnect=None):
        """Create the manager

        @param host: %(doc_host)s
        @param autoconnect(iterable): list of profiles to connect automatically
        """ = host
        self._autoconnect = bool(autoconnect)
        self.current = ProfileRecord()

    def go(self, autoconnect):
        if self._autoconnect:

    def autoconnect(self, profile_keys):
        """Automatically connect profiles

        @param profile_keys(iterable): list of profile keys to connect
        if not profile_keys:
            log.warning("No profile given to autoconnect")
        self._autoconnect = True
        self._autoconnect_profiles = []

    def _do_autoconnect(self, profile_keys):
        """Connect automatically given profiles

        @param profile_kes(iterable): profiles to connect
        assert self._autoconnect

        def authenticate_cb(data, cb_id, profile):

            if C.bool(data.pop("validated", C.BOOL_FALSE)):
                if len(self._autoconnect_profiles) == len(profile_keys):
                    # all the profiles have been validated
                # a profile is not validated, we go to manual mode
                self._autoconnect = False
  , callback=authenticate_cb, profile=profile)

        def getProfileNameCb(profile):
            if not profile:
                # FIXME: this method is not handling manual mode correclty anymore
                #        must be thought to be handled asynchronously
                self._autoconnect = False  # manual mode
                msg = _("Trying to plug an unknown profile key ({})".format(profile_key))
      "Profile plugging in error"), msg, "error")
                    C.AUTHENTICATE_PROFILE_ID, callback=authenticate_cb, profile=profile

        def getProfileNameEb(failure):
            log.error("Can't retrieve profile name: {}".format(failure))

        for profile_key in profile_keys:
                profile_key, callback=getProfileNameCb, errback=getProfileNameEb

    def getParamError(self, __):"Error"), _("Can't get profile parameter"), "error")

    ## Helping methods ##

    def _getErrorMessage(self, reason):
        """Return an error message corresponding to profile creation error

        @param reason (str): reason as returned by profileCreate
        @return (unicode): human readable error message
        if reason == "ConflictError":
            message = _("A profile with this name already exists")
        elif reason == "CancelError":
            message = _("Profile creation cancelled by backend")
        elif reason == "ValueError":
            message = _(
                "You profile name is not valid"
            )  # TODO: print a more informative message (empty name, name starting with '@')
            message = _("Can't create profile ({})").format(reason)
        return message

    def _deleteProfile(self):
        """Delete the currently selected profile"""
        if self.current.profile:
                self.current.profile, callback=self.refillProfiles

    ## workflow methods (events occuring during the profiles selection) ##

    # These methods must be called by the frontend at some point

    def _onConnectProfiles(self):
        """Connect the profiles and start the main widget"""
        if self._autoconnect:
                _("Internal error"),
                _("You can't connect manually and automatically at the same time"),
        profiles = self.getProfiles()
        if not profiles:
                _("No profile selected"),
                _("You need to create and select at least one profile before connecting"),
            # All profiles in the list are already validated, so we can plug them directly

    def getConnectionParams(self, profile):
        """Get login and password and display them

        @param profile: %(doc_profile)s

    def updateConnectionParams(self):
        """Check if connection parameters have changed, and update them if so"""
        if self.current.profile:
            login = self.getJID()
            password = self.getPassword()
            if login != self.current.login and self.current.login is not None:
                self.current.login = login
                    "JabberID", login, "Connection", profile_key=self.current.profile
      "login updated for profile [{}]".format(self.current.profile))
            if password != self.current.password and self.current.password is not None:
                self.current.password = password
                    "Password", password, "Connection", profile_key=self.current.profile
                    "password updated for profile [{}]".format(self.current.profile)

    ## graphic updates (should probably be overriden in frontends) ##

    def resetFields(self):
        """Set profile to None, and reset fields"""
        self.current.profile = None

    def refillProfiles(self):
        """Rebuild the list of profiles"""
        profiles =

    ## Method which must be implemented by frontends ##

    # get/set data

    def getProfiles(self):
        """Return list of selected profiles

        Must be implemented by frontends
        @return (list): list of profiles
        raise NotImplementedError

    def setProfiles(self, profiles):
        """Update the list of profiles"""
        raise NotImplementedError

    def getJID(self):
        """Get current jid

        Must be implemented by frontends
        @return (unicode): current jabber id
        raise NotImplementedError

    def getPassword(self):
        """Get current password

        Must be implemented by frontends
        @return (unicode): current password
        raise NotImplementedError

    def setJID(self, jid_):
        """Set current jid

        Must be implemented by frontends
        @param jid_(unicode): jabber id to set
        raise NotImplementedError

    def setPassword(self, password):
        """Set current password

        Must be implemented by frontends
        raise NotImplementedError

    # dialogs

    # Note: a method which check profiles change must be implemented too