2021-05-15 18:57:17 +02:00
|
|
|
import re
|
2021-05-15 15:18:51 +02:00
|
|
|
from pathlib import PurePath
|
2021-05-23 17:24:05 +02:00
|
|
|
from typing import Any, Awaitable, Callable, Dict, List, Optional, Set, TypeVar, Union
|
2021-05-15 15:18:51 +02:00
|
|
|
|
|
|
|
import aiohttp
|
2021-05-21 12:02:51 +02:00
|
|
|
from aiohttp import hdrs
|
2021-05-15 18:57:17 +02:00
|
|
|
from bs4 import BeautifulSoup, Tag
|
2021-05-16 14:32:53 +02:00
|
|
|
|
2021-05-19 21:34:36 +02:00
|
|
|
from PFERD.authenticators import Authenticator
|
|
|
|
from PFERD.config import Config
|
2021-05-22 23:23:21 +02:00
|
|
|
from PFERD.crawler import CrawlError, CrawlerSection, CrawlWarning, anoncritical
|
|
|
|
from PFERD.http_crawler import HttpCrawler
|
2021-05-21 12:02:51 +02:00
|
|
|
from PFERD.logging import ProgressBar, log
|
|
|
|
from PFERD.output_dir import FileSink, Redownload
|
2021-05-19 21:34:36 +02:00
|
|
|
from PFERD.utils import soupify, url_set_query_param
|
2021-05-15 15:18:51 +02:00
|
|
|
|
2021-05-23 11:30:16 +02:00
|
|
|
from ...utils import fmt_path
|
2021-05-19 21:37:10 +02:00
|
|
|
from .file_templates import link_template_plain, link_template_rich
|
2021-05-19 21:34:36 +02:00
|
|
|
from .kit_ilias_html import IliasElementType, IliasPage, IliasPageElement
|
2021-05-15 15:18:51 +02:00
|
|
|
|
2021-05-15 20:42:18 +02:00
|
|
|
TargetType = Union[str, int]
|
2021-05-15 15:18:51 +02:00
|
|
|
|
|
|
|
|
2021-05-19 21:41:17 +02:00
|
|
|
class KitIliasWebCrawlerSection(CrawlerSection):
|
2021-05-15 15:18:51 +02:00
|
|
|
|
2021-05-15 20:42:18 +02:00
|
|
|
def target(self) -> TargetType:
|
|
|
|
target = self.s.get("target")
|
|
|
|
if not target:
|
|
|
|
self.missing_value("target")
|
2021-05-15 15:18:51 +02:00
|
|
|
|
2021-05-15 20:42:18 +02:00
|
|
|
if re.fullmatch(r"\d+", target):
|
|
|
|
# Course id
|
|
|
|
return int(target)
|
|
|
|
if target == "desktop":
|
|
|
|
# Full personal desktop
|
|
|
|
return target
|
|
|
|
if target.startswith("https://ilias.studium.kit.edu"):
|
|
|
|
# ILIAS URL
|
|
|
|
return target
|
2021-05-15 15:18:51 +02:00
|
|
|
|
2021-05-15 20:42:18 +02:00
|
|
|
self.invalid_value("target", target, "Should be <course id | desktop | kit ilias URL>")
|
2021-05-15 15:18:51 +02:00
|
|
|
|
|
|
|
def tfa_auth(self, authenticators: Dict[str, Authenticator]) -> Optional[Authenticator]:
|
|
|
|
value = self.s.get("tfa_auth")
|
|
|
|
if not value:
|
|
|
|
return None
|
|
|
|
|
|
|
|
auth = authenticators.get(f"auth:{value}")
|
|
|
|
if auth is None:
|
|
|
|
self.invalid_value("auth", value, "No such auth section exists")
|
|
|
|
return auth
|
|
|
|
|
2021-05-17 21:31:22 +02:00
|
|
|
def link_file_redirect_delay(self) -> int:
|
|
|
|
return self.s.getint("link_file_redirect_delay", fallback=-1)
|
|
|
|
|
|
|
|
def link_file_use_plaintext(self) -> bool:
|
2021-05-23 13:26:23 +02:00
|
|
|
return self.s.getboolean("link_file_plaintext", fallback=False)
|
2021-05-17 21:31:22 +02:00
|
|
|
|
2021-05-23 13:26:23 +02:00
|
|
|
def videos(self) -> bool:
|
|
|
|
return self.s.getboolean("videos", fallback=False)
|
2021-05-23 12:36:09 +02:00
|
|
|
|
2021-05-15 15:18:51 +02:00
|
|
|
|
2021-05-15 20:42:18 +02:00
|
|
|
_DIRECTORY_PAGES: Set[IliasElementType] = set([
|
|
|
|
IliasElementType.EXERCISE,
|
|
|
|
IliasElementType.FOLDER,
|
|
|
|
IliasElementType.MEETING,
|
|
|
|
IliasElementType.VIDEO_FOLDER,
|
|
|
|
IliasElementType.VIDEO_FOLDER_MAYBE_PAGINATED,
|
|
|
|
])
|
|
|
|
|
2021-05-23 12:36:09 +02:00
|
|
|
_VIDEO_ELEMENTS: Set[IliasElementType] = set([
|
|
|
|
IliasElementType.VIDEO,
|
|
|
|
IliasElementType.VIDEO_PLAYER,
|
|
|
|
IliasElementType.VIDEO_FOLDER,
|
|
|
|
IliasElementType.VIDEO_FOLDER_MAYBE_PAGINATED,
|
|
|
|
])
|
|
|
|
|
2021-05-19 22:01:09 +02:00
|
|
|
AWrapped = TypeVar("AWrapped", bound=Callable[..., Awaitable[None]])
|
|
|
|
|
|
|
|
|
2021-05-20 14:58:54 +02:00
|
|
|
def _iorepeat(attempts: int, name: str) -> Callable[[AWrapped], AWrapped]:
|
2021-05-19 22:01:09 +02:00
|
|
|
def decorator(f: AWrapped) -> AWrapped:
|
2021-05-23 00:28:27 +02:00
|
|
|
async def wrapper(*args: Any, **kwargs: Any) -> None:
|
2021-05-20 14:58:54 +02:00
|
|
|
last_exception: Optional[BaseException] = None
|
|
|
|
for round in range(attempts):
|
2021-05-19 22:01:09 +02:00
|
|
|
try:
|
2021-05-23 00:28:27 +02:00
|
|
|
await f(*args, **kwargs)
|
2021-05-19 22:01:09 +02:00
|
|
|
return
|
|
|
|
except aiohttp.ContentTypeError: # invalid content type
|
|
|
|
raise CrawlWarning("ILIAS returned an invalid content type")
|
|
|
|
except aiohttp.TooManyRedirects:
|
|
|
|
raise CrawlWarning("Got stuck in a redirect loop")
|
2021-05-20 14:58:54 +02:00
|
|
|
except aiohttp.ClientPayloadError as e: # encoding or not enough bytes
|
|
|
|
last_exception = e
|
|
|
|
except aiohttp.ClientConnectionError as e: # e.g. timeout, disconnect, resolve failed, etc.
|
|
|
|
last_exception = e
|
2021-05-23 11:30:16 +02:00
|
|
|
log.explain_topic(f"Retrying operation {name}. Retries left: {attempts - 1 - round}")
|
2021-05-20 14:58:54 +02:00
|
|
|
|
|
|
|
if last_exception:
|
2021-05-23 11:30:16 +02:00
|
|
|
message = f"Error in I/O Operation: {last_exception}"
|
2021-05-20 14:58:54 +02:00
|
|
|
raise CrawlWarning(message) from last_exception
|
|
|
|
raise CrawlError("Impossible return in ilias _iorepeat")
|
2021-05-19 22:01:09 +02:00
|
|
|
|
|
|
|
return wrapper # type: ignore
|
|
|
|
return decorator
|
|
|
|
|
2021-05-15 20:42:18 +02:00
|
|
|
|
2021-05-23 00:28:27 +02:00
|
|
|
def _wrap_io_in_warning(name: str) -> Callable[[AWrapped], AWrapped]:
|
|
|
|
"""
|
|
|
|
Wraps any I/O exception in a CrawlWarning.
|
|
|
|
"""
|
|
|
|
return _iorepeat(1, name)
|
|
|
|
|
|
|
|
|
|
|
|
# Crawler control flow:
|
|
|
|
#
|
|
|
|
# crawl_desktop -+
|
|
|
|
# |
|
|
|
|
# crawl_course --+
|
|
|
|
# |
|
2021-05-23 12:24:10 +02:00
|
|
|
# @_io_repeat | # retries internally (before the bar)
|
2021-05-23 00:28:27 +02:00
|
|
|
# +- crawl_url <-+
|
|
|
|
# |
|
|
|
|
# |
|
|
|
|
# | @_wrap_io_exception # does not need to retry as children acquire bars
|
|
|
|
# +> crawl_ilias_element -+
|
|
|
|
# ^ |
|
|
|
|
# | @_io_repeat | # retries internally (before the bar)
|
|
|
|
# +- crawl_ilias_page <---+
|
|
|
|
# | |
|
|
|
|
# +> get_page | # Handles and retries authentication
|
|
|
|
# |
|
|
|
|
# @_io_repeat | # retries internally (before the bar)
|
|
|
|
# +- download_link <---+
|
|
|
|
# | |
|
|
|
|
# +> resolve_target | # Handles and retries authentication
|
|
|
|
# |
|
|
|
|
# @_io_repeat | # retries internally (before the bar)
|
|
|
|
# +- download_video <---+
|
|
|
|
# | |
|
|
|
|
# | @_io_repeat | # retries internally (before the bar)
|
|
|
|
# +- download_file <---+
|
|
|
|
# |
|
|
|
|
# +> stream_from_url # Handles and retries authentication
|
|
|
|
|
2021-05-19 21:41:17 +02:00
|
|
|
class KitIliasWebCrawler(HttpCrawler):
|
2021-05-15 15:18:51 +02:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
name: str,
|
2021-05-19 21:41:17 +02:00
|
|
|
section: KitIliasWebCrawlerSection,
|
2021-05-15 15:18:51 +02:00
|
|
|
config: Config,
|
|
|
|
authenticators: Dict[str, Authenticator]
|
|
|
|
):
|
2021-05-18 22:43:46 +02:00
|
|
|
super().__init__(name, section, config)
|
2021-05-15 15:18:51 +02:00
|
|
|
|
|
|
|
self._shibboleth_login = KitShibbolethLogin(
|
|
|
|
section.auth(authenticators),
|
|
|
|
section.tfa_auth(authenticators)
|
|
|
|
)
|
2021-05-15 20:42:18 +02:00
|
|
|
self._base_url = "https://ilias.studium.kit.edu"
|
2021-05-15 15:18:51 +02:00
|
|
|
|
2021-05-15 20:42:18 +02:00
|
|
|
self._target = section.target()
|
2021-05-17 21:31:22 +02:00
|
|
|
self._link_file_redirect_delay = section.link_file_redirect_delay()
|
|
|
|
self._link_file_use_plaintext = section.link_file_use_plaintext()
|
2021-05-23 13:26:23 +02:00
|
|
|
self._videos = section.videos()
|
2021-05-15 15:18:51 +02:00
|
|
|
|
2021-05-22 23:18:05 +02:00
|
|
|
async def _run(self) -> None:
|
2021-05-15 20:42:18 +02:00
|
|
|
if isinstance(self._target, int):
|
2021-05-20 14:58:54 +02:00
|
|
|
log.explain_topic(f"Inferred crawl target: Course with id {self._target}")
|
2021-05-15 20:42:18 +02:00
|
|
|
await self._crawl_course(self._target)
|
|
|
|
elif self._target == "desktop":
|
2021-05-20 14:58:54 +02:00
|
|
|
log.explain_topic("Inferred crawl target: Personal desktop")
|
2021-05-15 20:42:18 +02:00
|
|
|
await self._crawl_desktop()
|
|
|
|
else:
|
2021-05-23 11:30:16 +02:00
|
|
|
log.explain_topic(f"Inferred crawl target: URL {self._target}")
|
2021-05-15 20:42:18 +02:00
|
|
|
await self._crawl_url(self._target)
|
|
|
|
|
|
|
|
async def _crawl_course(self, course_id: int) -> None:
|
|
|
|
# Start crawling at the given course
|
2021-05-19 21:34:36 +02:00
|
|
|
root_url = url_set_query_param(
|
2021-05-15 20:42:18 +02:00
|
|
|
self._base_url + "/goto.php", "target", f"crs_{course_id}"
|
|
|
|
)
|
|
|
|
|
|
|
|
await self._crawl_url(root_url, expected_id=course_id)
|
|
|
|
|
|
|
|
async def _crawl_desktop(self) -> None:
|
|
|
|
await self._crawl_url(self._base_url)
|
|
|
|
|
|
|
|
async def _crawl_url(self, url: str, expected_id: Optional[int] = None) -> None:
|
2021-05-23 12:24:10 +02:00
|
|
|
maybe_cl = await self.crawl(PurePath("."))
|
|
|
|
if not maybe_cl:
|
2021-05-22 23:18:05 +02:00
|
|
|
return
|
2021-05-23 12:24:10 +02:00
|
|
|
cl = maybe_cl # Not mypy's fault, but explained here: https://github.com/python/mypy/issues/2608
|
2021-05-22 23:18:05 +02:00
|
|
|
|
2021-05-23 17:24:05 +02:00
|
|
|
elements: List[IliasPageElement] = []
|
2021-05-15 20:42:18 +02:00
|
|
|
|
2021-05-23 17:24:05 +02:00
|
|
|
@_iorepeat(3, "crawling url")
|
|
|
|
async def gather_elements() -> None:
|
|
|
|
elements.clear()
|
2021-05-23 12:24:10 +02:00
|
|
|
async with cl:
|
|
|
|
soup = await self._get_page(url)
|
2021-05-15 20:42:18 +02:00
|
|
|
|
2021-05-23 12:24:10 +02:00
|
|
|
if expected_id is not None:
|
|
|
|
perma_link_element: Tag = soup.find(id="current_perma_link")
|
|
|
|
if not perma_link_element or "crs_" not in perma_link_element.get("value"):
|
|
|
|
raise CrawlError("Invalid course id? Didn't find anything looking like a course")
|
2021-05-15 20:42:18 +02:00
|
|
|
|
2021-05-23 17:24:05 +02:00
|
|
|
# Duplicated code, but the root page is special - we want to avoid fetching it twice!
|
2021-05-23 12:24:10 +02:00
|
|
|
page = IliasPage(soup, url, None)
|
2021-05-23 17:24:05 +02:00
|
|
|
elements.extend(page.get_child_elements())
|
2021-05-16 13:01:30 +02:00
|
|
|
|
2021-05-23 17:24:05 +02:00
|
|
|
# Fill up our task list with the found elements
|
|
|
|
await gather_elements()
|
|
|
|
tasks = [self._handle_ilias_element(PurePath("."), element) for element in elements]
|
2021-05-23 12:24:10 +02:00
|
|
|
|
2021-05-23 17:24:05 +02:00
|
|
|
# And execute them
|
|
|
|
await self.gather(tasks)
|
2021-05-15 20:42:18 +02:00
|
|
|
|
|
|
|
async def _handle_ilias_page(self, url: str, parent: IliasPageElement, path: PurePath) -> None:
|
2021-05-23 12:24:10 +02:00
|
|
|
maybe_cl = await self.crawl(path)
|
|
|
|
if not maybe_cl:
|
2021-05-19 21:57:55 +02:00
|
|
|
return
|
2021-05-23 12:24:10 +02:00
|
|
|
cl = maybe_cl # Not mypy's fault, but explained here: https://github.com/python/mypy/issues/2608
|
2021-05-19 21:57:55 +02:00
|
|
|
|
2021-05-23 17:24:05 +02:00
|
|
|
elements: List[IliasPageElement] = []
|
|
|
|
|
2021-05-23 00:28:27 +02:00
|
|
|
@_iorepeat(3, "crawling folder")
|
2021-05-23 17:24:05 +02:00
|
|
|
async def gather_elements() -> None:
|
|
|
|
elements.clear()
|
2021-05-23 00:28:27 +02:00
|
|
|
async with cl:
|
|
|
|
soup = await self._get_page(url)
|
2021-05-23 18:12:51 +02:00
|
|
|
log.explain_topic(f"Parsing HTML page for {path!r}")
|
|
|
|
log.explain(f"URL: {url!r}")
|
2021-05-23 00:28:27 +02:00
|
|
|
page = IliasPage(soup, url, parent)
|
2021-05-15 20:42:18 +02:00
|
|
|
|
2021-05-23 17:24:05 +02:00
|
|
|
elements.extend(page.get_child_elements())
|
2021-05-15 20:42:18 +02:00
|
|
|
|
2021-05-23 17:24:05 +02:00
|
|
|
# Fill up our task list with the found elements
|
|
|
|
await gather_elements()
|
|
|
|
tasks = [self._handle_ilias_element(PurePath("."), element) for element in elements]
|
2021-05-23 00:28:27 +02:00
|
|
|
|
2021-05-23 17:24:05 +02:00
|
|
|
# And execute them
|
|
|
|
await self.gather(tasks)
|
2021-05-15 20:42:18 +02:00
|
|
|
|
2021-05-16 13:01:30 +02:00
|
|
|
@anoncritical
|
2021-05-23 17:24:05 +02:00
|
|
|
# Shouldn't happen but we also really don't want to let I/O errors bubble up to anoncritical.
|
|
|
|
# If that happens we will be terminated as anoncritical doesn't tream them as non-critical.
|
2021-05-23 12:24:10 +02:00
|
|
|
@_wrap_io_in_warning("handling ilias element")
|
2021-05-15 20:42:18 +02:00
|
|
|
async def _handle_ilias_element(self, parent_path: PurePath, element: IliasPageElement) -> None:
|
|
|
|
element_path = PurePath(parent_path, element.name)
|
|
|
|
|
2021-05-23 12:36:09 +02:00
|
|
|
if element.type in _VIDEO_ELEMENTS:
|
|
|
|
log.explain_topic(f"Decision: Crawl video element {fmt_path(element_path)}")
|
2021-05-23 13:26:23 +02:00
|
|
|
if not self._videos:
|
2021-05-23 12:36:09 +02:00
|
|
|
log.explain("Video crawling is disabled")
|
|
|
|
log.explain("Answer: no")
|
|
|
|
return
|
|
|
|
else:
|
|
|
|
log.explain("Video crawling is enabled")
|
|
|
|
log.explain("Answer: yes")
|
|
|
|
|
2021-05-15 20:42:18 +02:00
|
|
|
if element.type == IliasElementType.FILE:
|
2021-05-15 21:29:43 +02:00
|
|
|
await self._download_file(element, element_path)
|
2021-05-15 20:42:18 +02:00
|
|
|
elif element.type == IliasElementType.FORUM:
|
2021-05-23 11:30:16 +02:00
|
|
|
log.explain_topic(f"Decision: Crawl {fmt_path(element_path)}")
|
2021-05-22 23:20:21 +02:00
|
|
|
log.explain("Forums are not supported")
|
2021-05-22 23:18:05 +02:00
|
|
|
log.explain("Answer: No")
|
2021-05-15 20:42:18 +02:00
|
|
|
elif element.type == IliasElementType.LINK:
|
2021-05-17 21:31:22 +02:00
|
|
|
await self._download_link(element, element_path)
|
2021-05-15 20:42:18 +02:00
|
|
|
elif element.type == IliasElementType.VIDEO:
|
2021-05-15 21:29:43 +02:00
|
|
|
await self._download_file(element, element_path)
|
2021-05-15 20:42:18 +02:00
|
|
|
elif element.type == IliasElementType.VIDEO_PLAYER:
|
2021-05-15 21:29:43 +02:00
|
|
|
await self._download_video(element, element_path)
|
2021-05-15 20:42:18 +02:00
|
|
|
elif element.type in _DIRECTORY_PAGES:
|
|
|
|
await self._handle_ilias_page(element.url, element, element_path)
|
|
|
|
else:
|
2021-05-20 14:58:54 +02:00
|
|
|
# This will retry it a few times, failing everytime. It doesn't make any network
|
|
|
|
# requests, so that's fine.
|
|
|
|
raise CrawlWarning(f"Unknown element type: {element.type!r}")
|
2021-05-15 20:42:18 +02:00
|
|
|
|
2021-05-17 21:31:22 +02:00
|
|
|
async def _download_link(self, element: IliasPageElement, element_path: PurePath) -> None:
|
2021-05-23 12:24:10 +02:00
|
|
|
maybe_dl = await self.download(element_path, mtime=element.mtime)
|
|
|
|
if not maybe_dl:
|
2021-05-17 21:31:22 +02:00
|
|
|
return
|
2021-05-23 12:24:10 +02:00
|
|
|
dl = maybe_dl # Not mypy's fault, but explained here: https://github.com/python/mypy/issues/2608
|
2021-05-17 21:31:22 +02:00
|
|
|
|
2021-05-23 12:24:10 +02:00
|
|
|
@_iorepeat(3, "resolving link")
|
2021-05-23 00:28:27 +02:00
|
|
|
async def impl() -> None:
|
|
|
|
async with dl as (bar, sink):
|
|
|
|
export_url = element.url.replace("cmd=calldirectlink", "cmd=exportHTML")
|
|
|
|
real_url = await self._resolve_link_target(export_url)
|
|
|
|
|
|
|
|
content = link_template_plain if self._link_file_use_plaintext else link_template_rich
|
|
|
|
content = content.replace("{{link}}", real_url)
|
|
|
|
content = content.replace("{{name}}", element.name)
|
|
|
|
content = content.replace("{{description}}", str(element.description))
|
|
|
|
content = content.replace("{{redirect_delay}}", str(self._link_file_redirect_delay))
|
|
|
|
sink.file.write(content.encode("utf-8"))
|
|
|
|
sink.done()
|
|
|
|
|
|
|
|
await impl()
|
|
|
|
|
|
|
|
async def _resolve_link_target(self, export_url: str) -> str:
|
|
|
|
async with self.session.get(export_url, allow_redirects=False) as resp:
|
|
|
|
# No redirect means we were authenticated
|
|
|
|
if hdrs.LOCATION not in resp.headers:
|
|
|
|
return soupify(await resp.read()).select_one("a").get("href").strip()
|
|
|
|
|
|
|
|
self._authenticate()
|
2021-05-17 21:31:22 +02:00
|
|
|
|
2021-05-23 00:28:27 +02:00
|
|
|
async with self.session.get(export_url, allow_redirects=False) as resp:
|
|
|
|
# No redirect means we were authenticated
|
|
|
|
if hdrs.LOCATION not in resp.headers:
|
|
|
|
return soupify(await resp.read()).select_one("a").get("href").strip()
|
|
|
|
|
|
|
|
raise CrawlError("resolve_link_target failed even after authenticating")
|
2021-05-17 21:31:22 +02:00
|
|
|
|
2021-05-15 21:29:43 +02:00
|
|
|
async def _download_video(self, element: IliasPageElement, element_path: PurePath) -> None:
|
|
|
|
# Videos will NOT be redownloaded - their content doesn't really change and they are chunky
|
2021-05-23 12:24:10 +02:00
|
|
|
maybe_dl = await self.download(element_path, mtime=element.mtime, redownload=Redownload.NEVER)
|
|
|
|
if not maybe_dl:
|
2021-05-15 20:42:18 +02:00
|
|
|
return
|
2021-05-23 12:24:10 +02:00
|
|
|
dl = maybe_dl # Not mypy's fault, but explained here: https://github.com/python/mypy/issues/2608
|
2021-05-15 20:42:18 +02:00
|
|
|
|
2021-05-23 12:24:10 +02:00
|
|
|
@_iorepeat(3, "downloading video")
|
2021-05-23 00:28:27 +02:00
|
|
|
async def impl() -> None:
|
|
|
|
assert dl # The function is only reached when dl is not None
|
|
|
|
async with dl as (bar, sink):
|
|
|
|
page = IliasPage(await self._get_page(element.url), element.url, element)
|
|
|
|
real_element = page.get_child_elements()[0]
|
|
|
|
|
|
|
|
await self._stream_from_url(real_element.url, sink, bar)
|
2021-05-15 21:29:43 +02:00
|
|
|
|
2021-05-23 00:28:27 +02:00
|
|
|
await impl()
|
2021-05-15 21:29:43 +02:00
|
|
|
|
|
|
|
async def _download_file(self, element: IliasPageElement, element_path: PurePath) -> None:
|
2021-05-23 12:24:10 +02:00
|
|
|
maybe_dl = await self.download(element_path, mtime=element.mtime)
|
|
|
|
if not maybe_dl:
|
2021-05-15 21:29:43 +02:00
|
|
|
return
|
2021-05-23 12:24:10 +02:00
|
|
|
dl = maybe_dl # Not mypy's fault, but explained here: https://github.com/python/mypy/issues/2608
|
2021-05-15 20:42:18 +02:00
|
|
|
|
2021-05-23 12:24:10 +02:00
|
|
|
@_iorepeat(3, "downloading file")
|
2021-05-23 00:28:27 +02:00
|
|
|
async def impl() -> None:
|
|
|
|
assert dl # The function is only reached when dl is not None
|
|
|
|
async with dl as (bar, sink):
|
|
|
|
await self._stream_from_url(element.url, sink, bar)
|
|
|
|
|
|
|
|
await impl()
|
2021-05-21 12:02:51 +02:00
|
|
|
|
|
|
|
async def _stream_from_url(self, url: str, sink: FileSink, bar: ProgressBar) -> None:
|
|
|
|
async def try_stream() -> bool:
|
|
|
|
async with self.session.get(url, allow_redirects=False) as resp:
|
|
|
|
# Redirect means we weren't authenticated
|
|
|
|
if hdrs.LOCATION in resp.headers:
|
|
|
|
return False
|
|
|
|
|
2021-05-15 21:29:43 +02:00
|
|
|
if resp.content_length:
|
|
|
|
bar.set_total(resp.content_length)
|
2021-05-15 20:42:18 +02:00
|
|
|
|
2021-05-15 21:29:43 +02:00
|
|
|
async for data in resp.content.iter_chunked(1024):
|
|
|
|
sink.file.write(data)
|
|
|
|
bar.advance(len(data))
|
2021-05-15 20:42:18 +02:00
|
|
|
|
2021-05-15 21:29:43 +02:00
|
|
|
sink.done()
|
2021-05-21 12:02:51 +02:00
|
|
|
return True
|
|
|
|
|
2021-05-23 11:55:34 +02:00
|
|
|
auth_id = await self._current_auth_id()
|
2021-05-21 12:02:51 +02:00
|
|
|
if await try_stream():
|
|
|
|
return
|
2021-05-15 15:18:51 +02:00
|
|
|
|
2021-05-21 12:02:51 +02:00
|
|
|
await self.authenticate(auth_id)
|
|
|
|
|
|
|
|
if not await try_stream():
|
|
|
|
raise CrawlError("File streaming failed after authenticate()")
|
|
|
|
|
|
|
|
async def _get_page(self, url: str) -> BeautifulSoup:
|
2021-05-23 11:55:34 +02:00
|
|
|
auth_id = await self._current_auth_id()
|
2021-05-16 13:01:30 +02:00
|
|
|
async with self.session.get(url) as request:
|
|
|
|
soup = soupify(await request.read())
|
|
|
|
if self._is_logged_in(soup):
|
|
|
|
return soup
|
|
|
|
|
2021-05-21 12:02:51 +02:00
|
|
|
# We weren't authenticated, so try to do that
|
|
|
|
await self.authenticate(auth_id)
|
2021-05-15 15:18:51 +02:00
|
|
|
|
2021-05-21 12:02:51 +02:00
|
|
|
# Retry once after authenticating. If this fails, we will die.
|
|
|
|
async with self.session.get(url) as request:
|
|
|
|
soup = soupify(await request.read())
|
|
|
|
if self._is_logged_in(soup):
|
|
|
|
return soup
|
|
|
|
raise CrawlError("get_page failed even after authenticating")
|
|
|
|
|
|
|
|
# We repeat this as the login method in shibboleth doesn't handle I/O errors.
|
|
|
|
# Shibboleth is quite reliable as well, the repeat is likely not critical here.
|
|
|
|
@_iorepeat(3, "Login")
|
|
|
|
async def _authenticate(self) -> None:
|
|
|
|
await self._shibboleth_login.login(self.session)
|
2021-05-15 15:18:51 +02:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _is_logged_in(soup: BeautifulSoup) -> bool:
|
|
|
|
# Normal ILIAS pages
|
|
|
|
userlog = soup.find("li", {"id": "userlog"})
|
|
|
|
if userlog is not None:
|
|
|
|
return True
|
|
|
|
# Video listing embeds do not have complete ILIAS html. Try to match them by
|
|
|
|
# their video listing table
|
|
|
|
video_table = soup.find(
|
|
|
|
recursive=True,
|
|
|
|
name="table",
|
|
|
|
attrs={"id": lambda x: x is not None and x.startswith("tbl_xoct")}
|
|
|
|
)
|
|
|
|
if video_table is not None:
|
|
|
|
return True
|
|
|
|
# The individual video player wrapper page has nothing of the above.
|
|
|
|
# Match it by its playerContainer.
|
|
|
|
if soup.select_one("#playerContainer") is not None:
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
|
class KitShibbolethLogin:
|
|
|
|
"""
|
|
|
|
Login via KIT's shibboleth system.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, authenticator: Authenticator, tfa_authenticator: Optional[Authenticator]) -> None:
|
|
|
|
self._auth = authenticator
|
|
|
|
self._tfa_auth = tfa_authenticator
|
|
|
|
|
|
|
|
async def login(self, sess: aiohttp.ClientSession) -> None:
|
|
|
|
"""
|
|
|
|
Performs the ILIAS Shibboleth authentication dance and saves the login
|
|
|
|
cookies it receieves.
|
|
|
|
|
|
|
|
This function should only be called whenever it is detected that you're
|
|
|
|
not logged in. The cookies obtained should be good for a few minutes,
|
|
|
|
maybe even an hour or two.
|
|
|
|
"""
|
|
|
|
|
|
|
|
# Equivalent: Click on "Mit KIT-Account anmelden" button in
|
|
|
|
# https://ilias.studium.kit.edu/login.php
|
|
|
|
url = "https://ilias.studium.kit.edu/Shibboleth.sso/Login"
|
|
|
|
data = {
|
|
|
|
"sendLogin": "1",
|
|
|
|
"idp_selection": "https://idp.scc.kit.edu/idp/shibboleth",
|
|
|
|
"target": "/shib_login.php",
|
|
|
|
"home_organization_selection": "Mit KIT-Account anmelden",
|
|
|
|
}
|
|
|
|
soup: BeautifulSoup = await _post(sess, url, data)
|
|
|
|
|
|
|
|
# Attempt to login using credentials, if necessary
|
|
|
|
while not self._login_successful(soup):
|
|
|
|
# Searching the form here so that this fails before asking for
|
|
|
|
# credentials rather than after asking.
|
|
|
|
form = soup.find("form", {"class": "full content", "method": "post"})
|
|
|
|
action = form["action"]
|
|
|
|
|
|
|
|
csrf_token = form.find("input", {"name": "csrf_token"})["value"]
|
|
|
|
|
|
|
|
# Equivalent: Enter credentials in
|
|
|
|
# https://idp.scc.kit.edu/idp/profile/SAML2/Redirect/SSO
|
|
|
|
url = "https://idp.scc.kit.edu" + action
|
|
|
|
username, password = await self._auth.credentials()
|
|
|
|
data = {
|
|
|
|
"_eventId_proceed": "",
|
|
|
|
"j_username": username,
|
|
|
|
"j_password": password,
|
|
|
|
"csrf_token": csrf_token
|
|
|
|
}
|
|
|
|
soup = await _post(sess, url, data)
|
|
|
|
|
|
|
|
if self._tfa_required(soup):
|
|
|
|
soup = await self._authenticate_tfa(sess, soup)
|
|
|
|
|
|
|
|
if not self._login_successful(soup):
|
2021-05-15 17:37:05 +02:00
|
|
|
self._auth.invalidate_credentials()
|
2021-05-15 15:18:51 +02:00
|
|
|
|
|
|
|
# Equivalent: Being redirected via JS automatically
|
|
|
|
# (or clicking "Continue" if you have JS disabled)
|
|
|
|
relay_state = soup.find("input", {"name": "RelayState"})
|
|
|
|
saml_response = soup.find("input", {"name": "SAMLResponse"})
|
|
|
|
url = "https://ilias.studium.kit.edu/Shibboleth.sso/SAML2/POST"
|
|
|
|
data = { # using the info obtained in the while loop above
|
|
|
|
"RelayState": relay_state["value"],
|
|
|
|
"SAMLResponse": saml_response["value"],
|
|
|
|
}
|
|
|
|
await sess.post(url, data=data)
|
|
|
|
|
|
|
|
async def _authenticate_tfa(
|
|
|
|
self,
|
|
|
|
session: aiohttp.ClientSession,
|
|
|
|
soup: BeautifulSoup
|
|
|
|
) -> BeautifulSoup:
|
|
|
|
if not self._tfa_auth:
|
|
|
|
raise RuntimeError("No 'tfa_auth' present but you use two-factor authentication!")
|
|
|
|
|
2021-05-15 18:24:03 +02:00
|
|
|
tfa_token = await self._tfa_auth.password()
|
2021-05-15 15:18:51 +02:00
|
|
|
|
|
|
|
# Searching the form here so that this fails before asking for
|
|
|
|
# credentials rather than after asking.
|
|
|
|
form = soup.find("form", {"method": "post"})
|
|
|
|
action = form["action"]
|
|
|
|
|
|
|
|
# Equivalent: Enter token in
|
|
|
|
# https://idp.scc.kit.edu/idp/profile/SAML2/Redirect/SSO
|
|
|
|
url = "https://idp.scc.kit.edu" + action
|
|
|
|
data = {
|
|
|
|
"_eventId_proceed": "",
|
|
|
|
"j_tokenNumber": tfa_token
|
|
|
|
}
|
|
|
|
return _post(session, url, data)
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _login_successful(soup: BeautifulSoup) -> bool:
|
|
|
|
relay_state = soup.find("input", {"name": "RelayState"})
|
|
|
|
saml_response = soup.find("input", {"name": "SAMLResponse"})
|
|
|
|
return relay_state is not None and saml_response is not None
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _tfa_required(soup: BeautifulSoup) -> bool:
|
|
|
|
return soup.find(id="j_tokenNumber") is not None
|
|
|
|
|
|
|
|
|
|
|
|
async def _post(session: aiohttp.ClientSession, url: str, data: Any) -> BeautifulSoup:
|
|
|
|
async with session.post(url, data=data) as response:
|
|
|
|
return soupify(await response.read())
|