Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
  • Loading branch information
J-Lindvig authored Mar 3, 2023
1 parent 8a09fb6 commit ce07e21
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 73 deletions.
117 changes: 45 additions & 72 deletions custom_components/bibliotek_dk/library_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
DEBUG = True

#### KEYS
# CHECKLIST = "CHECKLIST" # JS
DEBTS = "DEBTS"
LOANS = "LOANS"
LOANS_OVERDUE = "LOANS_OVERDUE"
Expand All @@ -27,18 +26,10 @@
MY_PAGES = "MY_PAGES"
RESERVATIONS = "RESERVATIONS"
RESERVATIONS_READY = "RESERVATIONS_READY"
# SEARCHES = "SEARCHES" # JS
USER_PROFILE = "USER_PROFILE"

#### SEARCH STRINGS
LOGGED_IN = "logget ind"
LOGGED_IN_ELIB = "Logged-in"
EBOOKS = "ebøger"
AUDIO_BOOKS = "lydbøger"

#### LINKS TO USER PAGES
URLS = {
# CHECKLIST: "/user/me/checklist", # JS
DEBTS: "/user/me/status-debts",
LOANS: "/user/me/status-loans",
LOANS_OVERDUE: "/user/me/status-loans-overdue",
Expand All @@ -47,32 +38,23 @@
MY_PAGES: "/user/me/view",
RESERVATIONS: "/user/me/status-reservations",
RESERVATIONS_READY: "/user/me/status-reservations-ready",
# SEARCHES: "/user/me/followed-searches", # JS
USER_PROFILE: "/user/me/edit",
}

#### SEARCH STRINGS
LOGGED_IN = "logget ind"
LOGGED_IN_ELIB = "Logged-in"
EBOOKS = "ebøger"
AUDIO_BOOKS = "lydbøger"

_LOGGER: logging.Logger = logging.getLogger(__package__)
_LOGGER = logging.getLogger(__name__)

"""
Library holds the engine of the scraping.
"""


class Library:
host, libraryName, icon, user = None, None, None, None
loggedIn, eLoggedIn, running = False, False, False

"""
Initialize of Library takes these arguments:
userId: (CPR-number) or Loaner-ID
pincode: Pincode
host, URL to your local library
A libraryUser object is created from the credentials.
"""

def __init__(
self, userId: str, pincode: str, host=str, libraryName=None, agency=None
) -> None:
Expand All @@ -96,8 +78,6 @@ def update(self):
self.running = True

if self.login():
# self.fetchUserLinks() # Soon obsolete....

# Only fetch user info once
if not self.user.name:
self.fetchUserInfo()
Expand Down Expand Up @@ -131,7 +111,6 @@ def update(self):
return True

#### PRIVATE BEGIN ####

# Retrieve a webpage with either GET/POST
def _fetchPage(self, url=str, payload=None) -> BS:
# If payload, use POST
Expand Down Expand Up @@ -296,6 +275,9 @@ def login(self):
self.loggedIn = self._titleInSoup(soup, LOGGED_IN)
self.libraryName = soup.title.string.split("|")[0].strip() # REDUNDANT

if DEBUG:
_LOGGER.debug(f"({self.user.userId[:-4]}) is logged in: {self.loggedIn}")

return self.loggedIn

def login_eLib(self) -> tuple:
Expand Down Expand Up @@ -327,6 +309,11 @@ def login_eLib(self) -> tuple:
)
self.loggedIn = soup if self._titleInSoup(soup, LOGGED_IN_ELIB) else False

if DEBUG:
_LOGGER.debug(
f"({self.user.userId[:-4]}) is logged in @{self.host_elib}: {bool(self.loggedIn)}"
)

return self.loggedIn, soup

def logout(self, url=None):
Expand All @@ -336,6 +323,10 @@ def logout(self, url=None):
self.loggedIn = not self.session.get(url).status_code == 200
if not self.loggedIn:
self.session.close()
if DEBUG:
_LOGGER.debug(
f"({self.user.userId[:-4]}) is logged OUT @{url}: {not bool(self.loggedIn)}"
)

def fecthELibUsedQuota(self, soup):
for li in soup.h1.parent.div.ul.find_all("li"):
Expand All @@ -347,19 +338,10 @@ def fecthELibUsedQuota(self, soup):
elif result.group(3) == AUDIO_BOOKS:
self.user.audioBooks = result.group(1)
self.user.audioBooksQuota = result.group(2)

