Skip to content
Snippets Groups Projects
main.py 3.20 KiB
#!/usr/bin/env python

import json
import os
import re
import time

import requests


class Box:
    re_title = re.compile(r"Box:\s*(.*)$")
    re_weight = re.compile(r"\*\s*(.*)kg$")
    re_content = re.compile(r"\*\s*(.*)\s*$")
    re_size_2d = re.compile(r"\*\s*(\d+)[x\*](\d+)\s*$")
    re_size_3d = re.compile(r"\*\s*(\d+)[x\*](\d+)[x\*](\d+)\s*$")

    def __init__(self, lines):
        self.title = ""
        self.weight = ""
        self.size = ""
        self.content = []

        for line in lines:
            title = Box.re_title.match(line)
            if title:
                self.title = title[1]
                continue

            weight = Box.re_weight.match(line)
            if weight:
                self.weight = weight[1].strip()
                continue

            size_2d = Box.re_size_2d.match(line)
            if size_2d:
                self.size = f"{size_2d[1]}x{size_2d[2]}"
                continue

            size_3d = Box.re_size_3d.match(line)
            if size_3d:
                self.size = f"{size_3d[1]}x{size_3d[2]}x{size_3d[3]}"
                continue

            content = Box.re_content.match(line)
            if content:
                self.content.append(content[1])

    def __str__(self):
        return f"{self.title} ({self.size} | {self.weight} kg)"


class Loader:
    def __init__(self, url="https://pad.stratum0.org/p/inventar_eventfoo/export/txt", max_age=60):
        self._url = url
        self.boxes = []
        self._raw_lines = []

        cache_base = os.getenv("XDG_CACHE_HOME")
        if not cache_base:
            cache_base = os.path.join(os.getenv("HOME"), ".cache")
        cache_fn = os.path.join(cache_base, "hoa-inventory-boxes.json")

        reload = True
        if os.path.isfile(cache_fn):
            try:
                with open(cache_fn) as fh:
                    cache = json.load(fh)
                if time.time() - cache["ts"] < max_age:
                    reload = False
                    self._raw_lines = cache["raw"]
            except json.decoder.JSONDecodeError:
                pass

        if reload:
            self._load_via_http()
            with open(cache_fn, "w") as fh:
                json.dump({"ts": time.time(), "raw": self._raw_lines}, fh)
        else:
            self._raw_lines = cache["raw"]

        self._parse()

    def _load_via_http(self):
        r = requests.get(self._url)
        r.raise_for_status()
        self._raw_lines = [x.strip() for x in r.text.splitlines()]

    def _parse(self):
        in_list = False
        curr = []
        for line in self._raw_lines:
            if not in_list:
                if line.startswith("Box-Inventar"):
                    in_list = True
            else:
                if line.startswith("======="):
                    continue
                if line.startswith("Box: "):
                    # this starts a new block
                    if curr:
                        self.boxes.append(Box(curr))
                    curr = []
                if line:
                    curr.append(line)


def main():
    loader = Loader()
    for box in loader.boxes:
        print(box)
        for c in box.content:
            print(f"* {c}")


if __name__ == "__main__":
    main()