Ejemplo n.º 1
0
class MatrixLogHandler(logging.Handler):
    """Log handler to send records to a Matrix room.

    :param base_url: the base URL of the Matrix homeserver to use.  This should not include the
        `_matrix/client/` part.
    :param room_id: the room ID to send the messages to.  The account must be in the room and must
        have the sufficient power level to send messages.  Note that this must be the room ID
        (!foo:bar.org), not an alias!
    :param username: a username to use for logging in if no access token was set
    :param password: a password to use for logging in if no access token was set
    :param token: a valid access token that can be used to identify the log handler to the Matrix
        homeserver.  This is the recommended way for authorization.  If not set, a
        username/password pair must be set so the handler can acquire an access token.
    :use_m_text: if `True`, the handler will send `m.text` messages instead of `m.notice` ones
        (which is intended for bots)
    :type base_url: str
    :type room_id: str
    :type username: str
    :type password: str
    :type token: str
    :type use_m_text: bool
    """
    def __init__(
            self,
            base_url,
            room_id,
            username=None,
            password=None,
            token=None,
            use_m_text=False,
            format='[%(levelname)s] [%(asctime)s] [%(name)s] - %(message)s'):
        logging.Handler.__init__(self)

        self.base_url = base_url
        self.username = username
        self.password = password
        self.room_id = room_id
        self.token = token
        self.use_m_text = use_m_text

        self.matrix = MatrixHttpApi(base_url, token=self.token)

        self.formatter = logging.Formatter(format)

    def _login(self):
        if self.username is None or self.password is None:
            raise ValueError(
                'Both username and password must be set if there is no token available!'
            )

        response = self.matrix.login('m.login.password',
                                     user=self.username,
                                     password=self.password)

        self.token = response['access_token']

    def _make_content(self, record):
        content = {
            'msgtype': 'm.text' if self.use_m_text else 'm.notice',
            'body': self.format(record),
        }

        return content

    def emit(self, record):
        content = self._make_content(record)

        try:
            if not self.token:
                self._login()

            self.matrix.send_message_event(self.room_id, 'm.room.message',
                                           content)
        except:
            self.handleError(record)
Ejemplo n.º 2
0
def startup(config):
    # setup api/endpoint
    login = config.json['user_id'][1:].split(":")[0]
    if not config.json['token']:
        matrix = MatrixHttpApi(config.json['url'])
        matrix.validate_certificate(config.json['cert_verify'])
        try:
            res = matrix.login(login_type="m.login.password",
                               user=login,
                               password=config.json['password'])
        except MatrixRequestError as err:
            log.error("Login error: %r" % err)
            exit()
        log.debug("Login result: %r" % res)
        config.json['token'] = res["access_token"]
        matrix.token = config.json['token']
    else:
        matrix = MatrixHttpApi(config.json['url'], config.json['token'])
        matrix.validate_certificate(config.json['cert_verify'])

    config.save()

    # Update Display Name if needed
    cur_dn = matrix.get_display_name(config.json['user_id'])
    if not login == cur_dn:
        matrix.set_display_name(config.json['user_id'], login)

    # root path for plugin search and locale load
    config.rootf = os.path.dirname(os.path.abspath(matrix_bot.__file__))
    log.debug("Matrix_bot root folder: %s" % config.rootf)
    log.debug("Matrix_bot configuration: %s" %
              json.dumps(config.json, indent=4, sort_keys=True))

    # setup engine
    engine = Engine(matrix, config)
    # Dytnamic plugin load from plugins folder
    osppath = os.path.join(config.rootf, "plugins")
    lst = os.listdir(osppath)
    for fil in lst:
        name, ext = os.path.splitext(fil)
        if (not os.path.isdir(os.path.join(osppath, fil)) and not fil[0] == "_"
                and ext in (".py")):
            try:
                mod = __import__("matrix_bot.plugins." + name, fromlist=["*"])
                for cls in inspect.getmembers(mod, inspect.isclass):
                    if hasattr(cls[1], "name"):
                        if not config.json['plugins'] or cls[
                                1].name in config.json['plugins']:
                            engine.add_plugin(cls[1])
                            log.info("Load plugin %s (%s) from %s" %
                                     (cls[1].name, cls[0],
                                      os.path.join("plugins", fil)))
                        else:
                            log.info(
                                "Skip plugin %s (%s) from %s - not listed in config"
                                % (cls[1].name, cls[0],
                                   os.path.join("plugins", fil)))
            except ImportError as err:
                log.error("Plugin module %s import error: %r" %
                          ("plugins." + fil, err))

    engine.setup()

    while True:
        try:
            log.info("Listening for incoming events.")
            engine.event_loop()
        except Exception as e:
            log.error("Ruh roh: %s", e)
        time.sleep(5)

    log.info("Terminating.")
