Passed
Push — main ( ffd0cb...e582cb )
by Jochen
04:07
created

weitersager.processor.Processor.run()   A

Complexity

Conditions 3

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 8.6667

Importance

Changes 0
Metric Value
cc 3
eloc 7
nop 1
dl 0
loc 9
ccs 1
cts 7
cp 0.1429
crap 8.6667
rs 10
c 0
b 0
f 0
1
"""
2
weitersager.processor
3
~~~~~~~~~~~~~~~~~~~~~
4
5
Connect HTTP server and IRC bot.
6
7
:Copyright: 2007-2020 Jochen Kupperschmidt
8
:License: MIT, see LICENSE for details.
9
"""
10
11 1
from time import sleep
12 1
from typing import Any, Dict, Optional, Set, Tuple
13
14 1
from .config import Config
15 1
from .http import start_receive_server
16 1
from .irc import create_bot
17 1
from .signals import channel_joined, message_approved, message_received
18 1
from .util import log
19
20
21 1
class Processor:
22
23 1
    def __init__(self) -> None:
24 1
        self.enabled_channel_names: Set[str] = set()
25
26 1
    def connect_to_signals(self) -> None:
27 1
        channel_joined.connect(self.enable_channel)
28 1
        message_received.connect(self.handle_message)
29
30 1
    def enable_channel(self, sender, *, channel_name=None) -> None:
31 1
        log('Enabled forwarding to channel {}.', channel_name)
32 1
        self.enabled_channel_names.add(channel_name)
33
34 1
    def handle_message(
35
        self,
36
        sender: Optional[Any],
37
        *,
38
        channel_name: str,
39
        text: str,
40
        source_address: Tuple[str, int],
41
    ) -> None:
42
        """Log and announce an incoming message."""
43 1
        source = f'{source_address[0]}:{source_address[1]:d}'
44
45 1
        log(
46
            'Received message from {} for channel {} with text "{}"',
47
            source,
48
            channel_name,
49
            text,
50
        )
51
52 1
        if channel_name not in self.enabled_channel_names:
53
            log(
54
                'Could not send message to channel {}, not joined.',
55
                channel_name,
56
            )
57
            return
58
59 1
        message_approved.send(channel_name=channel_name, text=text)
60
61 1
    def run(self) -> None:
62
        """Run the main loop."""
63
        try:
64
            while True:
65
                sleep(0.5)
66
        except KeyboardInterrupt:
67
            pass
68
69
        log('Shutting down ...')
70
71
72 1
def start(config: Config, **options: Dict[str, Any]) -> None:
73
    """Start the IRC bot and HTTP listen server."""
74
    bot = create_bot(config.irc, **options)
75
    message_approved.connect(bot.say)
76
77
    processor = Processor()
78
79
    # Up to this point, no signals must have been sent.
80
81
    processor.connect_to_signals()
82
83
    # Signals are allowed be sent from here on.
84
85
    start_receive_server(config.http)
86
    bot.start()
87
88
    processor.run()
89
90
    bot.disconnect('Bye.')  # Joins bot thread.
91