aboutsummaryrefslogtreecommitdiffstats
path: root/src/bbss/sizes.py
blob: c1d58f5ccac5d568e6ffd5bef42b57382324ee75 (plain) (blame)
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
from bbss.lists import BaseListFile, ListFileEntry, parse_listfile
from bbss.buttons import ButtonListFile
from dataclasses import dataclass
from typing import Optional, Self, Tuple
from collections.abc import Sequence
import requests
import re

@dataclass(frozen=True)
class SizeListFileEntry(ListFileEntry):
  root: str

  def url(self) -> str:
    return self.root + "/" + self.entry + "/list.txt"

  def exists(self) -> bool:
    return requests.head(self.url()).ok

  def get(self) -> Optional[ButtonListFile]:
    return ButtonListFile.from_url(self.url())

  def dims(self) -> Optional[Tuple[int, int]]:
    matches = re.match("^([0-9]+)x([0-9]+)$", self.entry)
    return (matches[1], matches[2]) if matches is not None else None

class SizeListFile(BaseListFile[SizeListFileEntry]):
  def __init__(self, contents: str, root: str):
    super().__init__(contents)
    self._root = root

    def construct_entry(entry: str, comment: Optional[str]):
      return SizeListFileEntry(entry, comment, root)
    self._entries = parse_listfile(contents, construct_entry)

    for entry in self._entries:
      if entry.entry == "88x31":
        break
    else:
      default = SizeListFileEntry("88x31", None, root)
      if default.exists():
        self._entries.append(default)

  @classmethod
  def from_url(cls, url: str) -> Optional[Self]:
    (root, _, _) = url.rpartition('/')
    req = requests.get(url, stream = False)
    if not req.ok:
      return None
    return cls(req.text, root)

__all__ = ["SizeListFileEntry", "SizeListFile"]