mirror of
https://github.com/Garmelon/PFERD.git
synced 2023-12-21 10:23:01 +01:00
Compare commits
42 Commits
Author | SHA1 | Date | |
---|---|---|---|
259cfc20cc | |||
37b51a66d8 | |||
f47d2f11d8 | |||
1b6be6bd79 | |||
e1430e6298 | |||
5fdd40204b | |||
fb4631ba18 | |||
d72fc2760b | |||
4a51aaa4f5 | |||
66a5b1ba02 | |||
aa5a3a10bc | |||
d9b111cec2 | |||
345f52a1f6 | |||
ed24366aba | |||
46fb782798 | |||
846c29aee1 | |||
a5015fe9b1 | |||
616b0480f7 | |||
2f0e04ce13 | |||
bcc537468c | |||
694ffb4d77 | |||
af2cc1169a | |||
bc3fa36637 | |||
afbd03f777 | |||
b8fe25c580 | |||
a241672726 | |||
a8f76e9be7 | |||
b56475450d | |||
aa74604d29 | |||
d2e6d91880 | |||
602044ff1b | |||
31631fb409 | |||
00db348218 | |||
a709280cbf | |||
a99ddaa0cc | |||
ba3d299c05 | |||
07a21f80a6 | |||
f17b9b68f4 | |||
a2831fbea2 | |||
da72863b47 | |||
86e2e226dc | |||
7872fe5221 |
2
.github/workflows/build-and-release.yml
vendored
2
.github/workflows/build-and-release.yml
vendored
@ -14,7 +14,7 @@ jobs:
|
|||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
os: [ubuntu-latest, windows-latest, macos-latest]
|
os: [ubuntu-latest, windows-latest, macos-latest]
|
||||||
python: ["3.8"]
|
python: ["3.9"]
|
||||||
steps:
|
steps:
|
||||||
|
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v2
|
||||||
|
47
CHANGELOG.md
47
CHANGELOG.md
@ -22,6 +22,53 @@ ambiguous situations.
|
|||||||
|
|
||||||
## Unreleased
|
## Unreleased
|
||||||
|
|
||||||
|
## 3.4.2 - 2022-10-26
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Recognize and crawl content pages in cards
|
||||||
|
- Recognize and ignore surveys
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- Forum crawling crashing when a thread has no messages at all
|
||||||
|
- Forum crawling crashing when a forum has no threads at all
|
||||||
|
- Ilias login failing in some cases
|
||||||
|
- Crawling of paginated future meetings
|
||||||
|
- IPD crawler handling of URLs without trailing slash
|
||||||
|
|
||||||
|
## 3.4.1 - 2022-08-17
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Download of page descriptions
|
||||||
|
- Forum download support
|
||||||
|
- `pass` authenticator
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Add `cpp` extension to default `link_regex` of IPD crawler
|
||||||
|
- Mention hrefs in IPD crawler's `--explain` output for users of `link_regex` option
|
||||||
|
- Simplify default IPD crawler `link_regex`
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- IPD crawler crashes on some sites
|
||||||
|
- Meeting name normalization for yesterday, today and tomorrow
|
||||||
|
- Crawling of meeting file previews
|
||||||
|
- Login with new login button html layout
|
||||||
|
- Descriptions for courses are now placed in the correct subfolder when
|
||||||
|
downloading the whole desktop
|
||||||
|
|
||||||
|
## 3.4.0 - 2022-05-01
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Message when Shibboleth entitlements need to be manually reviewed
|
||||||
|
- Links to unofficial packages and repology in the readme
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Increase minimum supported Python version to 3.9
|
||||||
|
- Support video listings with more columns
|
||||||
|
- Use UTF-8 when reading/writing the config file
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- Crash during authentication when the Shibboleth session is still valid
|
||||||
|
|
||||||
## 3.3.1 - 2022-01-15
|
## 3.3.1 - 2022-01-15
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
23
CONFIG.md
23
CONFIG.md
@ -146,7 +146,7 @@ requests is likely a good idea.
|
|||||||
- `target`: URL to a KIT-IPD page
|
- `target`: URL to a KIT-IPD page
|
||||||
- `link_regex`: A regex that is matched against the `href` part of links. If it
|
- `link_regex`: A regex that is matched against the `href` part of links. If it
|
||||||
matches, the given link is downloaded as a file. This is used to extract
|
matches, the given link is downloaded as a file. This is used to extract
|
||||||
files from KIT-IPD pages. (Default: `^.*/[^/]*\.(?:pdf|zip|c|java)$`)
|
files from KIT-IPD pages. (Default: `^.*?[^/]+\.(pdf|zip|c|cpp|java)$`)
|
||||||
|
|
||||||
### The `kit-ilias-web` crawler
|
### The `kit-ilias-web` crawler
|
||||||
|
|
||||||
@ -223,6 +223,23 @@ is stored in the keyring.
|
|||||||
- `keyring_name`: The service name PFERD uses for storing credentials. (Default:
|
- `keyring_name`: The service name PFERD uses for storing credentials. (Default:
|
||||||
`PFERD`)
|
`PFERD`)
|
||||||
|
|
||||||
|
### The `pass` authenticator
|
||||||
|
|
||||||
|
This authenticator queries the [`pass` password manager][3] for a username and
|
||||||
|
password. It tries to be mostly compatible with [browserpass][4] and
|
||||||
|
[passff][5], so see those links for an overview of the format. If PFERD fails
|
||||||
|
to load your password, you can use the `--explain` flag to see why.
|
||||||
|
|
||||||
|
- `passname`: The name of the password to use (Required)
|
||||||
|
- `username_prefixes`: A comma-separated list of username line prefixes
|
||||||
|
(Default: `login,username,user`)
|
||||||
|
- `password_prefixes`: A comma-separated list of password line prefixes
|
||||||
|
(Default: `password,pass,secret`)
|
||||||
|
|
||||||
|
[3]: <https://www.passwordstore.org/> "Pass: The Standard Unix Password Manager"
|
||||||
|
[4]: <https://github.com/browserpass/browserpass-extension#organizing-password-store> "Organizing password store"
|
||||||
|
[5]: <https://github.com/passff/passff#multi-line-format> "Multi-line format"
|
||||||
|
|
||||||
### The `tfa` authenticator
|
### The `tfa` authenticator
|
||||||
|
|
||||||
This authenticator prompts the user on the console for a two-factor
|
This authenticator prompts the user on the console for a two-factor
|
||||||
@ -316,7 +333,7 @@ is a regular expression and `TARGET` an f-string based template. If a path
|
|||||||
matches `SOURCE`, the output path is created using `TARGET` as template.
|
matches `SOURCE`, the output path is created using `TARGET` as template.
|
||||||
`SOURCE` is automatically anchored.
|
`SOURCE` is automatically anchored.
|
||||||
|
|
||||||
`TARGET` uses Python's [format string syntax][3]. The *n*-th capturing group can
|
`TARGET` uses Python's [format string syntax][6]. The *n*-th capturing group can
|
||||||
be referred to as `{g<n>}` (e.g. `{g3}`). `{g0}` refers to the original path.
|
be referred to as `{g<n>}` (e.g. `{g3}`). `{g0}` refers to the original path.
|
||||||
If capturing group *n*'s contents are a valid integer, the integer value is
|
If capturing group *n*'s contents are a valid integer, the integer value is
|
||||||
available as `{i<n>}` (e.g. `{i3}`). If capturing group *n*'s contents are a
|
available as `{i<n>}` (e.g. `{i3}`). If capturing group *n*'s contents are a
|
||||||
@ -337,7 +354,7 @@ Example: `f(oo+)/be?ar -re-> B{g1.upper()}H/fear`
|
|||||||
- Converts `fooooo/bear` into `BOOOOOH/fear`
|
- Converts `fooooo/bear` into `BOOOOOH/fear`
|
||||||
- Converts `foo/bar/baz` into `BOOH/fear/baz`
|
- Converts `foo/bar/baz` into `BOOH/fear/baz`
|
||||||
|
|
||||||
[3]: <https://docs.python.org/3/library/string.html#format-string-syntax> "Format String Syntax"
|
[6]: <https://docs.python.org/3/library/string.html#format-string-syntax> "Format String Syntax"
|
||||||
|
|
||||||
### The `-name-re->` arrow
|
### The `-name-re->` arrow
|
||||||
|
|
||||||
|
@ -159,3 +159,7 @@ def main() -> None:
|
|||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
else:
|
else:
|
||||||
pferd.print_report()
|
pferd.print_report()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
|
@ -5,6 +5,7 @@ from ..config import Config
|
|||||||
from .authenticator import Authenticator, AuthError, AuthLoadError, AuthSection # noqa: F401
|
from .authenticator import Authenticator, AuthError, AuthLoadError, AuthSection # noqa: F401
|
||||||
from .credential_file import CredentialFileAuthenticator, CredentialFileAuthSection
|
from .credential_file import CredentialFileAuthenticator, CredentialFileAuthSection
|
||||||
from .keyring import KeyringAuthenticator, KeyringAuthSection
|
from .keyring import KeyringAuthenticator, KeyringAuthSection
|
||||||
|
from .pass_ import PassAuthenticator, PassAuthSection
|
||||||
from .simple import SimpleAuthenticator, SimpleAuthSection
|
from .simple import SimpleAuthenticator, SimpleAuthSection
|
||||||
from .tfa import TfaAuthenticator
|
from .tfa import TfaAuthenticator
|
||||||
|
|
||||||
@ -19,6 +20,8 @@ AUTHENTICATORS: Dict[str, AuthConstructor] = {
|
|||||||
CredentialFileAuthenticator(n, CredentialFileAuthSection(s), c),
|
CredentialFileAuthenticator(n, CredentialFileAuthSection(s), c),
|
||||||
"keyring": lambda n, s, c:
|
"keyring": lambda n, s, c:
|
||||||
KeyringAuthenticator(n, KeyringAuthSection(s)),
|
KeyringAuthenticator(n, KeyringAuthSection(s)),
|
||||||
|
"pass": lambda n, s, c:
|
||||||
|
PassAuthenticator(n, PassAuthSection(s)),
|
||||||
"simple": lambda n, s, c:
|
"simple": lambda n, s, c:
|
||||||
SimpleAuthenticator(n, SimpleAuthSection(s)),
|
SimpleAuthenticator(n, SimpleAuthSection(s)),
|
||||||
"tfa": lambda n, s, c:
|
"tfa": lambda n, s, c:
|
||||||
|
@ -20,8 +20,10 @@ class CredentialFileAuthenticator(Authenticator):
|
|||||||
|
|
||||||
path = config.default_section.working_dir() / section.path()
|
path = config.default_section.working_dir() / section.path()
|
||||||
try:
|
try:
|
||||||
with open(path) as f:
|
with open(path, encoding="utf-8") as f:
|
||||||
lines = list(f)
|
lines = list(f)
|
||||||
|
except UnicodeDecodeError:
|
||||||
|
raise AuthLoadError(f"Credential file at {fmt_real_path(path)} is not encoded using UTF-8")
|
||||||
except OSError as e:
|
except OSError as e:
|
||||||
raise AuthLoadError(f"No credential file at {fmt_real_path(path)}") from e
|
raise AuthLoadError(f"No credential file at {fmt_real_path(path)}") from e
|
||||||
|
|
||||||
|
98
PFERD/auth/pass_.py
Normal file
98
PFERD/auth/pass_.py
Normal file
@ -0,0 +1,98 @@
|
|||||||
|
import re
|
||||||
|
import subprocess
|
||||||
|
from typing import List, Tuple
|
||||||
|
|
||||||
|
from ..logging import log
|
||||||
|
from .authenticator import Authenticator, AuthError, AuthSection
|
||||||
|
|
||||||
|
|
||||||
|
class PassAuthSection(AuthSection):
|
||||||
|
def passname(self) -> str:
|
||||||
|
if (value := self.s.get("passname")) is None:
|
||||||
|
self.missing_value("passname")
|
||||||
|
return value
|
||||||
|
|
||||||
|
def username_prefixes(self) -> List[str]:
|
||||||
|
value = self.s.get("username_prefixes", "login,username,user")
|
||||||
|
return [prefix.lower() for prefix in value.split(",")]
|
||||||
|
|
||||||
|
def password_prefixes(self) -> List[str]:
|
||||||
|
value = self.s.get("password_prefixes", "password,pass,secret")
|
||||||
|
return [prefix.lower() for prefix in value.split(",")]
|
||||||
|
|
||||||
|
|
||||||
|
class PassAuthenticator(Authenticator):
|
||||||
|
PREFIXED_LINE_RE = r"([a-zA-Z]+):\s?(.*)" # to be used with fullmatch
|
||||||
|
|
||||||
|
def __init__(self, name: str, section: PassAuthSection) -> None:
|
||||||
|
super().__init__(name)
|
||||||
|
|
||||||
|
self._passname = section.passname()
|
||||||
|
self._username_prefixes = section.username_prefixes()
|
||||||
|
self._password_prefixes = section.password_prefixes()
|
||||||
|
|
||||||
|
async def credentials(self) -> Tuple[str, str]:
|
||||||
|
log.explain_topic("Obtaining credentials from pass")
|
||||||
|
|
||||||
|
try:
|
||||||
|
log.explain(f"Calling 'pass show {self._passname}'")
|
||||||
|
result = subprocess.check_output(["pass", "show", self._passname], text=True)
|
||||||
|
except subprocess.CalledProcessError as e:
|
||||||
|
raise AuthError(f"Failed to get password info from {self._passname}: {e}")
|
||||||
|
|
||||||
|
prefixed = {}
|
||||||
|
unprefixed = []
|
||||||
|
for line in result.strip().splitlines():
|
||||||
|
if match := re.fullmatch(self.PREFIXED_LINE_RE, line):
|
||||||
|
prefix = match.group(1).lower()
|
||||||
|
value = match.group(2)
|
||||||
|
log.explain(f"Found prefixed line {line!r} with prefix {prefix!r}, value {value!r}")
|
||||||
|
if prefix in prefixed:
|
||||||
|
raise AuthError(f"Prefix {prefix} specified multiple times")
|
||||||
|
prefixed[prefix] = value
|
||||||
|
else:
|
||||||
|
log.explain(f"Found unprefixed line {line!r}")
|
||||||
|
unprefixed.append(line)
|
||||||
|
|
||||||
|
username = None
|
||||||
|
for prefix in self._username_prefixes:
|
||||||
|
log.explain(f"Looking for username at prefix {prefix!r}")
|
||||||
|
if prefix in prefixed:
|
||||||
|
username = prefixed[prefix]
|
||||||
|
log.explain(f"Found username {username!r}")
|
||||||
|
break
|
||||||
|
|
||||||
|
password = None
|
||||||
|
for prefix in self._password_prefixes:
|
||||||
|
log.explain(f"Looking for password at prefix {prefix!r}")
|
||||||
|
if prefix in prefixed:
|
||||||
|
password = prefixed[prefix]
|
||||||
|
log.explain(f"Found password {password!r}")
|
||||||
|
break
|
||||||
|
|
||||||
|
if password is None and username is None:
|
||||||
|
log.explain("No username and password found so far")
|
||||||
|
log.explain("Using first unprefixed line as password")
|
||||||
|
log.explain("Using second unprefixed line as username")
|
||||||
|
elif password is None:
|
||||||
|
log.explain("No password found so far")
|
||||||
|
log.explain("Using first unprefixed line as password")
|
||||||
|
elif username is None:
|
||||||
|
log.explain("No username found so far")
|
||||||
|
log.explain("Using first unprefixed line as username")
|
||||||
|
|
||||||
|
if password is None:
|
||||||
|
if not unprefixed:
|
||||||
|
log.explain("Not enough unprefixed lines left")
|
||||||
|
raise AuthError("Password could not be determined")
|
||||||
|
password = unprefixed.pop(0)
|
||||||
|
log.explain(f"Found password {password!r}")
|
||||||
|
|
||||||
|
if username is None:
|
||||||
|
if not unprefixed:
|
||||||
|
log.explain("Not enough unprefixed lines left")
|
||||||
|
raise AuthError("Username could not be determined")
|
||||||
|
username = unprefixed.pop(0)
|
||||||
|
log.explain(f"Found username {username!r}")
|
||||||
|
|
||||||
|
return username, password
|
@ -62,6 +62,11 @@ GROUP.add_argument(
|
|||||||
action=BooleanOptionalAction,
|
action=BooleanOptionalAction,
|
||||||
help="crawl and download videos"
|
help="crawl and download videos"
|
||||||
)
|
)
|
||||||
|
GROUP.add_argument(
|
||||||
|
"--forums",
|
||||||
|
action=BooleanOptionalAction,
|
||||||
|
help="crawl and download forum posts"
|
||||||
|
)
|
||||||
GROUP.add_argument(
|
GROUP.add_argument(
|
||||||
"--http-timeout", "-t",
|
"--http-timeout", "-t",
|
||||||
type=float,
|
type=float,
|
||||||
@ -90,6 +95,8 @@ def load(
|
|||||||
section["link_redirect_delay"] = str(args.link_redirect_delay)
|
section["link_redirect_delay"] = str(args.link_redirect_delay)
|
||||||
if args.videos is not None:
|
if args.videos is not None:
|
||||||
section["videos"] = "yes" if args.videos else "no"
|
section["videos"] = "yes" if args.videos else "no"
|
||||||
|
if args.forums is not None:
|
||||||
|
section["forums"] = "yes" if args.forums else "no"
|
||||||
if args.http_timeout is not None:
|
if args.http_timeout is not None:
|
||||||
section["http_timeout"] = str(args.http_timeout)
|
section["http_timeout"] = str(args.http_timeout)
|
||||||
|
|
||||||
|
@ -120,7 +120,7 @@ class Config:
|
|||||||
# Using config.read_file instead of config.read because config.read
|
# Using config.read_file instead of config.read because config.read
|
||||||
# would just ignore a missing file and carry on.
|
# would just ignore a missing file and carry on.
|
||||||
try:
|
try:
|
||||||
with open(path) as f:
|
with open(path, encoding="utf-8") as f:
|
||||||
parser.read_file(f, source=str(path))
|
parser.read_file(f, source=str(path))
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
raise ConfigLoadError(path, "File does not exist")
|
raise ConfigLoadError(path, "File does not exist")
|
||||||
@ -128,6 +128,8 @@ class Config:
|
|||||||
raise ConfigLoadError(path, "That's a directory, not a file")
|
raise ConfigLoadError(path, "That's a directory, not a file")
|
||||||
except PermissionError:
|
except PermissionError:
|
||||||
raise ConfigLoadError(path, "Insufficient permissions")
|
raise ConfigLoadError(path, "Insufficient permissions")
|
||||||
|
except UnicodeDecodeError:
|
||||||
|
raise ConfigLoadError(path, "File is not encoded using UTF-8")
|
||||||
|
|
||||||
def dump(self, path: Optional[Path] = None) -> None:
|
def dump(self, path: Optional[Path] = None) -> None:
|
||||||
"""
|
"""
|
||||||
@ -154,12 +156,12 @@ class Config:
|
|||||||
try:
|
try:
|
||||||
# x = open for exclusive creation, failing if the file already
|
# x = open for exclusive creation, failing if the file already
|
||||||
# exists
|
# exists
|
||||||
with open(path, "x") as f:
|
with open(path, "x", encoding="utf-8") as f:
|
||||||
self._parser.write(f)
|
self._parser.write(f)
|
||||||
except FileExistsError:
|
except FileExistsError:
|
||||||
print("That file already exists.")
|
print("That file already exists.")
|
||||||
if asyncio.run(prompt_yes_no("Overwrite it?", default=False)):
|
if asyncio.run(prompt_yes_no("Overwrite it?", default=False)):
|
||||||
with open(path, "w") as f:
|
with open(path, "w", encoding="utf-8") as f:
|
||||||
self._parser.write(f)
|
self._parser.write(f)
|
||||||
else:
|
else:
|
||||||
raise ConfigDumpError(path, "File already exists")
|
raise ConfigDumpError(path, "File already exists")
|
||||||
|
@ -1,9 +1,10 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
import os
|
import os
|
||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
|
from collections.abc import Awaitable, Coroutine
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from pathlib import Path, PurePath
|
from pathlib import Path, PurePath
|
||||||
from typing import Any, Awaitable, Callable, Dict, List, Optional, Sequence, Set, Tuple, TypeVar
|
from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Tuple, TypeVar
|
||||||
|
|
||||||
from ..auth import Authenticator
|
from ..auth import Authenticator
|
||||||
from ..config import Config, Section
|
from ..config import Config, Section
|
||||||
@ -58,7 +59,7 @@ def noncritical(f: Wrapped) -> Wrapped:
|
|||||||
return wrapper # type: ignore
|
return wrapper # type: ignore
|
||||||
|
|
||||||
|
|
||||||
AWrapped = TypeVar("AWrapped", bound=Callable[..., Awaitable[Optional[Any]]])
|
AWrapped = TypeVar("AWrapped", bound=Callable[..., Coroutine[Any, Any, Optional[Any]]])
|
||||||
|
|
||||||
|
|
||||||
def anoncritical(f: AWrapped) -> AWrapped:
|
def anoncritical(f: AWrapped) -> AWrapped:
|
||||||
|
@ -108,7 +108,7 @@ class HttpCrawler(Crawler):
|
|||||||
|
|
||||||
def _load_cookies_from_file(self, path: Path) -> None:
|
def _load_cookies_from_file(self, path: Path) -> None:
|
||||||
jar: Any = http.cookies.SimpleCookie()
|
jar: Any = http.cookies.SimpleCookie()
|
||||||
with open(path) as f:
|
with open(path, encoding="utf-8") as f:
|
||||||
for i, line in enumerate(f):
|
for i, line in enumerate(f):
|
||||||
# Names of headers are case insensitive
|
# Names of headers are case insensitive
|
||||||
if line[:11].lower() == "set-cookie:":
|
if line[:11].lower() == "set-cookie:":
|
||||||
@ -121,7 +121,7 @@ class HttpCrawler(Crawler):
|
|||||||
jar: Any = http.cookies.SimpleCookie()
|
jar: Any = http.cookies.SimpleCookie()
|
||||||
for morsel in self._cookie_jar:
|
for morsel in self._cookie_jar:
|
||||||
jar[morsel.key] = morsel
|
jar[morsel.key] = morsel
|
||||||
with open(path, "w") as f:
|
with open(path, "w", encoding="utf-8") as f:
|
||||||
f.write(jar.output(sep="\n"))
|
f.write(jar.output(sep="\n"))
|
||||||
f.write("\n") # A trailing newline is just common courtesy
|
f.write("\n") # A trailing newline is just common courtesy
|
||||||
|
|
||||||
|
91
PFERD/crawl/ilias/ilias_html_cleaner.py
Normal file
91
PFERD/crawl/ilias/ilias_html_cleaner.py
Normal file
@ -0,0 +1,91 @@
|
|||||||
|
from bs4 import BeautifulSoup, Comment, Tag
|
||||||
|
|
||||||
|
_STYLE_TAG_CONTENT = """
|
||||||
|
.ilc_text_block_Information {
|
||||||
|
background-color: #f5f7fa;
|
||||||
|
}
|
||||||
|
div.ilc_text_block_Standard {
|
||||||
|
margin-bottom: 10px;
|
||||||
|
margin-top: 10px;
|
||||||
|
}
|
||||||
|
span.ilc_text_inline_Strong {
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
.accordion-head {
|
||||||
|
background-color: #f5f7fa;
|
||||||
|
padding: 0.5rem 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
h3 {
|
||||||
|
margin-top: 0.5rem;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
br.visible-break {
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
article {
|
||||||
|
margin: 0.5rem 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
padding: 1em;
|
||||||
|
grid-template-columns: 1fr min(60rem, 90%) 1fr;
|
||||||
|
line-height: 1.2;
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
|
||||||
|
_ARTICLE_WORTHY_CLASSES = [
|
||||||
|
"ilc_text_block_Information",
|
||||||
|
"ilc_section_Attention",
|
||||||
|
"ilc_section_Link",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def insert_base_markup(soup: BeautifulSoup) -> BeautifulSoup:
|
||||||
|
head = soup.new_tag("head")
|
||||||
|
soup.insert(0, head)
|
||||||
|
|
||||||
|
simplecss_link: Tag = soup.new_tag("link")
|
||||||
|
# <link rel="stylesheet" href="https://cdn.simplecss.org/simple.css">
|
||||||
|
simplecss_link["rel"] = "stylesheet"
|
||||||
|
simplecss_link["href"] = "https://cdn.simplecss.org/simple.css"
|
||||||
|
head.append(simplecss_link)
|
||||||
|
|
||||||
|
# Basic style tags for compat
|
||||||
|
style: Tag = soup.new_tag("style")
|
||||||
|
style.append(_STYLE_TAG_CONTENT)
|
||||||
|
head.append(style)
|
||||||
|
|
||||||
|
return soup
|
||||||
|
|
||||||
|
|
||||||
|
def clean(soup: BeautifulSoup) -> BeautifulSoup:
|
||||||
|
for block in soup.find_all(class_=lambda x: x in _ARTICLE_WORTHY_CLASSES):
|
||||||
|
block.name = "article"
|
||||||
|
|
||||||
|
for block in soup.find_all("h3"):
|
||||||
|
block.name = "div"
|
||||||
|
|
||||||
|
for block in soup.find_all("h1"):
|
||||||
|
block.name = "h3"
|
||||||
|
|
||||||
|
for block in soup.find_all(class_="ilc_va_ihcap_VAccordIHeadCap"):
|
||||||
|
block.name = "h3"
|
||||||
|
block["class"] += ["accordion-head"]
|
||||||
|
|
||||||
|
for dummy in soup.select(".ilc_text_block_Standard.ilc_Paragraph"):
|
||||||
|
children = list(dummy.children)
|
||||||
|
if not children:
|
||||||
|
dummy.decompose()
|
||||||
|
if len(children) > 1:
|
||||||
|
continue
|
||||||
|
if type(children[0]) == Comment:
|
||||||
|
dummy.decompose()
|
||||||
|
|
||||||
|
for hrule_imposter in soup.find_all(class_="ilc_section_Separator"):
|
||||||
|
hrule_imposter.insert(0, soup.new_tag("hr"))
|
||||||
|
|
||||||
|
return soup
|
@ -3,7 +3,7 @@ import re
|
|||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from datetime import date, datetime, timedelta
|
from datetime import date, datetime, timedelta
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
from typing import List, Optional, Union
|
from typing import Dict, List, Optional, Union
|
||||||
from urllib.parse import urljoin, urlparse
|
from urllib.parse import urljoin, urlparse
|
||||||
|
|
||||||
from bs4 import BeautifulSoup, Tag
|
from bs4 import BeautifulSoup, Tag
|
||||||
@ -24,6 +24,7 @@ class IliasElementType(Enum):
|
|||||||
LINK = "link"
|
LINK = "link"
|
||||||
BOOKING = "booking"
|
BOOKING = "booking"
|
||||||
MEETING = "meeting"
|
MEETING = "meeting"
|
||||||
|
SURVEY = "survey"
|
||||||
VIDEO = "video"
|
VIDEO = "video"
|
||||||
VIDEO_PLAYER = "video_player"
|
VIDEO_PLAYER = "video_player"
|
||||||
VIDEO_FOLDER = "video_folder"
|
VIDEO_FOLDER = "video_folder"
|
||||||
@ -55,6 +56,21 @@ class IliasPageElement:
|
|||||||
return self.url
|
return self.url
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class IliasDownloadForumData:
|
||||||
|
url: str
|
||||||
|
form_data: Dict[str, Union[str, List[str]]]
|
||||||
|
empty: bool
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class IliasForumThread:
|
||||||
|
title: str
|
||||||
|
title_tag: Tag
|
||||||
|
content_tag: Tag
|
||||||
|
mtime: Optional[datetime]
|
||||||
|
|
||||||
|
|
||||||
class IliasPage:
|
class IliasPage:
|
||||||
|
|
||||||
def __init__(self, soup: BeautifulSoup, _page_url: str, source_element: Optional[IliasPageElement]):
|
def __init__(self, soup: BeautifulSoup, _page_url: str, source_element: Optional[IliasPageElement]):
|
||||||
@ -85,13 +101,72 @@ class IliasPage:
|
|||||||
log.explain("Page is a normal folder, searching for elements")
|
log.explain("Page is a normal folder, searching for elements")
|
||||||
return self._find_normal_entries()
|
return self._find_normal_entries()
|
||||||
|
|
||||||
|
def get_description(self) -> Optional[BeautifulSoup]:
|
||||||
|
def is_interesting_class(name: str) -> bool:
|
||||||
|
return name in ["ilCOPageSection", "ilc_Paragraph", "ilc_va_ihcap_VAccordIHeadCap"]
|
||||||
|
|
||||||
|
paragraphs: List[Tag] = self._soup.findAll(class_=is_interesting_class)
|
||||||
|
if not paragraphs:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Extract bits and pieces into a string and parse it again.
|
||||||
|
# This ensures we don't miss anything and weird structures are resolved
|
||||||
|
# somewhat gracefully.
|
||||||
|
raw_html = ""
|
||||||
|
for p in paragraphs:
|
||||||
|
if p.find_parent(class_=is_interesting_class):
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Ignore special listings (like folder groupings)
|
||||||
|
if "ilc_section_Special" in p["class"]:
|
||||||
|
continue
|
||||||
|
|
||||||
|
raw_html += str(p) + "\n"
|
||||||
|
raw_html = f"<body>\n{raw_html}\n</body>"
|
||||||
|
|
||||||
|
return BeautifulSoup(raw_html, "html.parser")
|
||||||
|
|
||||||
|
def get_download_forum_data(self) -> Optional[IliasDownloadForumData]:
|
||||||
|
form = self._soup.find("form", attrs={"action": lambda x: x and "fallbackCmd=showThreads" in x})
|
||||||
|
if not form:
|
||||||
|
return None
|
||||||
|
post_url = self._abs_url_from_relative(form["action"])
|
||||||
|
|
||||||
|
thread_ids = [f["value"] for f in form.find_all(attrs={"name": "thread_ids[]"})]
|
||||||
|
|
||||||
|
form_data: Dict[str, Union[str, List[ſtr]]] = {
|
||||||
|
"thread_ids[]": thread_ids,
|
||||||
|
"selected_cmd2": "html",
|
||||||
|
"select_cmd2": "Ausführen",
|
||||||
|
"selected_cmd": "",
|
||||||
|
}
|
||||||
|
|
||||||
|
return IliasDownloadForumData(url=post_url, form_data=form_data, empty=len(thread_ids) == 0)
|
||||||
|
|
||||||
def get_next_stage_element(self) -> Optional[IliasPageElement]:
|
def get_next_stage_element(self) -> Optional[IliasPageElement]:
|
||||||
|
if self._is_forum_page():
|
||||||
|
if "trows=800" in self._page_url:
|
||||||
|
return None
|
||||||
|
log.explain("Requesting *all* forum threads")
|
||||||
|
return self._get_show_max_forum_entries_per_page_url()
|
||||||
if self._is_ilias_opencast_embedding():
|
if self._is_ilias_opencast_embedding():
|
||||||
|
log.explain("Unwrapping opencast embedding")
|
||||||
return self.get_child_elements()[0]
|
return self.get_child_elements()[0]
|
||||||
if self._page_type == IliasElementType.VIDEO_FOLDER_MAYBE_PAGINATED:
|
if self._page_type == IliasElementType.VIDEO_FOLDER_MAYBE_PAGINATED:
|
||||||
|
log.explain("Unwrapping video pagination")
|
||||||
return self._find_video_entries_paginated()[0]
|
return self._find_video_entries_paginated()[0]
|
||||||
|
if self._contains_collapsed_future_meetings():
|
||||||
|
log.explain("Requesting *all* future meetings")
|
||||||
|
return self._uncollapse_future_meetings_url()
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
def _is_forum_page(self) -> bool:
|
||||||
|
read_more_btn = self._soup.find(
|
||||||
|
"button",
|
||||||
|
attrs={"onclick": lambda x: x and "cmdClass=ilobjforumgui&cmd=markAllRead" in x}
|
||||||
|
)
|
||||||
|
return read_more_btn is not None
|
||||||
|
|
||||||
def _is_video_player(self) -> bool:
|
def _is_video_player(self) -> bool:
|
||||||
return "paella_config_file" in str(self._soup)
|
return "paella_config_file" in str(self._soup)
|
||||||
|
|
||||||
@ -135,6 +210,16 @@ class IliasPage:
|
|||||||
return False
|
return False
|
||||||
return "target=copa_" in link.get("value")
|
return "target=copa_" in link.get("value")
|
||||||
|
|
||||||
|
def _contains_collapsed_future_meetings(self) -> bool:
|
||||||
|
return self._uncollapse_future_meetings_url() is not None
|
||||||
|
|
||||||
|
def _uncollapse_future_meetings_url(self) -> Optional[IliasPageElement]:
|
||||||
|
element = self._soup.find("a", attrs={"href": lambda x: x and "crs_next_sess=1" in x})
|
||||||
|
if not element:
|
||||||
|
return None
|
||||||
|
link = self._abs_url_from_link(element)
|
||||||
|
return IliasPageElement(IliasElementType.FOLDER, link, "show all meetings")
|
||||||
|
|
||||||
def _player_to_video(self) -> List[IliasPageElement]:
|
def _player_to_video(self) -> List[IliasPageElement]:
|
||||||
# Fetch the actual video page. This is a small wrapper page initializing a javscript
|
# Fetch the actual video page. This is a small wrapper page initializing a javscript
|
||||||
# player. Sadly we can not execute that JS. The actual video stream url is nowhere
|
# player. Sadly we can not execute that JS. The actual video stream url is nowhere
|
||||||
@ -169,6 +254,19 @@ class IliasPage:
|
|||||||
|
|
||||||
return items
|
return items
|
||||||
|
|
||||||
|
def _get_show_max_forum_entries_per_page_url(self) -> Optional[IliasPageElement]:
|
||||||
|
correct_link = self._soup.find(
|
||||||
|
"a",
|
||||||
|
attrs={"href": lambda x: x and "trows=800" in x and "cmd=showThreads" in x}
|
||||||
|
)
|
||||||
|
|
||||||
|
if not correct_link:
|
||||||
|
return None
|
||||||
|
|
||||||
|
link = self._abs_url_from_link(correct_link)
|
||||||
|
|
||||||
|
return IliasPageElement(IliasElementType.FORUM, link, "show all forum threads")
|
||||||
|
|
||||||
def _find_personal_desktop_entries(self) -> List[IliasPageElement]:
|
def _find_personal_desktop_entries(self) -> List[IliasPageElement]:
|
||||||
items: List[IliasPageElement] = []
|
items: List[IliasPageElement] = []
|
||||||
|
|
||||||
@ -280,11 +378,22 @@ class IliasPage:
|
|||||||
|
|
||||||
def _listed_video_to_element(self, link: Tag) -> IliasPageElement:
|
def _listed_video_to_element(self, link: Tag) -> IliasPageElement:
|
||||||
# The link is part of a table with multiple columns, describing metadata.
|
# The link is part of a table with multiple columns, describing metadata.
|
||||||
# 6th child (1 indexed) is the modification time string
|
# 6th or 7th child (1 indexed) is the modification time string. Try to find it
|
||||||
|
# by parsing backwards from the end and finding something that looks like a date
|
||||||
|
modification_time = None
|
||||||
|
row: Tag = link.parent.parent.parent
|
||||||
|
column_count = len(row.select("td.std"))
|
||||||
|
for index in range(column_count, 0, -1):
|
||||||
modification_string = link.parent.parent.parent.select_one(
|
modification_string = link.parent.parent.parent.select_one(
|
||||||
"td.std:nth-child(6)"
|
f"td.std:nth-child({index})"
|
||||||
).getText().strip()
|
).getText().strip()
|
||||||
|
if re.search(r"\d+\.\d+.\d+ - \d+:\d+", modification_string):
|
||||||
modification_time = datetime.strptime(modification_string, "%d.%m.%Y - %H:%M")
|
modification_time = datetime.strptime(modification_string, "%d.%m.%Y - %H:%M")
|
||||||
|
break
|
||||||
|
|
||||||
|
if modification_time is None:
|
||||||
|
log.warn(f"Could not determine upload time for {link}")
|
||||||
|
modification_time = datetime.now()
|
||||||
|
|
||||||
title = link.parent.parent.parent.select_one("td.std:nth-child(3)").getText().strip()
|
title = link.parent.parent.parent.select_one("td.std:nth-child(3)").getText().strip()
|
||||||
title += ".mp4"
|
title += ".mp4"
|
||||||
@ -417,6 +526,12 @@ class IliasPage:
|
|||||||
element_type = self._find_type_from_link(element_name, link, abs_url)
|
element_type = self._find_type_from_link(element_name, link, abs_url)
|
||||||
description = self._find_link_description(link)
|
description = self._find_link_description(link)
|
||||||
|
|
||||||
|
# The last meeting on every page is expanded by default.
|
||||||
|
# Its content is then shown inline *and* in the meeting page itself.
|
||||||
|
# We should skip the inline content.
|
||||||
|
if element_type != IliasElementType.MEETING and self._is_in_expanded_meeting(link):
|
||||||
|
continue
|
||||||
|
|
||||||
if not element_type:
|
if not element_type:
|
||||||
continue
|
continue
|
||||||
if element_type == IliasElementType.MEETING:
|
if element_type == IliasElementType.MEETING:
|
||||||
@ -434,6 +549,26 @@ class IliasPage:
|
|||||||
|
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
def _is_in_expanded_meeting(self, tag: Tag) -> bool:
|
||||||
|
"""
|
||||||
|
Returns whether a file is part of an expanded meeting.
|
||||||
|
Has false positives for meetings themselves as their title is also "in the expanded meeting content".
|
||||||
|
It is in the same general div and this whole thing is guesswork.
|
||||||
|
Therefore, you should check for meetings before passing them in this function.
|
||||||
|
"""
|
||||||
|
parents: List[Tag] = list(tag.parents)
|
||||||
|
for parent in parents:
|
||||||
|
if not parent.get("class"):
|
||||||
|
continue
|
||||||
|
|
||||||
|
# We should not crawl files under meetings
|
||||||
|
if "ilContainerListItemContentCB" in parent.get("class"):
|
||||||
|
link: Tag = parent.parent.find("a")
|
||||||
|
type = IliasPage._find_type_from_folder_like(link, self._page_url)
|
||||||
|
return type == IliasElementType.MEETING
|
||||||
|
|
||||||
|
return False
|
||||||
|
|
||||||
def _find_upwards_folder_hierarchy(self, tag: Tag) -> List[str]:
|
def _find_upwards_folder_hierarchy(self, tag: Tag) -> List[str]:
|
||||||
"""
|
"""
|
||||||
Interprets accordions and expandable blocks as virtual folders and returns them
|
Interprets accordions and expandable blocks as virtual folders and returns them
|
||||||
@ -596,6 +731,10 @@ class IliasPage:
|
|||||||
return IliasElementType.TEST
|
return IliasElementType.TEST
|
||||||
if "fold" in icon["class"]:
|
if "fold" in icon["class"]:
|
||||||
return IliasElementType.FOLDER
|
return IliasElementType.FOLDER
|
||||||
|
if "copa" in icon["class"]:
|
||||||
|
return IliasElementType.FOLDER
|
||||||
|
if "svy" in icon["class"]:
|
||||||
|
return IliasElementType.SURVEY
|
||||||
|
|
||||||
_unexpected_html_warning()
|
_unexpected_html_warning()
|
||||||
log.warn_contd(f"Could not extract type from {icon} for card title {card_title}")
|
log.warn_contd(f"Could not extract type from {icon} for card title {card_title}")
|
||||||
@ -675,6 +814,10 @@ class IliasPage:
|
|||||||
if img_tag is None:
|
if img_tag is None:
|
||||||
img_tag = found_parent.select_one("img.icon")
|
img_tag = found_parent.select_one("img.icon")
|
||||||
|
|
||||||
|
if img_tag is None and found_parent.find("a", attrs={"href": lambda x: x and "crs_next_sess=" in x}):
|
||||||
|
log.explain("Found session expansion button, skipping it as it has no content")
|
||||||
|
return None
|
||||||
|
|
||||||
if img_tag is None:
|
if img_tag is None:
|
||||||
_unexpected_html_warning()
|
_unexpected_html_warning()
|
||||||
log.warn_contd(f"Tried to figure out element type, but did not find an image for {url}")
|
log.warn_contd(f"Tried to figure out element type, but did not find an image for {url}")
|
||||||
@ -709,17 +852,26 @@ class IliasPage:
|
|||||||
Normalizes meeting names, which have a relative time as their first part,
|
Normalizes meeting names, which have a relative time as their first part,
|
||||||
to their date in ISO format.
|
to their date in ISO format.
|
||||||
"""
|
"""
|
||||||
date_portion_str = meeting_name.split(" - ")[0]
|
|
||||||
|
# This checks whether we can reach a `:` without passing a `-`
|
||||||
|
if re.search(r"^[^-]+: ", meeting_name):
|
||||||
|
# Meeting name only contains date: "05. Jan 2000:"
|
||||||
|
split_delimiter = ":"
|
||||||
|
else:
|
||||||
|
# Meeting name contains date and start/end times: "05. Jan 2000, 16:00 - 17:30:"
|
||||||
|
split_delimiter = ", "
|
||||||
|
|
||||||
|
# We have a meeting day without time
|
||||||
|
date_portion_str = meeting_name.split(split_delimiter)[0]
|
||||||
date_portion = demangle_date(date_portion_str)
|
date_portion = demangle_date(date_portion_str)
|
||||||
|
|
||||||
|
# We failed to parse the date, bail out
|
||||||
if not date_portion:
|
if not date_portion:
|
||||||
return meeting_name
|
return meeting_name
|
||||||
|
|
||||||
rest_of_name = meeting_name
|
# Replace the first section with the absolute date
|
||||||
if rest_of_name.startswith(date_portion_str):
|
rest_of_name = split_delimiter.join(meeting_name.split(split_delimiter)[1:])
|
||||||
rest_of_name = rest_of_name[len(date_portion_str):]
|
return datetime.strftime(date_portion, "%Y-%m-%d") + split_delimiter + rest_of_name
|
||||||
|
|
||||||
return datetime.strftime(date_portion, "%Y-%m-%d, %H:%M") + rest_of_name
|
|
||||||
|
|
||||||
def _abs_url_from_link(self, link_tag: Tag) -> str:
|
def _abs_url_from_link(self, link_tag: Tag) -> str:
|
||||||
"""
|
"""
|
||||||
@ -744,35 +896,47 @@ english_months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
|
|||||||
|
|
||||||
def demangle_date(date_str: str, fail_silently: bool = False) -> Optional[datetime]:
|
def demangle_date(date_str: str, fail_silently: bool = False) -> Optional[datetime]:
|
||||||
"""
|
"""
|
||||||
Demangle a given date in one of the following formats:
|
Demangle a given date in one of the following formats (hour/minute part is optional):
|
||||||
"Gestern, HH:MM"
|
"Gestern, HH:MM"
|
||||||
"Heute, HH:MM"
|
"Heute, HH:MM"
|
||||||
"Morgen, HH:MM"
|
"Morgen, HH:MM"
|
||||||
"dd. mon yyyy, HH:MM
|
"dd. mon yyyy, HH:MM
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
|
# Normalize whitespace because users
|
||||||
date_str = re.sub(r"\s+", " ", date_str)
|
date_str = re.sub(r"\s+", " ", date_str)
|
||||||
|
|
||||||
date_str = re.sub("Gestern|Yesterday", _format_date_english(_yesterday()), date_str, re.I)
|
date_str = re.sub("Gestern|Yesterday", _format_date_english(_yesterday()), date_str, re.I)
|
||||||
date_str = re.sub("Heute|Today", _format_date_english(date.today()), date_str, re.I)
|
date_str = re.sub("Heute|Today", _format_date_english(date.today()), date_str, re.I)
|
||||||
date_str = re.sub("Morgen|Tomorrow", _format_date_english(_tomorrow()), date_str, re.I)
|
date_str = re.sub("Morgen|Tomorrow", _format_date_english(_tomorrow()), date_str, re.I)
|
||||||
|
date_str = date_str.strip()
|
||||||
for german, english in zip(german_months, english_months):
|
for german, english in zip(german_months, english_months):
|
||||||
date_str = date_str.replace(german, english)
|
date_str = date_str.replace(german, english)
|
||||||
# Remove trailing dots for abbreviations, e.g. "20. Apr. 2020" -> "20. Apr 2020"
|
# Remove trailing dots for abbreviations, e.g. "20. Apr. 2020" -> "20. Apr 2020"
|
||||||
date_str = date_str.replace(english + ".", english)
|
date_str = date_str.replace(english + ".", english)
|
||||||
|
|
||||||
# We now have a nice english String in the format: "dd. mmm yyyy, hh:mm"
|
# We now have a nice english String in the format: "dd. mmm yyyy, hh:mm" or "dd. mmm yyyy"
|
||||||
|
|
||||||
|
# Check if we have a time as well
|
||||||
|
if ", " in date_str:
|
||||||
day_part, time_part = date_str.split(",")
|
day_part, time_part = date_str.split(",")
|
||||||
|
else:
|
||||||
|
day_part = date_str.split(",")[0]
|
||||||
|
time_part = None
|
||||||
|
|
||||||
day_str, month_str, year_str = day_part.split(" ")
|
day_str, month_str, year_str = day_part.split(" ")
|
||||||
|
|
||||||
day = int(day_str.strip().replace(".", ""))
|
day = int(day_str.strip().replace(".", ""))
|
||||||
month = english_months.index(month_str.strip()) + 1
|
month = english_months.index(month_str.strip()) + 1
|
||||||
year = int(year_str.strip())
|
year = int(year_str.strip())
|
||||||
|
|
||||||
|
if time_part:
|
||||||
hour_str, minute_str = time_part.split(":")
|
hour_str, minute_str = time_part.split(":")
|
||||||
hour = int(hour_str)
|
hour = int(hour_str)
|
||||||
minute = int(minute_str)
|
minute = int(minute_str)
|
||||||
|
|
||||||
return datetime(year, month, day, hour, minute)
|
return datetime(year, month, day, hour, minute)
|
||||||
|
|
||||||
|
return datetime(year, month, day)
|
||||||
except Exception:
|
except Exception:
|
||||||
if not fail_silently:
|
if not fail_silently:
|
||||||
log.warn(f"Date parsing failed for {date_str!r}")
|
log.warn(f"Date parsing failed for {date_str!r}")
|
||||||
@ -794,3 +958,45 @@ def _tomorrow() -> date:
|
|||||||
|
|
||||||
def _sanitize_path_name(name: str) -> str:
|
def _sanitize_path_name(name: str) -> str:
|
||||||
return name.replace("/", "-").replace("\\", "-").strip()
|
return name.replace("/", "-").replace("\\", "-").strip()
|
||||||
|
|
||||||
|
|
||||||
|
def parse_ilias_forum_export(forum_export: BeautifulSoup) -> List[IliasForumThread]:
|
||||||
|
elements = []
|
||||||
|
for p in forum_export.select("body > p"):
|
||||||
|
title_tag = p
|
||||||
|
content_tag = p.find_next_sibling("ul")
|
||||||
|
|
||||||
|
if not content_tag:
|
||||||
|
# ILIAS allows users to delete the initial post while keeping the thread open
|
||||||
|
# This produces empty threads without *any* content.
|
||||||
|
# I am not sure why you would want this, but ILIAS makes it easy to do.
|
||||||
|
continue
|
||||||
|
|
||||||
|
title = p.find("b").text
|
||||||
|
if ":" in title:
|
||||||
|
title = title[title.find(":") + 1:]
|
||||||
|
title = title.strip()
|
||||||
|
mtime = _guess_timestamp_from_forum_post_content(content_tag)
|
||||||
|
elements.append(IliasForumThread(title, title_tag, content_tag, mtime))
|
||||||
|
|
||||||
|
return elements
|
||||||
|
|
||||||
|
|
||||||
|
def _guess_timestamp_from_forum_post_content(content: Tag) -> Optional[datetime]:
|
||||||
|
posts: Optional[Tag] = content.select(".ilFrmPostHeader > span.small")
|
||||||
|
if not posts:
|
||||||
|
return None
|
||||||
|
|
||||||
|
newest_date: Optional[datetime] = None
|
||||||
|
|
||||||
|
for post in posts:
|
||||||
|
text = post.text.strip()
|
||||||
|
text = text[text.rfind("|") + 1:]
|
||||||
|
date = demangle_date(text, fail_silently=True)
|
||||||
|
if not date:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if not newest_date or newest_date < date:
|
||||||
|
newest_date = date
|
||||||
|
|
||||||
|
return newest_date
|
||||||
|
@ -1,7 +1,8 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
import re
|
import re
|
||||||
|
from collections.abc import Awaitable, Coroutine
|
||||||
from pathlib import PurePath
|
from pathlib import PurePath
|
||||||
from typing import Any, Awaitable, Callable, Dict, List, Optional, Set, TypeVar, Union, cast
|
from typing import Any, Callable, Dict, List, Optional, Set, Union, cast
|
||||||
|
|
||||||
import aiohttp
|
import aiohttp
|
||||||
import yarl
|
import yarl
|
||||||
@ -13,13 +14,21 @@ from ...config import Config
|
|||||||
from ...logging import ProgressBar, log
|
from ...logging import ProgressBar, log
|
||||||
from ...output_dir import FileSink, Redownload
|
from ...output_dir import FileSink, Redownload
|
||||||
from ...utils import fmt_path, soupify, url_set_query_param
|
from ...utils import fmt_path, soupify, url_set_query_param
|
||||||
from ..crawler import CrawlError, CrawlToken, CrawlWarning, DownloadToken, anoncritical
|
from ..crawler import AWrapped, CrawlError, CrawlToken, CrawlWarning, DownloadToken, anoncritical
|
||||||
from ..http_crawler import HttpCrawler, HttpCrawlerSection
|
from ..http_crawler import HttpCrawler, HttpCrawlerSection
|
||||||
from .file_templates import Links
|
from .file_templates import Links
|
||||||
from .kit_ilias_html import IliasElementType, IliasPage, IliasPageElement
|
from .ilias_html_cleaner import clean, insert_base_markup
|
||||||
|
from .kit_ilias_html import (IliasElementType, IliasForumThread, IliasPage, IliasPageElement,
|
||||||
|
_sanitize_path_name, parse_ilias_forum_export)
|
||||||
|
|
||||||
TargetType = Union[str, int]
|
TargetType = Union[str, int]
|
||||||
|
|
||||||
|
_ILIAS_URL = "https://ilias.studium.kit.edu"
|
||||||
|
|
||||||
|
|
||||||
|
class KitShibbolethBackgroundLoginSuccessful():
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
class KitIliasWebCrawlerSection(HttpCrawlerSection):
|
class KitIliasWebCrawlerSection(HttpCrawlerSection):
|
||||||
def target(self) -> TargetType:
|
def target(self) -> TargetType:
|
||||||
@ -33,7 +42,7 @@ class KitIliasWebCrawlerSection(HttpCrawlerSection):
|
|||||||
if target == "desktop":
|
if target == "desktop":
|
||||||
# Full personal desktop
|
# Full personal desktop
|
||||||
return target
|
return target
|
||||||
if target.startswith("https://ilias.studium.kit.edu"):
|
if target.startswith(_ILIAS_URL):
|
||||||
# ILIAS URL
|
# ILIAS URL
|
||||||
return target
|
return target
|
||||||
|
|
||||||
@ -65,6 +74,9 @@ class KitIliasWebCrawlerSection(HttpCrawlerSection):
|
|||||||
def videos(self) -> bool:
|
def videos(self) -> bool:
|
||||||
return self.s.getboolean("videos", fallback=False)
|
return self.s.getboolean("videos", fallback=False)
|
||||||
|
|
||||||
|
def forums(self) -> bool:
|
||||||
|
return self.s.getboolean("forums", fallback=False)
|
||||||
|
|
||||||
|
|
||||||
_DIRECTORY_PAGES: Set[IliasElementType] = set([
|
_DIRECTORY_PAGES: Set[IliasElementType] = set([
|
||||||
IliasElementType.EXERCISE,
|
IliasElementType.EXERCISE,
|
||||||
@ -82,8 +94,6 @@ _VIDEO_ELEMENTS: Set[IliasElementType] = set([
|
|||||||
IliasElementType.VIDEO_FOLDER_MAYBE_PAGINATED,
|
IliasElementType.VIDEO_FOLDER_MAYBE_PAGINATED,
|
||||||
])
|
])
|
||||||
|
|
||||||
AWrapped = TypeVar("AWrapped", bound=Callable[..., Awaitable[Optional[Any]]])
|
|
||||||
|
|
||||||
|
|
||||||
def _iorepeat(attempts: int, name: str, failure_is_error: bool = False) -> Callable[[AWrapped], AWrapped]:
|
def _iorepeat(attempts: int, name: str, failure_is_error: bool = False) -> Callable[[AWrapped], AWrapped]:
|
||||||
def decorator(f: AWrapped) -> AWrapped:
|
def decorator(f: AWrapped) -> AWrapped:
|
||||||
@ -177,12 +187,13 @@ instance's greatest bottleneck.
|
|||||||
section.tfa_auth(authenticators),
|
section.tfa_auth(authenticators),
|
||||||
)
|
)
|
||||||
|
|
||||||
self._base_url = "https://ilias.studium.kit.edu"
|
self._base_url = _ILIAS_URL
|
||||||
|
|
||||||
self._target = section.target()
|
self._target = section.target()
|
||||||
self._link_file_redirect_delay = section.link_redirect_delay()
|
self._link_file_redirect_delay = section.link_redirect_delay()
|
||||||
self._links = section.links()
|
self._links = section.links()
|
||||||
self._videos = section.videos()
|
self._videos = section.videos()
|
||||||
|
self._forums = section.forums()
|
||||||
self._visited_urls: Set[str] = set()
|
self._visited_urls: Set[str] = set()
|
||||||
|
|
||||||
async def _run(self) -> None:
|
async def _run(self) -> None:
|
||||||
@ -216,27 +227,44 @@ instance's greatest bottleneck.
|
|||||||
cl = maybe_cl # Not mypy's fault, but explained here: https://github.com/python/mypy/issues/2608
|
cl = maybe_cl # Not mypy's fault, but explained here: https://github.com/python/mypy/issues/2608
|
||||||
|
|
||||||
elements: List[IliasPageElement] = []
|
elements: List[IliasPageElement] = []
|
||||||
|
# A list as variable redefinitions are not propagated to outer scopes
|
||||||
|
description: List[BeautifulSoup] = []
|
||||||
|
|
||||||
@_iorepeat(3, "crawling url")
|
@_iorepeat(3, "crawling url")
|
||||||
async def gather_elements() -> None:
|
async def gather_elements() -> None:
|
||||||
elements.clear()
|
elements.clear()
|
||||||
async with cl:
|
async with cl:
|
||||||
soup = await self._get_page(url)
|
next_stage_url: Optional[str] = url
|
||||||
|
current_parent = None
|
||||||
|
|
||||||
if expected_id is not None:
|
# Duplicated code, but the root page is special - we want to avoid fetching it twice!
|
||||||
|
while next_stage_url:
|
||||||
|
soup = await self._get_page(next_stage_url)
|
||||||
|
|
||||||
|
if current_parent is None and expected_id is not None:
|
||||||
perma_link_element: Tag = soup.find(id="current_perma_link")
|
perma_link_element: Tag = soup.find(id="current_perma_link")
|
||||||
if not perma_link_element or "crs_" not in perma_link_element.get("value"):
|
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")
|
raise CrawlError("Invalid course id? Didn't find anything looking like a course")
|
||||||
|
|
||||||
# Duplicated code, but the root page is special - we want to avoid fetching it twice!
|
log.explain_topic(f"Parsing HTML page for {fmt_path(cl.path)}")
|
||||||
log.explain_topic("Parsing root HTML page")
|
log.explain(f"URL: {next_stage_url}")
|
||||||
log.explain(f"URL: {url}")
|
page = IliasPage(soup, next_stage_url, current_parent)
|
||||||
page = IliasPage(soup, url, None)
|
if next_element := page.get_next_stage_element():
|
||||||
|
current_parent = next_element
|
||||||
|
next_stage_url = next_element.url
|
||||||
|
else:
|
||||||
|
next_stage_url = None
|
||||||
|
|
||||||
elements.extend(page.get_child_elements())
|
elements.extend(page.get_child_elements())
|
||||||
|
if description_string := page.get_description():
|
||||||
|
description.append(description_string)
|
||||||
|
|
||||||
# Fill up our task list with the found elements
|
# Fill up our task list with the found elements
|
||||||
await gather_elements()
|
await gather_elements()
|
||||||
|
|
||||||
|
if description:
|
||||||
|
await self._download_description(PurePath("."), description[0])
|
||||||
|
|
||||||
elements.sort(key=lambda e: e.id())
|
elements.sort(key=lambda e: e.id())
|
||||||
|
|
||||||
tasks: List[Awaitable[None]] = []
|
tasks: List[Awaitable[None]] = []
|
||||||
@ -252,7 +280,7 @@ instance's greatest bottleneck.
|
|||||||
url: str,
|
url: str,
|
||||||
parent: IliasPageElement,
|
parent: IliasPageElement,
|
||||||
path: PurePath,
|
path: PurePath,
|
||||||
) -> Optional[Awaitable[None]]:
|
) -> Optional[Coroutine[Any, Any, None]]:
|
||||||
maybe_cl = await self.crawl(path)
|
maybe_cl = await self.crawl(path)
|
||||||
if not maybe_cl:
|
if not maybe_cl:
|
||||||
return None
|
return None
|
||||||
@ -266,6 +294,8 @@ instance's greatest bottleneck.
|
|||||||
cl: CrawlToken,
|
cl: CrawlToken,
|
||||||
) -> None:
|
) -> None:
|
||||||
elements: List[IliasPageElement] = []
|
elements: List[IliasPageElement] = []
|
||||||
|
# A list as variable redefinitions are not propagated to outer scopes
|
||||||
|
description: List[BeautifulSoup] = []
|
||||||
|
|
||||||
@_iorepeat(3, "crawling folder")
|
@_iorepeat(3, "crawling folder")
|
||||||
async def gather_elements() -> None:
|
async def gather_elements() -> None:
|
||||||
@ -286,10 +316,15 @@ instance's greatest bottleneck.
|
|||||||
next_stage_url = None
|
next_stage_url = None
|
||||||
|
|
||||||
elements.extend(page.get_child_elements())
|
elements.extend(page.get_child_elements())
|
||||||
|
if description_string := page.get_description():
|
||||||
|
description.append(description_string)
|
||||||
|
|
||||||
# Fill up our task list with the found elements
|
# Fill up our task list with the found elements
|
||||||
await gather_elements()
|
await gather_elements()
|
||||||
|
|
||||||
|
if description:
|
||||||
|
await self._download_description(cl.path, description[0])
|
||||||
|
|
||||||
elements.sort(key=lambda e: e.id())
|
elements.sort(key=lambda e: e.id())
|
||||||
|
|
||||||
tasks: List[Awaitable[None]] = []
|
tasks: List[Awaitable[None]] = []
|
||||||
@ -310,7 +345,7 @@ instance's greatest bottleneck.
|
|||||||
self,
|
self,
|
||||||
parent_path: PurePath,
|
parent_path: PurePath,
|
||||||
element: IliasPageElement,
|
element: IliasPageElement,
|
||||||
) -> Optional[Awaitable[None]]:
|
) -> Optional[Coroutine[Any, Any, None]]:
|
||||||
if element.url in self._visited_urls:
|
if element.url in self._visited_urls:
|
||||||
raise CrawlWarning(
|
raise CrawlWarning(
|
||||||
f"Found second path to element {element.name!r} at {element.url!r}. Aborting subpath"
|
f"Found second path to element {element.name!r} at {element.url!r}. Aborting subpath"
|
||||||
@ -320,26 +355,42 @@ instance's greatest bottleneck.
|
|||||||
element_path = PurePath(parent_path, element.name)
|
element_path = PurePath(parent_path, element.name)
|
||||||
|
|
||||||
if element.type in _VIDEO_ELEMENTS:
|
if element.type in _VIDEO_ELEMENTS:
|
||||||
log.explain_topic(f"Decision: Crawl video element {fmt_path(element_path)}")
|
|
||||||
if not self._videos:
|
if not self._videos:
|
||||||
log.explain("Video crawling is disabled")
|
log.status(
|
||||||
log.explain("Answer: no")
|
"[bold bright_black]",
|
||||||
|
"Ignored",
|
||||||
|
fmt_path(element_path),
|
||||||
|
"[bright_black](enable with option 'videos')"
|
||||||
|
)
|
||||||
return None
|
return None
|
||||||
else:
|
|
||||||
log.explain("Video crawling is enabled")
|
|
||||||
log.explain("Answer: yes")
|
|
||||||
|
|
||||||
if element.type == IliasElementType.FILE:
|
if element.type == IliasElementType.FILE:
|
||||||
return await self._handle_file(element, element_path)
|
return await self._handle_file(element, element_path)
|
||||||
elif element.type == IliasElementType.FORUM:
|
elif element.type == IliasElementType.FORUM:
|
||||||
log.explain_topic(f"Decision: Crawl {fmt_path(element_path)}")
|
if not self._forums:
|
||||||
log.explain("Forums are not supported")
|
log.status(
|
||||||
log.explain("Answer: No")
|
"[bold bright_black]",
|
||||||
|
"Ignored",
|
||||||
|
fmt_path(element_path),
|
||||||
|
"[bright_black](enable with option 'forums')"
|
||||||
|
)
|
||||||
return None
|
return None
|
||||||
|
return await self._handle_forum(element, element_path)
|
||||||
elif element.type == IliasElementType.TEST:
|
elif element.type == IliasElementType.TEST:
|
||||||
log.explain_topic(f"Decision: Crawl {fmt_path(element_path)}")
|
log.status(
|
||||||
log.explain("Tests contain no relevant files")
|
"[bold bright_black]",
|
||||||
log.explain("Answer: No")
|
"Ignored",
|
||||||
|
fmt_path(element_path),
|
||||||
|
"[bright_black](tests contain no relevant data)"
|
||||||
|
)
|
||||||
|
return None
|
||||||
|
elif element.type == IliasElementType.SURVEY:
|
||||||
|
log.status(
|
||||||
|
"[bold bright_black]",
|
||||||
|
"Ignored",
|
||||||
|
fmt_path(element_path),
|
||||||
|
"[bright_black](surveys contain no relevant data)"
|
||||||
|
)
|
||||||
return None
|
return None
|
||||||
elif element.type == IliasElementType.LINK:
|
elif element.type == IliasElementType.LINK:
|
||||||
return await self._handle_link(element, element_path)
|
return await self._handle_link(element, element_path)
|
||||||
@ -360,7 +411,7 @@ instance's greatest bottleneck.
|
|||||||
self,
|
self,
|
||||||
element: IliasPageElement,
|
element: IliasPageElement,
|
||||||
element_path: PurePath,
|
element_path: PurePath,
|
||||||
) -> Optional[Awaitable[None]]:
|
) -> Optional[Coroutine[Any, Any, None]]:
|
||||||
log.explain_topic(f"Decision: Crawl Link {fmt_path(element_path)}")
|
log.explain_topic(f"Decision: Crawl Link {fmt_path(element_path)}")
|
||||||
log.explain(f"Links type is {self._links}")
|
log.explain(f"Links type is {self._links}")
|
||||||
|
|
||||||
@ -407,7 +458,7 @@ instance's greatest bottleneck.
|
|||||||
self,
|
self,
|
||||||
element: IliasPageElement,
|
element: IliasPageElement,
|
||||||
element_path: PurePath,
|
element_path: PurePath,
|
||||||
) -> Optional[Awaitable[None]]:
|
) -> Optional[Coroutine[Any, Any, None]]:
|
||||||
log.explain_topic(f"Decision: Crawl Booking Link {fmt_path(element_path)}")
|
log.explain_topic(f"Decision: Crawl Booking Link {fmt_path(element_path)}")
|
||||||
log.explain(f"Links type is {self._links}")
|
log.explain(f"Links type is {self._links}")
|
||||||
|
|
||||||
@ -426,6 +477,19 @@ instance's greatest bottleneck.
|
|||||||
|
|
||||||
return self._download_booking(element, link_template_maybe, maybe_dl)
|
return self._download_booking(element, link_template_maybe, maybe_dl)
|
||||||
|
|
||||||
|
@anoncritical
|
||||||
|
@_iorepeat(1, "downloading description")
|
||||||
|
async def _download_description(self, parent_path: PurePath, description: BeautifulSoup) -> None:
|
||||||
|
path = parent_path / "Description.html"
|
||||||
|
dl = await self.download(path, redownload=Redownload.ALWAYS)
|
||||||
|
if not dl:
|
||||||
|
return
|
||||||
|
|
||||||
|
async with dl as (bar, sink):
|
||||||
|
description = clean(insert_base_markup(description))
|
||||||
|
sink.file.write(description.prettify().encode("utf-8"))
|
||||||
|
sink.done()
|
||||||
|
|
||||||
@anoncritical
|
@anoncritical
|
||||||
@_iorepeat(3, "resolving booking")
|
@_iorepeat(3, "resolving booking")
|
||||||
async def _download_booking(
|
async def _download_booking(
|
||||||
@ -443,7 +507,7 @@ instance's greatest bottleneck.
|
|||||||
if hdrs.LOCATION not in resp.headers:
|
if hdrs.LOCATION not in resp.headers:
|
||||||
return soupify(await resp.read()).select_one("a").get("href").strip()
|
return soupify(await resp.read()).select_one("a").get("href").strip()
|
||||||
|
|
||||||
self._authenticate()
|
await self._authenticate()
|
||||||
|
|
||||||
async with self.session.get(export_url, allow_redirects=False) as resp:
|
async with self.session.get(export_url, allow_redirects=False) as resp:
|
||||||
# No redirect means we were authenticated
|
# No redirect means we were authenticated
|
||||||
@ -456,7 +520,7 @@ instance's greatest bottleneck.
|
|||||||
self,
|
self,
|
||||||
element: IliasPageElement,
|
element: IliasPageElement,
|
||||||
element_path: PurePath,
|
element_path: PurePath,
|
||||||
) -> Optional[Awaitable[None]]:
|
) -> Optional[Coroutine[Any, Any, None]]:
|
||||||
# Copy old mapping as it is likely still relevant
|
# Copy old mapping as it is likely still relevant
|
||||||
if self.prev_report:
|
if self.prev_report:
|
||||||
self.report.add_custom_value(
|
self.report.add_custom_value(
|
||||||
@ -564,7 +628,7 @@ instance's greatest bottleneck.
|
|||||||
self,
|
self,
|
||||||
element: IliasPageElement,
|
element: IliasPageElement,
|
||||||
element_path: PurePath,
|
element_path: PurePath,
|
||||||
) -> Optional[Awaitable[None]]:
|
) -> Optional[Coroutine[Any, Any, None]]:
|
||||||
maybe_dl = await self.download(element_path, mtime=element.mtime)
|
maybe_dl = await self.download(element_path, mtime=element.mtime)
|
||||||
if not maybe_dl:
|
if not maybe_dl:
|
||||||
return None
|
return None
|
||||||
@ -607,6 +671,72 @@ instance's greatest bottleneck.
|
|||||||
if not await try_stream():
|
if not await try_stream():
|
||||||
raise CrawlError("File streaming failed after authenticate()")
|
raise CrawlError("File streaming failed after authenticate()")
|
||||||
|
|
||||||
|
async def _handle_forum(
|
||||||
|
self,
|
||||||
|
element: IliasPageElement,
|
||||||
|
element_path: PurePath,
|
||||||
|
) -> Optional[Coroutine[Any, Any, None]]:
|
||||||
|
maybe_cl = await self.crawl(element_path)
|
||||||
|
if not maybe_cl:
|
||||||
|
return None
|
||||||
|
return self._crawl_forum(element, maybe_cl)
|
||||||
|
|
||||||
|
@_iorepeat(3, "crawling forum")
|
||||||
|
@anoncritical
|
||||||
|
async def _crawl_forum(self, element: IliasPageElement, cl: CrawlToken) -> None:
|
||||||
|
elements: List[IliasForumThread] = []
|
||||||
|
|
||||||
|
async with cl:
|
||||||
|
next_stage_url = element.url
|
||||||
|
while next_stage_url:
|
||||||
|
log.explain_topic(f"Parsing HTML page for {fmt_path(cl.path)}")
|
||||||
|
log.explain(f"URL: {next_stage_url}")
|
||||||
|
|
||||||
|
soup = await self._get_page(next_stage_url)
|
||||||
|
page = IliasPage(soup, next_stage_url, None)
|
||||||
|
|
||||||
|
if next := page.get_next_stage_element():
|
||||||
|
next_stage_url = next.url
|
||||||
|
else:
|
||||||
|
break
|
||||||
|
|
||||||
|
download_data = page.get_download_forum_data()
|
||||||
|
if not download_data:
|
||||||
|
raise CrawlWarning("Failed to extract forum data")
|
||||||
|
if download_data.empty:
|
||||||
|
log.explain("Forum had no threads")
|
||||||
|
elements = []
|
||||||
|
return
|
||||||
|
html = await self._post_authenticated(download_data.url, download_data.form_data)
|
||||||
|
elements = parse_ilias_forum_export(soupify(html))
|
||||||
|
|
||||||
|
elements.sort(key=lambda elem: elem.title)
|
||||||
|
|
||||||
|
tasks: List[Awaitable[None]] = []
|
||||||
|
for elem in elements:
|
||||||
|
tasks.append(asyncio.create_task(self._download_forum_thread(cl.path, elem)))
|
||||||
|
|
||||||
|
# And execute them
|
||||||
|
await self.gather(tasks)
|
||||||
|
|
||||||
|
@anoncritical
|
||||||
|
@_iorepeat(3, "saving forum thread")
|
||||||
|
async def _download_forum_thread(
|
||||||
|
self,
|
||||||
|
parent_path: PurePath,
|
||||||
|
element: IliasForumThread,
|
||||||
|
) -> None:
|
||||||
|
path = parent_path / (_sanitize_path_name(element.title) + ".html")
|
||||||
|
maybe_dl = await self.download(path, mtime=element.mtime)
|
||||||
|
if not maybe_dl:
|
||||||
|
return
|
||||||
|
|
||||||
|
async with maybe_dl as (bar, sink):
|
||||||
|
content = element.title_tag.prettify()
|
||||||
|
content += element.content_tag.prettify()
|
||||||
|
sink.file.write(content.encode("utf-8"))
|
||||||
|
sink.done()
|
||||||
|
|
||||||
async def _get_page(self, url: str) -> BeautifulSoup:
|
async def _get_page(self, url: str) -> BeautifulSoup:
|
||||||
auth_id = await self._current_auth_id()
|
auth_id = await self._current_auth_id()
|
||||||
async with self.session.get(url) as request:
|
async with self.session.get(url) as request:
|
||||||
@ -624,6 +754,30 @@ instance's greatest bottleneck.
|
|||||||
return soup
|
return soup
|
||||||
raise CrawlError("get_page failed even after authenticating")
|
raise CrawlError("get_page failed even after authenticating")
|
||||||
|
|
||||||
|
async def _post_authenticated(
|
||||||
|
self,
|
||||||
|
url: str,
|
||||||
|
data: dict[str, Union[str, List[str]]]
|
||||||
|
) -> BeautifulSoup:
|
||||||
|
auth_id = await self._current_auth_id()
|
||||||
|
|
||||||
|
form_data = aiohttp.FormData()
|
||||||
|
for key, val in data.items():
|
||||||
|
form_data.add_field(key, val)
|
||||||
|
|
||||||
|
async with self.session.post(url, data=form_data(), allow_redirects=False) as request:
|
||||||
|
if request.status == 200:
|
||||||
|
return await request.read()
|
||||||
|
|
||||||
|
# We weren't authenticated, so try to do that
|
||||||
|
await self.authenticate(auth_id)
|
||||||
|
|
||||||
|
# Retry once after authenticating. If this fails, we will die.
|
||||||
|
async with self.session.post(url, data=data, allow_redirects=False) as request:
|
||||||
|
if request.status == 200:
|
||||||
|
return await request.read()
|
||||||
|
raise CrawlError("post_authenticated failed even after authenticating")
|
||||||
|
|
||||||
# We repeat this as the login method in shibboleth doesn't handle I/O errors.
|
# 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.
|
# Shibboleth is quite reliable as well, the repeat is likely not critical here.
|
||||||
@ _iorepeat(3, "Login", failure_is_error=True)
|
@ _iorepeat(3, "Login", failure_is_error=True)
|
||||||
@ -635,7 +789,7 @@ instance's greatest bottleneck.
|
|||||||
# Normal ILIAS pages
|
# Normal ILIAS pages
|
||||||
mainbar: Optional[Tag] = soup.find(class_="il-maincontrols-metabar")
|
mainbar: Optional[Tag] = soup.find(class_="il-maincontrols-metabar")
|
||||||
if mainbar is not None:
|
if mainbar is not None:
|
||||||
login_button = mainbar.find("button", attrs={"data-action": lambda x: x and "login.php" in x})
|
login_button = mainbar.find(attrs={"href": lambda x: x and "login.php" in x})
|
||||||
shib_login = soup.find(id="button_shib_login")
|
shib_login = soup.find(id="button_shib_login")
|
||||||
return not login_button and not shib_login
|
return not login_button and not shib_login
|
||||||
|
|
||||||
@ -680,14 +834,17 @@ class KitShibbolethLogin:
|
|||||||
|
|
||||||
# Equivalent: Click on "Mit KIT-Account anmelden" button in
|
# Equivalent: Click on "Mit KIT-Account anmelden" button in
|
||||||
# https://ilias.studium.kit.edu/login.php
|
# https://ilias.studium.kit.edu/login.php
|
||||||
url = "https://ilias.studium.kit.edu/shib_login.php"
|
url = f"{_ILIAS_URL}/shib_login.php"
|
||||||
data = {
|
data = {
|
||||||
"sendLogin": "1",
|
"sendLogin": "1",
|
||||||
"idp_selection": "https://idp.scc.kit.edu/idp/shibboleth",
|
"idp_selection": "https://idp.scc.kit.edu/idp/shibboleth",
|
||||||
"il_target": "",
|
"il_target": "",
|
||||||
"home_organization_selection": "Weiter",
|
"home_organization_selection": "Weiter",
|
||||||
}
|
}
|
||||||
soup: BeautifulSoup = await _shib_post(sess, url, data)
|
soup: Union[BeautifulSoup, KitShibbolethBackgroundLoginSuccessful] = await _shib_post(sess, url, data)
|
||||||
|
|
||||||
|
if isinstance(soup, KitShibbolethBackgroundLoginSuccessful):
|
||||||
|
return
|
||||||
|
|
||||||
# Attempt to login using credentials, if necessary
|
# Attempt to login using credentials, if necessary
|
||||||
while not self._login_successful(soup):
|
while not self._login_successful(soup):
|
||||||
@ -710,6 +867,12 @@ class KitShibbolethLogin:
|
|||||||
}
|
}
|
||||||
soup = await _post(sess, url, data)
|
soup = await _post(sess, url, data)
|
||||||
|
|
||||||
|
if soup.find(id="attributeRelease"):
|
||||||
|
raise CrawlError(
|
||||||
|
"ILIAS Shibboleth entitlements changed! "
|
||||||
|
"Please log in once in your browser and review them"
|
||||||
|
)
|
||||||
|
|
||||||
if self._tfa_required(soup):
|
if self._tfa_required(soup):
|
||||||
soup = await self._authenticate_tfa(sess, soup)
|
soup = await self._authenticate_tfa(sess, soup)
|
||||||
|
|
||||||
@ -720,7 +883,7 @@ class KitShibbolethLogin:
|
|||||||
# (or clicking "Continue" if you have JS disabled)
|
# (or clicking "Continue" if you have JS disabled)
|
||||||
relay_state = soup.find("input", {"name": "RelayState"})
|
relay_state = soup.find("input", {"name": "RelayState"})
|
||||||
saml_response = soup.find("input", {"name": "SAMLResponse"})
|
saml_response = soup.find("input", {"name": "SAMLResponse"})
|
||||||
url = "https://ilias.studium.kit.edu/Shibboleth.sso/SAML2/POST"
|
url = f"{_ILIAS_URL}/Shibboleth.sso/SAML2/POST"
|
||||||
data = { # using the info obtained in the while loop above
|
data = { # using the info obtained in the while loop above
|
||||||
"RelayState": relay_state["value"],
|
"RelayState": relay_state["value"],
|
||||||
"SAMLResponse": saml_response["value"],
|
"SAMLResponse": saml_response["value"],
|
||||||
@ -769,24 +932,41 @@ async def _post(session: aiohttp.ClientSession, url: str, data: Any) -> Beautifu
|
|||||||
return soupify(await response.read())
|
return soupify(await response.read())
|
||||||
|
|
||||||
|
|
||||||
async def _shib_post(session: aiohttp.ClientSession, url: str, data: Any) -> BeautifulSoup:
|
async def _shib_post(
|
||||||
|
session: aiohttp.ClientSession,
|
||||||
|
url: str,
|
||||||
|
data: Any
|
||||||
|
) -> Union[BeautifulSoup, KitShibbolethBackgroundLoginSuccessful]:
|
||||||
"""
|
"""
|
||||||
aiohttp unescapes '/' and ':' in URL query parameters which is not RFC compliant and rejected
|
aiohttp unescapes '/' and ':' in URL query parameters which is not RFC compliant and rejected
|
||||||
by Shibboleth. Thanks a lot. So now we unroll the requests manually, parse location headers and
|
by Shibboleth. Thanks a lot. So now we unroll the requests manually, parse location headers and
|
||||||
build encoded URL objects ourselves... Who thought mangling location header was a good idea??
|
build encoded URL objects ourselves... Who thought mangling location header was a good idea??
|
||||||
"""
|
"""
|
||||||
|
log.explain_topic("Shib login POST")
|
||||||
async with session.post(url, data=data, allow_redirects=False) as response:
|
async with session.post(url, data=data, allow_redirects=False) as response:
|
||||||
location = response.headers.get("location")
|
location = response.headers.get("location")
|
||||||
|
log.explain(f"Got location {location!r}")
|
||||||
if not location:
|
if not location:
|
||||||
raise CrawlWarning(f"Login failed, no location header present at {url}")
|
raise CrawlWarning(f"Login failed (1), no location header present at {url}")
|
||||||
correct_url = yarl.URL(location, encoded=True)
|
correct_url = yarl.URL(location, encoded=True)
|
||||||
|
log.explain(f"Corrected location to {correct_url!r}")
|
||||||
|
|
||||||
|
if str(correct_url).startswith(_ILIAS_URL):
|
||||||
|
log.explain("ILIAS recognized our shib token and logged us in in the background, returning")
|
||||||
|
return KitShibbolethBackgroundLoginSuccessful()
|
||||||
|
|
||||||
async with session.get(correct_url, allow_redirects=False) as response:
|
async with session.get(correct_url, allow_redirects=False) as response:
|
||||||
as_yarl = yarl.URL(response.url)
|
|
||||||
location = response.headers.get("location")
|
location = response.headers.get("location")
|
||||||
|
log.explain(f"Redirected to {location!r} with status {response.status}")
|
||||||
|
# If shib still still has a valid session, it will directly respond to the request
|
||||||
|
if location is None:
|
||||||
|
log.explain("Shib recognized us, returning its response directly")
|
||||||
|
return soupify(await response.read())
|
||||||
|
|
||||||
|
as_yarl = yarl.URL(response.url)
|
||||||
|
# Probably not needed anymore, but might catch a few weird situations with a nicer message
|
||||||
if not location or not as_yarl.host:
|
if not location or not as_yarl.host:
|
||||||
raise CrawlWarning(f"Login failed, no location header present at {correct_url}")
|
raise CrawlWarning(f"Login failed (2), no location header present at {correct_url}")
|
||||||
|
|
||||||
correct_url = yarl.URL.build(
|
correct_url = yarl.URL.build(
|
||||||
scheme=as_yarl.scheme,
|
scheme=as_yarl.scheme,
|
||||||
@ -794,6 +974,7 @@ async def _shib_post(session: aiohttp.ClientSession, url: str, data: Any) -> Bea
|
|||||||
path=location,
|
path=location,
|
||||||
encoded=True
|
encoded=True
|
||||||
)
|
)
|
||||||
|
log.explain(f"Corrected location to {correct_url!r}")
|
||||||
|
|
||||||
async with session.get(correct_url, allow_redirects=False) as response:
|
async with session.get(correct_url, allow_redirects=False) as response:
|
||||||
return soupify(await response.read())
|
return soupify(await response.read())
|
||||||
|
@ -24,10 +24,13 @@ class KitIpdCrawlerSection(HttpCrawlerSection):
|
|||||||
if not target.startswith("https://"):
|
if not target.startswith("https://"):
|
||||||
self.invalid_value("target", target, "Should be a URL")
|
self.invalid_value("target", target, "Should be a URL")
|
||||||
|
|
||||||
|
if not target.endswith("/"):
|
||||||
|
target = target + "/"
|
||||||
|
|
||||||
return target
|
return target
|
||||||
|
|
||||||
def link_regex(self) -> Pattern[str]:
|
def link_regex(self) -> Pattern[str]:
|
||||||
regex = self.s.get("link_regex", r"^.*/[^/]*\.(?:pdf|zip|c|java)$")
|
regex = self.s.get("link_regex", r"^.*?[^/]+\.(pdf|zip|c|cpp|java)$")
|
||||||
return re.compile(regex)
|
return re.compile(regex)
|
||||||
|
|
||||||
|
|
||||||
@ -45,7 +48,7 @@ class KitIpdFolder:
|
|||||||
def explain(self) -> None:
|
def explain(self) -> None:
|
||||||
log.explain_topic(f"Folder {self.name!r}")
|
log.explain_topic(f"Folder {self.name!r}")
|
||||||
for file in self.files:
|
for file in self.files:
|
||||||
log.explain(f"File {file.name!r}")
|
log.explain(f"File {file.name!r} (href={file.url!r})")
|
||||||
|
|
||||||
def __hash__(self) -> int:
|
def __hash__(self) -> int:
|
||||||
return self.name.__hash__()
|
return self.name.__hash__()
|
||||||
@ -113,7 +116,7 @@ class KitIpdCrawler(HttpCrawler):
|
|||||||
else:
|
else:
|
||||||
file = self._extract_file(element)
|
file = self._extract_file(element)
|
||||||
items.add(file)
|
items.add(file)
|
||||||
log.explain_topic(f"Orphan file {file.name!r}")
|
log.explain_topic(f"Orphan file {file.name!r} (href={file.url!r})")
|
||||||
log.explain("Attributing it to root folder")
|
log.explain("Attributing it to root folder")
|
||||||
|
|
||||||
return items
|
return items
|
||||||
@ -161,4 +164,10 @@ class KitIpdCrawler(HttpCrawler):
|
|||||||
|
|
||||||
async def get_page(self) -> BeautifulSoup:
|
async def get_page(self) -> BeautifulSoup:
|
||||||
async with self.session.get(self._url) as request:
|
async with self.session.get(self._url) as request:
|
||||||
return soupify(await request.read())
|
# The web page for Algorithmen für Routenplanung contains some
|
||||||
|
# weird comments that beautifulsoup doesn't parse correctly. This
|
||||||
|
# hack enables those pages to be crawled, and should hopefully not
|
||||||
|
# cause issues on other pages.
|
||||||
|
content = (await request.read()).decode("utf-8")
|
||||||
|
content = re.sub(r"<!--.*?-->", "", content)
|
||||||
|
return soupify(content.encode("utf-8"))
|
||||||
|
@ -68,7 +68,7 @@ class Log:
|
|||||||
if self._download_progress.task_ids:
|
if self._download_progress.task_ids:
|
||||||
elements.append(self._download_progress)
|
elements.append(self._download_progress)
|
||||||
|
|
||||||
group = Group(*elements) # type: ignore
|
group = Group(*elements)
|
||||||
self._live.update(group)
|
self._live.update(group)
|
||||||
|
|
||||||
@contextmanager
|
@contextmanager
|
||||||
@ -197,7 +197,7 @@ directly or as a GitHub issue: https://github.com/Garmelon/PFERD/issues/new
|
|||||||
if self.output_explain:
|
if self.output_explain:
|
||||||
self.print(f" {escape(text)}")
|
self.print(f" {escape(text)}")
|
||||||
|
|
||||||
def status(self, style: str, action: str, text: str) -> None:
|
def status(self, style: str, action: str, text: str, suffix: str = "") -> None:
|
||||||
"""
|
"""
|
||||||
Print a status update while crawling. Allows markup in the "style"
|
Print a status update while crawling. Allows markup in the "style"
|
||||||
argument which will be applied to the "action" string.
|
argument which will be applied to the "action" string.
|
||||||
@ -205,7 +205,7 @@ directly or as a GitHub issue: https://github.com/Garmelon/PFERD/issues/new
|
|||||||
|
|
||||||
if self.output_status:
|
if self.output_status:
|
||||||
action = escape(f"{action:<{self.STATUS_WIDTH}}")
|
action = escape(f"{action:<{self.STATUS_WIDTH}}")
|
||||||
self.print(f"{style}{action}[/] {escape(text)}")
|
self.print(f"{style}{action}[/] {escape(text)} {suffix}")
|
||||||
|
|
||||||
def report(self, text: str) -> None:
|
def report(self, text: str) -> None:
|
||||||
"""
|
"""
|
||||||
|
@ -503,7 +503,7 @@ class OutputDirectory:
|
|||||||
try:
|
try:
|
||||||
self._prev_report = Report.load(self._report_path)
|
self._prev_report = Report.load(self._report_path)
|
||||||
log.explain("Loaded report successfully")
|
log.explain("Loaded report successfully")
|
||||||
except (OSError, json.JSONDecodeError, ReportLoadError) as e:
|
except (OSError, UnicodeDecodeError, json.JSONDecodeError, ReportLoadError) as e:
|
||||||
log.explain("Failed to load report")
|
log.explain("Failed to load report")
|
||||||
log.explain(str(e))
|
log.explain(str(e))
|
||||||
|
|
||||||
|
@ -100,10 +100,10 @@ class Report:
|
|||||||
@classmethod
|
@classmethod
|
||||||
def load(cls, path: Path) -> "Report":
|
def load(cls, path: Path) -> "Report":
|
||||||
"""
|
"""
|
||||||
May raise OSError, JsonDecodeError, ReportLoadError.
|
May raise OSError, UnicodeDecodeError, JsonDecodeError, ReportLoadError.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
with open(path) as f:
|
with open(path, encoding="utf-8") as f:
|
||||||
data = json.load(f)
|
data = json.load(f)
|
||||||
|
|
||||||
if not isinstance(data, dict):
|
if not isinstance(data, dict):
|
||||||
@ -148,7 +148,7 @@ class Report:
|
|||||||
"encountered_errors": self.encountered_errors,
|
"encountered_errors": self.encountered_errors,
|
||||||
}
|
}
|
||||||
|
|
||||||
with open(path, "w") as f:
|
with open(path, "w", encoding="utf-8") as f:
|
||||||
json.dump(data, f, indent=2, sort_keys=True)
|
json.dump(data, f, indent=2, sort_keys=True)
|
||||||
f.write("\n") # json.dump doesn't do this
|
f.write("\n") # json.dump doesn't do this
|
||||||
|
|
||||||
|
@ -1,2 +1,2 @@
|
|||||||
NAME = "PFERD"
|
NAME = "PFERD"
|
||||||
VERSION = "3.3.1"
|
VERSION = "3.4.2"
|
||||||
|
10
README.md
10
README.md
@ -17,7 +17,7 @@ Binaries for Linux, Windows and Mac can be downloaded directly from the
|
|||||||
|
|
||||||
### With pip
|
### With pip
|
||||||
|
|
||||||
Ensure you have at least Python 3.8 installed. Run the following command to
|
Ensure you have at least Python 3.9 installed. Run the following command to
|
||||||
install PFERD or upgrade it to the latest version:
|
install PFERD or upgrade it to the latest version:
|
||||||
|
|
||||||
```
|
```
|
||||||
@ -26,6 +26,14 @@ $ pip install --upgrade git+https://github.com/Garmelon/PFERD@latest
|
|||||||
|
|
||||||
The use of [venv](https://docs.python.org/3/library/venv.html) is recommended.
|
The use of [venv](https://docs.python.org/3/library/venv.html) is recommended.
|
||||||
|
|
||||||
|
### With package managers
|
||||||
|
|
||||||
|
Unofficial packages are available for:
|
||||||
|
- [AUR](https://aur.archlinux.org/packages/pferd)
|
||||||
|
- [nixpkgs](https://github.com/NixOS/nixpkgs/blob/master/pkgs/tools/misc/pferd/default.nix)
|
||||||
|
|
||||||
|
See also PFERD's [repology page](https://repology.org/project/pferd/versions).
|
||||||
|
|
||||||
## Basic usage
|
## Basic usage
|
||||||
|
|
||||||
PFERD can be run directly from the command line with no config file. Run `pferd
|
PFERD can be run directly from the command line with no config file. Run `pferd
|
||||||
|
Reference in New Issue
Block a user