# Fetch the links to the different pages from the "My Pages page
def fetchUserLinks(self):
## Fetch "My view"
soup = self._fetchPage(self.host + URLS[MY_PAGES])

# Fetch usefull user states - OBSOLETE WHEN FETCHING DETAILS
for a_status in soup.select_one("ul[class='list-links specials']").find_all(
"a"
):
if URLS[DEBTS] in a_status["href"]:
self.user.debts = a_status.parent.find_all("span")[-1].string
print(a_status.parent.find_all("span")[-1])
if DEBUG:
_LOGGER.debug(
f"({self.user.userId[:-4]}), done fetching eLibQuotas: ({self.user.eBooks}/{self.user.eBooksQuota}) ({self.user.audioBooks}/{self.user.audioBooksQuota})"
)

# Get information on the user
def fetchUserInfo(self):
Expand Down Expand Up @@ -406,6 +388,11 @@ def fetchUserInfo(self):
self.user.pickupLibrary = library.string
break

if DEBUG:
_LOGGER.debug(
f"({self.user.userId[:-4]}) is actually '{self.user.name}'. Pickup library is {self.user.pickupLibrary}"
)

# Get the loans with all possible details
def fetchLoans(self, soup=None):
# Fetch the loans page
Expand Down Expand Up @@ -440,44 +427,17 @@ def fetchLoans(self, soup=None):
# Add the loan to the stack
tempList.append(obj)

if DEBUG:
_LOGGER.debug(f"{self.user.name} has {len(tempList)} loans")

return tempList

def fetchLoansOverdue(self):
if DEBUG:
_LOGGER.debug(f"{self.user.name}, Reusing the fetchLoans function...")
# Fetch the loans overdue page
# soup = self._fetchPage(self.host + URLS[LOANS_OVERDUE])

return self.fetchLoans(self._fetchPage(self.host + URLS[LOANS_OVERDUE]))

# # From the <div> containing part of the class
# # for material in soup.select("div[class*='material-item']"):
# tempList = []
# for material in self._getMaterials(soup):
# # Create an instance of libraryLoan
# obj = libraryLoan()

# # Renewable
# obj.renewId, obj.renewAble = self._getIdInfo(material)

# # URL and image
# obj.url, obj.coverUrl = self._getMaterialUrls(material)

# # Type, title and creator
# obj.title, obj.creators, obj.type = self._getMaterialInfo(material)

# # Details
# for keys, value in self._getDetails(material):
# if "loan-date" in keys:
# obj.loanDate = self._getDatetime(value)
# elif "expire-date" in keys:
# obj.expireDate = self._getDatetime(value)
# elif "material-number" in keys:
# obj.id = value

# # Add the loan to the stack
# tempList.append(obj)

# return tempList

# Get the current reservations
def fetchReservations(self):
# Fecth the reservations page
Expand Down Expand Up @@ -512,6 +472,9 @@ def fetchReservations(self):
# Add the reservation to the stack
tempList.append(obj)

if DEBUG:
_LOGGER.debug(f"{self.user.name} has {len(tempList)} reservations")

return tempList

# Get the reservations which are ready
Expand Down Expand Up @@ -548,6 +511,11 @@ def fetchReservationsReady(self) -> list:
# Add the reservation to the stack
tempList.append(obj)

if DEBUG:
_LOGGER.debug(
f"{self.user.name} has {len(tempList)} reservations ready for pickup"
)

return tempList

# Get debts, if any, from the Library
Expand Down Expand Up @@ -583,6 +551,11 @@ def fetchDebts(self) -> tuple:
amount = soup.select_one("span[class='amount']")
amount = self._removeCurrency(amount.string) if amount else 0.0

if DEBUG:
_LOGGER.debug(
f"{self.user.name} has {len(tempList)} debts with a total of {amount}"
)

return tempList, amount


Expand Down
2 changes: 1 addition & 1 deletion custom_components/bibliotek_dk/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,6 @@
"codeowners": ["@J-Lindvig"],
"requirements": ["beautifulsoup4", "html.parser"],
"iot_class": "cloud_polling",
"version": "0.3.1",
"version": "0.3.2",
"config_flow": true
}

0 comments on commit ce07e21

Please sign in to comment.