ovdashboard/api/ovkiosk/dav_file.py

58 lines
1.4 KiB
Python
Raw Normal View History

2022-08-29 11:27:18 +00:00
import logging
from io import BytesIO
2022-08-31 01:29:44 +00:00
from threading import Lock
2022-08-29 11:27:18 +00:00
from typing import Any
2022-08-31 01:29:44 +00:00
from apscheduler.schedulers.asyncio import AsyncIOScheduler
2022-08-29 11:27:18 +00:00
from webdav3.client import Client, Resource
_logger = logging.getLogger(__name__)
class DavFile:
2022-08-31 01:29:44 +00:00
__instances = None
2022-08-29 11:27:18 +00:00
def __init__(self, client: Client, path: Any) -> None:
self.__resource: Resource = client.resource(path)
self.__buffer = BytesIO()
2022-08-31 01:29:44 +00:00
self.__lock = Lock()
# register
if DavFile.__instances is None:
DavFile.__instances = []
DavFile.__instances.append(self)
2022-08-29 11:27:18 +00:00
def update(self) -> None:
2022-08-31 01:29:44 +00:00
_logger.info(f"updating {self.__resource}")
2022-08-29 11:27:18 +00:00
with self.__lock:
self.__buffer.seek(0)
self.__buffer.truncate(0)
self.__resource.write_to(self.__buffer)
2022-08-31 01:29:44 +00:00
@classmethod
def refresh(cls, refresh_interval: int = 5) -> AsyncIOScheduler:
scheduler = AsyncIOScheduler()
2022-08-29 11:27:18 +00:00
2022-08-31 01:29:44 +00:00
def tick() -> None:
for davfile in DavFile.__instances:
davfile.update()
2022-08-29 11:27:18 +00:00
2022-08-31 01:29:44 +00:00
scheduler.add_job(tick)
scheduler.add_job(
tick, "interval",
seconds=refresh_interval,
)
scheduler.start()
2022-08-29 11:27:18 +00:00
2022-08-31 01:29:44 +00:00
return scheduler
2022-08-29 11:27:18 +00:00
@property
def bytes(self) -> bytes:
with self.__lock:
self.__buffer.seek(0)
return self.__buffer.read()
def __str__(self) -> str:
return self.bytes.decode(encoding="utf-8")