def index(request):
    if request.method == 'POST':
        print("POST form")
        form = NameForm(request.POST)
        if form.is_valid():
            #for s in list(Session.objects.all()):
            #print(s.matrix_user_name)
            #Get username from db or create it, and fill out the information from the form
            #Add user_name to message to pass to chat view so it knows which session to open
            messages.add_message(request, messages.INFO,
                                 form.cleaned_data['your_name'])
            if not Session.objects.filter(
                    matrix_user_name=form.cleaned_data['your_name']):
                print("CREATE SESSION")
                session = Session.objects.create(
                    matrix_user_name=form.cleaned_data['your_name'],
                    matrix_room_name=form.cleaned_data['room'],
                    matrix_server=form.cleaned_data['server'],
                    message_count=form.cleaned_data['message_count'],
                    show_images=form.cleaned_data['show_images'])
                session.save()
                sys.stdout.flush()
            else:
                print("OPEN SESSION")
                session = Session.objects.get(
                    matrix_user_name=form.cleaned_data['your_name'])
                session.matrix_user_name = form.cleaned_data['your_name']
                session.matrix_room_name = form.cleaned_data['room']
                session.matrix_server = form.cleaned_data['server']
                session.message_count = form.cleaned_data['message_count']
                session.show_images = form.cleaned_data['show_images']
                session.save()
                sys.stdout.flush()
            try:
                print("LOGIN VARS")
                print("session.matrix_user_name ", session.matrix_user_name)
                print("form.cleaned_data['your_name'] ",
                      form.cleaned_data['your_name'])
                print("session.matrix_room_name ", session.matrix_room_name)
                print("form.cleaned_data['room'] ", form.cleaned_data['room'])
                print("session.matrix_server ", session.matrix_server)
                print("form.cleaned_data['server'] ",
                      form.cleaned_data['server'])
                print("session.message_count ", session.message_count)
                print("form.cleaned_data['message_count'] ",
                      form.cleaned_data['message_count'])
                print("session.show_images ", session.show_images)
                print("form.cleaned_data['show_images'] ",
                      form.cleaned_data['show_images'])
                print("session_token: ", str(session.matrix_token))

                print("Logging in to matrix")
                sys.stdout.flush()
                api = MatrixHttpApi(session.matrix_server)
                response = api.login('m.login.password',
                                     user=form.cleaned_data['your_name'],
                                     password=form.cleaned_data['your_pass'])
                session.matrix_token = response["access_token"]
                session.save()
                print("session_token: ", str(session.matrix_token))
                sys.stdout.flush()
            except MatrixRequestError as e:
                #return HttpResponseForbidden()
                return render(request, 'client_app/login.html', {
                    'form': form,
                    'login_error': True,
                    'error_text': str(e)
                })
            else:
                return HttpResponseRedirect('/chat')
    else:  #GET page returns form with initial values
        form = NameForm(
            initial={
                "room": "#cosmic_horror:matrix.org",
                "server": "https://matrix.org",
                "message_count": 1000
            })
    return render(request, 'client_app/login.html', {
        'form': form,
        'login_error': False
    })