summaryrefslogtreecommitdiff
path: root/src/openwrt_log_analyzer.py
blob: 35b755fb23d9c570e1ca7c1156545921fc157d17 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#!/usr/bin/env python3
import home.telegram as telegram

from home.config import config
from home.database import BotsDatabase, SimpleState

"""
config.toml example:

[simple_state]
file = "/home/user/.config/openwrt_log_analyzer/state.txt"

[mysql]
host = "localhost"
database = ".."
user = ".."
password = ".."

[devices]
Device1 = "00:00:00:00:00:00"
Device2 = "01:01:01:01:01:01"

[telegram]
chat_id = ".."
token = ".."
parse_mode = "HTML"

[openwrt_log_analyzer]
limit = 10
"""


def main(mac: str,
         title: str,
         ap: int) -> int:
    db = BotsDatabase()

    data = db.get_openwrt_logs(filter_text=mac,
                               min_id=state['last_id'],
                               access_point=ap,
                               limit=config['openwrt_log_analyzer']['limit'])
    if not data:
        return 0

    max_id = 0
    for log in data:
        if log.id > max_id:
            max_id = log.id

    text = '\n'.join(map(lambda s: str(s), data))
    telegram.send_message(f'<b>{title} (AP #{ap})</b>\n\n' + text)

    return max_id


if __name__ == '__main__':
    config.load_app('openwrt_log_analyzer')
    for ap in config['openwrt_log_analyzer']['aps']:
        state_file = config['simple_state']['file']
        state_file = state_file.replace('.txt', f'-{ap}.txt')

        state = SimpleState(file=state_file,
                            default={'last_id': 0})

        max_last_id = 0
        for name, mac in config['devices'].items():
            last_id = main(mac, title=name, ap=ap)
            if last_id > max_last_id:
                max_last_id = last_id

        if max_last_id:
            state['last_id'] = max_last_id