aboutsummaryrefslogblamecommitdiffstats
path: root/src/bbss/buttons.py
blob: 1def0104e83f8c647e01bb8730ccd1b9d3707ed7 (plain) (tree)
1
2
3
4
                                                                  
                                 

                                    











                                         

                                     
 
                                                        

                                               




                                                             

              
                                                
                                      





                                                   
from bbss.lists import BaseListFile, ListFileEntry, parse_listfile
from dataclasses import dataclass
from typing import Optional, Self
from collections.abc import Sequence
import requests

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

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

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

  def get(self) -> requests.Response:
    return requests.get(self.url())

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

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

  @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__ = ["ButtonListFileEntry", "ButtonListFile"]