"""Сенсоры Paperless в HA.""" import re CFG = "/opt/smart-lxc/homeassistant/config/configuration.yaml" SEC = "/opt/smart-lxc/homeassistant/config/secrets.yaml" PT = open("/tmp/paperless-token", encoding="utf-8").read().strip() sec = open(SEC, encoding="utf-8").read() if "paperless_token" not in sec: with open(SEC, "a", encoding="utf-8") as f: f.write(f'\npaperless_token: "Token {PT}"\n') print(" секрет добавлен") block = ''' - resource: http://192.168.1.105:8000/api/documents/?page_size=1 headers: Authorization: !secret paperless_token scan_interval: 600 sensor: - name: "Paperless документов" unique_id: paperless_documents value_template: "{{ value_json.count }}" - resource: http://192.168.1.105:8000/api/tags/?page_size=1 headers: Authorization: !secret paperless_token scan_interval: 600 sensor: - name: "Paperless тегов" unique_id: paperless_tags value_template: "{{ value_json.count }}" ''' s = open(CFG, encoding="utf-8").read() if "paperless_documents" in s: print(" сенсоры уже есть") else: lines = s.split("\n") start = next((i for i, l in enumerate(lines) if re.match(r"^rest:\s*$", l)), None) if start is None: s = s.rstrip() + "\n\nrest:\n" + block else: end = len(lines) for j in range(start + 1, len(lines)): if lines[j] and not lines[j].startswith((" ", "\t")) and not lines[j].startswith("#"): end = j break lines[end:end] = block.split("\n") s = "\n".join(lines) open(CFG, "w", encoding="utf-8").write(s) print(" сенсоры добавлены")