Compare commits

...

58 Commits

Author SHA1 Message Date
Miguel Sozinho Ramalho
56526a9ac7 Merge pull request #365 from bellingcat/dev
Facebook reels fix
2025-10-23 10:40:43 +01:00
msramalho
3a22cc28c0 skip tiktok antibot test in CI 2025-10-23 10:17:14 +01:00
msramalho
dbb3dfa04f fixes wikipedia test 2025-10-23 10:04:44 +01:00
msramalho
01bdb35f5d version bump 2025-10-23 09:51:31 +01:00
msramalho
43cbc6ac56 generic extractor improvements 2025-10-23 09:51:14 +01:00
msramalho
9c7cab1ae2 dependencies update 2025-10-22 21:07:12 +01:00
msramalho
a9a0bae083 dependencies update 2025-10-22 18:11:36 +01:00
Miguel Sozinho Ramalho
97d133ce79 Merge pull request #357 from bellingcat/dev
small improvements on tiktok and verison bumps
2025-10-22 16:02:26 +01:00
msramalho
432ee3dcfd version bump 2025-10-22 15:50:50 +01:00
msramalho
794b4f6052 Merge branch 'dev' of https://github.com/bellingcat/auto-archiver into dev 2025-09-11 15:06:27 +01:00
msramalho
965d7d41dd dependency updates 2025-09-11 15:06:25 +01:00
Miguel Sozinho Ramalho
e73faa70cc Merge pull request #352 from mjgaughan/developer-documentation-updates
updating the style-checking code in the documentation
2025-08-11 10:42:53 +01:00
mgaughan
80beab9f23 ruff-fix -> ruff-clean; there is no ruff-fix in the Makefile. Maybe the command /should/ be ruff-fix to align with the underlying ruff command; for later discussion. This at least reconciles the documentation to the Makefile 2025-08-05 21:36:32 -04:00
Miguel Sozinho Ramalho
200cea4e12 Merge pull request #345 from mjgaughan/main
Correction of small documentation typos
2025-07-29 09:36:10 +01:00
mgaughan
1256fde159 updating location of .env.test.example in documentation 2025-07-23 13:04:48 -04:00
mgaughan
65e222e177 fixing typo in documentation pytest -> poetry 2025-07-22 17:20:59 -04:00
mgaughan
f2eb9ef784 correcting to double-dash in the poetry install documentation 2025-07-21 17:55:48 -04:00
msramalho
2081c16555 embed retry into timestamping 2025-07-10 14:49:53 +01:00
msramalho
d3efd7121c avoid empty metadata comments 2025-07-06 14:05:17 +01:00
msramalho
9d3cd5774b an improved approach for #295 2025-07-06 14:04:01 +01:00
Miguel Sozinho Ramalho
80d61e8b85 Merge pull request #341 from bellingcat/dev
Address several small bugs, includes tiktok photos extraction, and data-saving for proxy usage in generic_extractor.
2025-07-05 20:28:00 +01:00
msramalho
d36cdbfa87 fixing pypaperclip see issue #339 2025-07-05 19:07:23 +01:00
msramalho
c1506ee1cf some wayback errors are expected and should be warnings 2025-07-05 18:31:39 +01:00
msramalho
3a34a49822 adds antibot tiktok logic for photos closes #295 2025-07-05 18:31:12 +01:00
msramalho
37c6d97275 new auth wall check logic and escaped CSS selector in selenium 2025-07-05 18:30:31 +01:00
msramalho
7234eda85f expands Sheets API retries for really large spreadsheets 2025-07-05 18:29:33 +01:00
msramalho
a8c1ef3912 generic_extractor config to use proxy only when needed to avoid overzealousness 2025-07-05 16:54:58 +01:00
msramalho
52ed8196a5 updates dependencies 2025-07-05 16:03:47 +01:00
msramalho
2051e8e491 adds further exponential backoff for Sheets API worksheet enumeration 2025-07-05 16:02:07 +01:00
msramalho
21255db86a stops using service that is not up for timestamping 2025-07-05 16:00:46 +01:00
msramalho
eae0da08b3 fix issue with two runs of anitbot extractor 2025-07-05 16:00:03 +01:00
msramalho
0d1447117c updates docs to reflect new general approach extractor 2025-07-05 15:56:13 +01:00
Miguel Sozinho Ramalho
0f56a5aae5 Merge pull request #331 from bellingcat/dev
1.1.1 multiple small fixes, and new logging strategy
2025-06-30 02:36:25 +01:00
msramalho
649412053e exclude non-ready code 2025-06-30 02:27:21 +01:00
msramalho
c2c9718f73 make python api tests work on gh when no env is set 2025-06-30 02:20:51 +01:00
msramalho
30ea8a0ba4 bumps dependencies 2025-06-30 02:20:09 +01:00
msramalho
73c8dc583f closes #333 2025-06-30 01:52:22 +01:00
msramalho
b2648fa3cd follow docs advice on exponential backoff of SheetsAPI 2025-06-30 01:47:12 +01:00
msramalho
4ad71b3589 adds retry to worksheet read for slow worksheets 2025-06-30 01:42:34 +01:00
msramalho
7c9475cde2 allow for human readable console logs, but defaults to JSON on file logs. 2025-06-30 00:53:10 +01:00
msramalho
afd9090a4c concludes logging standardization refactor 2025-06-26 17:20:04 +01:00
msramalho
ad29cb4447 adds post_data to metadata for instagram 2025-06-26 15:48:10 +01:00
msramalho
ce4d7ac649 WIP refactor logging 2025-06-21 15:54:51 +01:00
msramalho
ade7feb5a0 version bump 2025-06-18 17:38:17 +01:00
msramalho
12b457706b closes #166 adds story URL feature to telethon extractor 2025-06-18 17:37:44 +01:00
msramalho
592dc30415 closes #330 2025-06-18 16:40:55 +01:00
msramalho
4a36e6f6b0 fix tests 2025-06-18 13:50:21 +01:00
msramalho
d46eeee9b6 docs improved 2025-06-18 13:35:51 +01:00
msramalho
302e6f4258 logs improved 2025-06-18 13:35:43 +01:00
Miguel Sozinho Ramalho
e803c5d0e3 Merge branch 'main' into dev 2025-06-18 13:35:21 +01:00
msramalho
e1d0314a9e Merge branch 'dev' of https://github.com/bellingcat/auto-archiver into dev 2025-06-18 13:26:48 +01:00
Miguel Sozinho Ramalho
5d5119e053 Merge pull request #329 from bellingcat/dev
installs ffmpeg in readthedocs
2025-06-18 00:31:09 +01:00
msramalho
d6c90d87f1 installs ffmpeg in readthedocs 2025-06-18 00:30:45 +01:00
msramalho
212bf67ab1 installs ffmpeg in readthedocs 2025-06-18 00:29:36 +01:00
Miguel Sozinho Ramalho
6abe2edb13 Merge pull request #328 from bellingcat/dev
fix to configuration editor npm versions
2025-06-18 00:22:39 +01:00
msramalho
03c0cf09ae fix issue with grid in scripts/config_editor @mui lib upgrade 2025-06-18 00:20:31 +01:00
Miguel Sozinho Ramalho
0db77c7e68 Merge pull request #326 from bellingcat/dependabot/npm_and_yarn/scripts/settings/actions-27795ad889
Bump @types/react from 19.1.7 to 19.1.8 in /scripts/settings in the actions group across 1 directory
2025-06-18 00:12:51 +01:00
dependabot[bot]
cd6607943d Bump @types/react
Bumps the actions group with 1 update in the /scripts/settings directory: [@types/react](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/react).


Updates `@types/react` from 19.1.7 to 19.1.8
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/react)

---
updated-dependencies:
- dependency-name: "@types/react"
  dependency-version: 19.1.8
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-06-17 22:58:23 +00:00
86 changed files with 2079 additions and 1608 deletions

View File

@@ -47,4 +47,4 @@ jobs:
- name: Run Download Tests - name: Run Download Tests
run: poetry run pytest -ra -v -x -m "download" run: poetry run pytest -ra -v -x -m "download"
env: env:
TWITTER_BEARER_TOKEN: ${{ secrets.TWITTER_BEARER_TOKEN }} TWITTER_BEARER_TOKEN: ${{ secrets.TWITTER_BEARER_TOKEN || '' }}

View File

@@ -7,6 +7,8 @@ version: 2
build: build:
os: ubuntu-22.04 os: ubuntu-22.04
apt_packages:
- ffmpeg
tools: tools:
python: "3.10" python: "3.10"
nodejs: "22" nodejs: "22"

View File

@@ -21,7 +21,7 @@ This allows you to run the auto-archiver without the `poetry run` prefix.
### Optional Development Packages ### Optional Development Packages
Install development packages (used for unit tests etc.) using: Install development packages (used for unit tests etc.) using:
`poetry install -with dev` `poetry install --with dev`
```{toctree} ```{toctree}
@@ -33,4 +33,4 @@ docs
release release
settings_page settings_page
style_guide style_guide
``` ```

View File

@@ -50,7 +50,7 @@ Note not all warnings can be fixed automatically.
Most fixes are safe, but some non-standard practices such as dynamic loading are not picked up by linters. Ensure you check any modifications by this before committing them. Most fixes are safe, but some non-standard practices such as dynamic loading are not picked up by linters. Ensure you check any modifications by this before committing them.
```shell ```shell
make ruff-fix make ruff-clean
``` ```
**Changing Configurations ⚙️** **Changing Configurations ⚙️**
@@ -67,4 +67,4 @@ One example is to extend the selected rules for linting the `pyproject.toml` fil
extend-select = ["B"] extend-select = ["B"]
``` ```
Then re-run the `make ruff-check` command to see the new rules in action. Then re-run the `make ruff-check` command to see the new rules in action.

View File

@@ -8,7 +8,7 @@
## Running Tests ## Running Tests
1. Make sure you've installed the dev dependencies with `pytest install --with dev` 1. Make sure you've installed the dev dependencies with `poetry install --with dev`
2. Tests can be run as follows: 2. Tests can be run as follows:
```{code} bash ```{code} bash
#### Command prefix of 'poetry run' removed here for simplicity #### Command prefix of 'poetry run' removed here for simplicity
@@ -26,7 +26,7 @@ pytest -ra -v tests/test_file.py
pytest -ra -v tests/test_file.py::test_function_name pytest -ra -v tests/test_file.py::test_function_name
``` ```
3. Some tests require environment variables to be set. You can use the example `.env.test.example` file as a template. Copy it to `.env.test` and fill in the required values. This file will be loaded automatically by `pytest`. 3. Some tests require environment variables to be set. You can use the example `tests/.env.test.example` file as a template. Copy it to `tests/.env.test` and fill in the required values. This file will be loaded automatically by `pytest`.
```{code} bash ```{code} bash
cp .env.test.example .env.test cp tests/.env.test.example tests/.env.test
``` ```

View File

@@ -24,7 +24,7 @@ This will disable all logs from Auto Archiver, but it does not disable logs for
#### Logging Level #### Logging Level
There are 7 logging levels in total, with 5 of them used in this tool. They are: `DEBUG`, `INFO`, `SUCCESS`, `WARNING` and `ERROR`. There are 7 logging levels in total, with 5 of them used in this tool. They are: `DEBUG`, `INFO`, `SUCCESS`, `WARNING` and `ERROR`. If you select a level, only that and higher (more serious) levels will be included. `DEBUG` is the most verbose, while `ERROR` is the least verbose.
Change the warning level by setting the value in your orchestration config file: Change the warning level by setting the value in your orchestration config file:
@@ -42,6 +42,20 @@ For normal usage, it is recommended to use the `INFO` level, or if you prefer qu
```{note} To learn about all logging levels, see the [loguru documentation](https://loguru.readthedocs.io/en/stable/api/logger.html) ```{note} To learn about all logging levels, see the [loguru documentation](https://loguru.readthedocs.io/en/stable/api/logger.html)
``` ```
### Logging Format
By default, the console logs are formatted in a human-readable way and the file logs are formatted in JSON. This is new from version 1.1.1. If you want to change the format of the console logs to JSON too you can set the `format:` option in your logging settings.
```{code} yaml
:caption: orchestration.yaml
logging:
format: json
```
When the Auto Archiver is writing logs it will include context about specific tasks, so if you are archiving a URL from a Google Sheet, both the URL (and a unique `trace_id` for that URL's archiving attempt) and the Spreadsheet name and row will be included in the logs. This is useful for debugging and understanding what the Auto Archiver is doing.
Using JSON allows you to easily parse the logs and extract specific information, tools like [`jq`](https://jqlang.org/) can be used to filter and search through the logs.
### Logging to a file ### Logging to a file
As default, auto-archiver will log to the console. But if you wish to store your logs for future reference, or you are running the auto-archiver from within code a implementation, then you may wish to enable file logging. This can be done by setting the `file:` config value in the logging settings. As default, auto-archiver will log to the console. But if you wish to store your logs for future reference, or you are running the auto-archiver from within code a implementation, then you may wish to enable file logging. This can be done by setting the `file:` config value in the logging settings.
@@ -84,6 +98,7 @@ The below example logs only `DEBUG` logs to the console and to the file `/my/fil
logging: logging:
level: DEBUG level: DEBUG
format: json
file: /my/file.log file: /my/file.log
rotation: 1 week rotation: 1 week
``` ```

View File

@@ -4,8 +4,9 @@ Extractor modules are used to extract the content of a given URL. Typically, one
Extractors that are able to extract content from a wide range of websites include: Extractors that are able to extract content from a wide range of websites include:
1. Generic Extractor: parses videos and images on sites using the powerful yt-dlp library. 1. Generic Extractor: parses videos and images on sites using the powerful yt-dlp library.
2. Wayback Machine Extractor: sends pages to the Wayback machine for archiving, and stores the link. 2. Antibot Extractor: uses a headless browser to bypass bot detection and extract content.
3. WACZ Extractor: runs a web browser to 'browse' the URL and save a copy of the page in WACZ format. 3. WACZ Extractor: runs a web browser to 'browse' the URL and save a copy of the page in WACZ format.
4. Wayback Machine Extractor: sends pages to the Wayback machine for archiving, and stores the archived link.
```{include} autogen/extractor.md ```{include} autogen/extractor.md
``` ```

2166
poetry.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -4,7 +4,7 @@ build-backend = "poetry.core.masonry.api"
[project] [project]
name = "auto-archiver" name = "auto-archiver"
version = "1.1.0" version = "1.1.6"
description = "Automatically archive links to videos, images, and social media content from Google Sheets (and more)." description = "Automatically archive links to videos, images, and social media content from Google Sheets (and more)."
requires-python = ">=3.10,<3.13" requires-python = ">=3.10,<3.13"
@@ -50,14 +50,15 @@ dependencies = [
"retrying (>=0.0.0)", "retrying (>=0.0.0)",
"rich-argparse (>=1.6.0,<2.0.0)", "rich-argparse (>=1.6.0,<2.0.0)",
"ruamel-yaml (>=0.18.10,<0.19.0)", "ruamel-yaml (>=0.18.10,<0.19.0)",
"rfc3161-client (>=1.0.1,<2.0.0)", "rfc3161-client (>=1.0.5)",
"cryptography (>44.0.1,<45.0.0)", "cryptography (>=46.0.3)",
"opentimestamps (>=0.4.5,<0.5.0)", "opentimestamps (>=0.4.5,<0.5.0)",
"bgutil-ytdlp-pot-provider (>=1.0.0)", "bgutil-ytdlp-pot-provider (>=1.0.0)",
"yt-dlp[curl-cffi,default] (>=2025.5.22,<2026.0.0)", "yt-dlp[curl-cffi,default] (>=2025.5.22,<2026.0.0)",
"secretstorage (>=3.3.3,<4.0.0)", "secretstorage (>=3.3.3,<4.0.0)",
"seleniumbase (>=4.36.4,<5.0.0)", "seleniumbase (>=4.36.4,<5.0.0)",
"pyautogui (>=0.9.54,<0.10.0)", "pyautogui (>=0.9.54,<0.10.0)",
"pyperclip (==1.8.2)",
] ]
[tool.poetry.group.dev.dependencies] [tool.poetry.group.dev.dependencies]

View File

@@ -13,7 +13,7 @@
"@emotion/react": "latest", "@emotion/react": "latest",
"@emotion/styled": "latest", "@emotion/styled": "latest",
"@mui/icons-material": "^7.1.1", "@mui/icons-material": "^7.1.1",
"@mui/material": "latest", "@mui/material": "^7.1.1",
"react": "19.1.0", "react": "19.1.0",
"react-dom": "19.1.0", "react-dom": "19.1.0",
"react-markdown": "^10.0.0", "react-markdown": "^10.0.0",
@@ -1244,9 +1244,9 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/@rollup/rollup-android-arm-eabi": { "node_modules/@rollup/rollup-android-arm-eabi": {
"version": "4.42.0", "version": "4.43.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.42.0.tgz", "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.43.0.tgz",
"integrity": "sha512-gldmAyS9hpj+H6LpRNlcjQWbuKUtb94lodB9uCz71Jm+7BxK1VIOo7y62tZZwxhA7j1ylv/yQz080L5WkS+LoQ==", "integrity": "sha512-Krjy9awJl6rKbruhQDgivNbD1WuLb8xAclM4IR4cN5pHGAs2oIMMQJEiC3IC/9TZJ+QZkmZhlMO/6MBGxPidpw==",
"cpu": [ "cpu": [
"arm" "arm"
], ],
@@ -1258,9 +1258,9 @@
] ]
}, },
"node_modules/@rollup/rollup-android-arm64": { "node_modules/@rollup/rollup-android-arm64": {
"version": "4.42.0", "version": "4.43.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.42.0.tgz", "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.43.0.tgz",
"integrity": "sha512-bpRipfTgmGFdCZDFLRvIkSNO1/3RGS74aWkJJTFJBH7h3MRV4UijkaEUeOMbi9wxtxYmtAbVcnMtHTPBhLEkaw==", "integrity": "sha512-ss4YJwRt5I63454Rpj+mXCXicakdFmKnUNxr1dLK+5rv5FJgAxnN7s31a5VchRYxCFWdmnDWKd0wbAdTr0J5EA==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
@@ -1272,9 +1272,9 @@
] ]
}, },
"node_modules/@rollup/rollup-darwin-arm64": { "node_modules/@rollup/rollup-darwin-arm64": {
"version": "4.42.0", "version": "4.43.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.42.0.tgz", "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.43.0.tgz",
"integrity": "sha512-JxHtA081izPBVCHLKnl6GEA0w3920mlJPLh89NojpU2GsBSB6ypu4erFg/Wx1qbpUbepn0jY4dVWMGZM8gplgA==", "integrity": "sha512-eKoL8ykZ7zz8MjgBenEF2OoTNFAPFz1/lyJ5UmmFSz5jW+7XbH1+MAgCVHy72aG59rbuQLcJeiMrP8qP5d/N0A==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
@@ -1286,9 +1286,9 @@
] ]
}, },
"node_modules/@rollup/rollup-darwin-x64": { "node_modules/@rollup/rollup-darwin-x64": {
"version": "4.42.0", "version": "4.43.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.42.0.tgz", "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.43.0.tgz",
"integrity": "sha512-rv5UZaWVIJTDMyQ3dCEK+m0SAn6G7H3PRc2AZmExvbDvtaDc+qXkei0knQWcI3+c9tEs7iL/4I4pTQoPbNL2SA==", "integrity": "sha512-SYwXJgaBYW33Wi/q4ubN+ldWC4DzQY62S4Ll2dgfr/dbPoF50dlQwEaEHSKrQdSjC6oIe1WgzosoaNoHCdNuMg==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
@@ -1300,9 +1300,9 @@
] ]
}, },
"node_modules/@rollup/rollup-freebsd-arm64": { "node_modules/@rollup/rollup-freebsd-arm64": {
"version": "4.42.0", "version": "4.43.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.42.0.tgz", "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.43.0.tgz",
"integrity": "sha512-fJcN4uSGPWdpVmvLuMtALUFwCHgb2XiQjuECkHT3lWLZhSQ3MBQ9pq+WoWeJq2PrNxr9rPM1Qx+IjyGj8/c6zQ==", "integrity": "sha512-SV+U5sSo0yujrjzBF7/YidieK2iF6E7MdF6EbYxNz94lA+R0wKl3SiixGyG/9Klab6uNBIqsN7j4Y/Fya7wAjQ==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
@@ -1314,9 +1314,9 @@
] ]
}, },
"node_modules/@rollup/rollup-freebsd-x64": { "node_modules/@rollup/rollup-freebsd-x64": {
"version": "4.42.0", "version": "4.43.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.42.0.tgz", "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.43.0.tgz",
"integrity": "sha512-CziHfyzpp8hJpCVE/ZdTizw58gr+m7Y2Xq5VOuCSrZR++th2xWAz4Nqk52MoIIrV3JHtVBhbBsJcAxs6NammOQ==", "integrity": "sha512-J7uCsiV13L/VOeHJBo5SjasKiGxJ0g+nQTrBkAsmQBIdil3KhPnSE9GnRon4ejX1XDdsmK/l30IYLiAaQEO0Cg==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
@@ -1328,9 +1328,9 @@
] ]
}, },
"node_modules/@rollup/rollup-linux-arm-gnueabihf": { "node_modules/@rollup/rollup-linux-arm-gnueabihf": {
"version": "4.42.0", "version": "4.43.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.42.0.tgz", "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.43.0.tgz",
"integrity": "sha512-UsQD5fyLWm2Fe5CDM7VPYAo+UC7+2Px4Y+N3AcPh/LdZu23YcuGPegQly++XEVaC8XUTFVPscl5y5Cl1twEI4A==", "integrity": "sha512-gTJ/JnnjCMc15uwB10TTATBEhK9meBIY+gXP4s0sHD1zHOaIh4Dmy1X9wup18IiY9tTNk5gJc4yx9ctj/fjrIw==",
"cpu": [ "cpu": [
"arm" "arm"
], ],
@@ -1342,9 +1342,9 @@
] ]
}, },
"node_modules/@rollup/rollup-linux-arm-musleabihf": { "node_modules/@rollup/rollup-linux-arm-musleabihf": {
"version": "4.42.0", "version": "4.43.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.42.0.tgz", "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.43.0.tgz",
"integrity": "sha512-/i8NIrlgc/+4n1lnoWl1zgH7Uo0XK5xK3EDqVTf38KvyYgCU/Rm04+o1VvvzJZnVS5/cWSd07owkzcVasgfIkQ==", "integrity": "sha512-ZJ3gZynL1LDSIvRfz0qXtTNs56n5DI2Mq+WACWZ7yGHFUEirHBRt7fyIk0NsCKhmRhn7WAcjgSkSVVxKlPNFFw==",
"cpu": [ "cpu": [
"arm" "arm"
], ],
@@ -1356,9 +1356,9 @@
] ]
}, },
"node_modules/@rollup/rollup-linux-arm64-gnu": { "node_modules/@rollup/rollup-linux-arm64-gnu": {
"version": "4.42.0", "version": "4.43.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.42.0.tgz", "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.43.0.tgz",
"integrity": "sha512-eoujJFOvoIBjZEi9hJnXAbWg+Vo1Ov8n/0IKZZcPZ7JhBzxh2A+2NFyeMZIRkY9iwBvSjloKgcvnjTbGKHE44Q==", "integrity": "sha512-8FnkipasmOOSSlfucGYEu58U8cxEdhziKjPD2FIa0ONVMxvl/hmONtX/7y4vGjdUhjcTHlKlDhw3H9t98fPvyA==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
@@ -1370,9 +1370,9 @@
] ]
}, },
"node_modules/@rollup/rollup-linux-arm64-musl": { "node_modules/@rollup/rollup-linux-arm64-musl": {
"version": "4.42.0", "version": "4.43.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.42.0.tgz", "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.43.0.tgz",
"integrity": "sha512-/3NrcOWFSR7RQUQIuZQChLND36aTU9IYE4j+TB40VU78S+RA0IiqHR30oSh6P1S9f9/wVOenHQnacs/Byb824g==", "integrity": "sha512-KPPyAdlcIZ6S9C3S2cndXDkV0Bb1OSMsX0Eelr2Bay4EsF9yi9u9uzc9RniK3mcUGCLhWY9oLr6er80P5DE6XA==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
@@ -1384,9 +1384,9 @@
] ]
}, },
"node_modules/@rollup/rollup-linux-loongarch64-gnu": { "node_modules/@rollup/rollup-linux-loongarch64-gnu": {
"version": "4.42.0", "version": "4.43.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loongarch64-gnu/-/rollup-linux-loongarch64-gnu-4.42.0.tgz", "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loongarch64-gnu/-/rollup-linux-loongarch64-gnu-4.43.0.tgz",
"integrity": "sha512-O8AplvIeavK5ABmZlKBq9/STdZlnQo7Sle0LLhVA7QT+CiGpNVe197/t8Aph9bhJqbDVGCHpY2i7QyfEDDStDg==", "integrity": "sha512-HPGDIH0/ZzAZjvtlXj6g+KDQ9ZMHfSP553za7o2Odegb/BEfwJcR0Sw0RLNpQ9nC6Gy8s+3mSS9xjZ0n3rhcYg==",
"cpu": [ "cpu": [
"loong64" "loong64"
], ],
@@ -1398,9 +1398,9 @@
] ]
}, },
"node_modules/@rollup/rollup-linux-powerpc64le-gnu": { "node_modules/@rollup/rollup-linux-powerpc64le-gnu": {
"version": "4.42.0", "version": "4.43.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-powerpc64le-gnu/-/rollup-linux-powerpc64le-gnu-4.42.0.tgz", "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-powerpc64le-gnu/-/rollup-linux-powerpc64le-gnu-4.43.0.tgz",
"integrity": "sha512-6Qb66tbKVN7VyQrekhEzbHRxXXFFD8QKiFAwX5v9Xt6FiJ3BnCVBuyBxa2fkFGqxOCSGGYNejxd8ht+q5SnmtA==", "integrity": "sha512-gEmwbOws4U4GLAJDhhtSPWPXUzDfMRedT3hFMyRAvM9Mrnj+dJIFIeL7otsv2WF3D7GrV0GIewW0y28dOYWkmw==",
"cpu": [ "cpu": [
"ppc64" "ppc64"
], ],
@@ -1412,9 +1412,9 @@
] ]
}, },
"node_modules/@rollup/rollup-linux-riscv64-gnu": { "node_modules/@rollup/rollup-linux-riscv64-gnu": {
"version": "4.42.0", "version": "4.43.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.42.0.tgz", "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.43.0.tgz",
"integrity": "sha512-KQETDSEBamQFvg/d8jajtRwLNBlGc3aKpaGiP/LvEbnmVUKlFta1vqJqTrvPtsYsfbE/DLg5CC9zyXRX3fnBiA==", "integrity": "sha512-XXKvo2e+wFtXZF/9xoWohHg+MuRnvO29TI5Hqe9xwN5uN8NKUYy7tXUG3EZAlfchufNCTHNGjEx7uN78KsBo0g==",
"cpu": [ "cpu": [
"riscv64" "riscv64"
], ],
@@ -1426,9 +1426,9 @@
] ]
}, },
"node_modules/@rollup/rollup-linux-riscv64-musl": { "node_modules/@rollup/rollup-linux-riscv64-musl": {
"version": "4.42.0", "version": "4.43.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.42.0.tgz", "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.43.0.tgz",
"integrity": "sha512-qMvnyjcU37sCo/tuC+JqeDKSuukGAd+pVlRl/oyDbkvPJ3awk6G6ua7tyum02O3lI+fio+eM5wsVd66X0jQtxw==", "integrity": "sha512-ruf3hPWhjw6uDFsOAzmbNIvlXFXlBQ4nk57Sec8E8rUxs/AI4HD6xmiiasOOx/3QxS2f5eQMKTAwk7KHwpzr/Q==",
"cpu": [ "cpu": [
"riscv64" "riscv64"
], ],
@@ -1440,9 +1440,9 @@
] ]
}, },
"node_modules/@rollup/rollup-linux-s390x-gnu": { "node_modules/@rollup/rollup-linux-s390x-gnu": {
"version": "4.42.0", "version": "4.43.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.42.0.tgz", "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.43.0.tgz",
"integrity": "sha512-I2Y1ZUgTgU2RLddUHXTIgyrdOwljjkmcZ/VilvaEumtS3Fkuhbw4p4hgHc39Ypwvo2o7sBFNl2MquNvGCa55Iw==", "integrity": "sha512-QmNIAqDiEMEvFV15rsSnjoSmO0+eJLoKRD9EAa9rrYNwO/XRCtOGM3A5A0X+wmG+XRrw9Fxdsw+LnyYiZWWcVw==",
"cpu": [ "cpu": [
"s390x" "s390x"
], ],
@@ -1454,9 +1454,9 @@
] ]
}, },
"node_modules/@rollup/rollup-linux-x64-gnu": { "node_modules/@rollup/rollup-linux-x64-gnu": {
"version": "4.42.0", "version": "4.43.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.42.0.tgz", "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.43.0.tgz",
"integrity": "sha512-Gfm6cV6mj3hCUY8TqWa63DB8Mx3NADoFwiJrMpoZ1uESbK8FQV3LXkhfry+8bOniq9pqY1OdsjFWNsSbfjPugw==", "integrity": "sha512-jAHr/S0iiBtFyzjhOkAics/2SrXE092qyqEg96e90L3t9Op8OTzS6+IX0Fy5wCt2+KqeHAkti+eitV0wvblEoQ==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
@@ -1468,9 +1468,9 @@
] ]
}, },
"node_modules/@rollup/rollup-linux-x64-musl": { "node_modules/@rollup/rollup-linux-x64-musl": {
"version": "4.42.0", "version": "4.43.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.42.0.tgz", "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.43.0.tgz",
"integrity": "sha512-g86PF8YZ9GRqkdi0VoGlcDUb4rYtQKyTD1IVtxxN4Hpe7YqLBShA7oHMKU6oKTCi3uxwW4VkIGnOaH/El8de3w==", "integrity": "sha512-3yATWgdeXyuHtBhrLt98w+5fKurdqvs8B53LaoKD7P7H7FKOONLsBVMNl9ghPQZQuYcceV5CDyPfyfGpMWD9mQ==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
@@ -1482,9 +1482,9 @@
] ]
}, },
"node_modules/@rollup/rollup-win32-arm64-msvc": { "node_modules/@rollup/rollup-win32-arm64-msvc": {
"version": "4.42.0", "version": "4.43.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.42.0.tgz", "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.43.0.tgz",
"integrity": "sha512-+axkdyDGSp6hjyzQ5m1pgcvQScfHnMCcsXkx8pTgy/6qBmWVhtRVlgxjWwDp67wEXXUr0x+vD6tp5W4x6V7u1A==", "integrity": "sha512-wVzXp2qDSCOpcBCT5WRWLmpJRIzv23valvcTwMHEobkjippNf+C3ys/+wf07poPkeNix0paTNemB2XrHr2TnGw==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
@@ -1496,9 +1496,9 @@
] ]
}, },
"node_modules/@rollup/rollup-win32-ia32-msvc": { "node_modules/@rollup/rollup-win32-ia32-msvc": {
"version": "4.42.0", "version": "4.43.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.42.0.tgz", "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.43.0.tgz",
"integrity": "sha512-F+5J9pelstXKwRSDq92J0TEBXn2nfUrQGg+HK1+Tk7VOL09e0gBqUHugZv7SW4MGrYj41oNCUe3IKCDGVlis2g==", "integrity": "sha512-fYCTEyzf8d+7diCw8b+asvWDCLMjsCEA8alvtAutqJOJp/wL5hs1rWSqJ1vkjgW0L2NB4bsYJrpKkiIPRR9dvw==",
"cpu": [ "cpu": [
"ia32" "ia32"
], ],
@@ -1510,9 +1510,9 @@
] ]
}, },
"node_modules/@rollup/rollup-win32-x64-msvc": { "node_modules/@rollup/rollup-win32-x64-msvc": {
"version": "4.42.0", "version": "4.43.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.42.0.tgz", "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.43.0.tgz",
"integrity": "sha512-LpHiJRwkaVz/LqjHjK8LCi8osq7elmpwujwbXKNW88bM8eeGxavJIKKjkjpMHAh/2xfnrt1ZSnhTv41WYUHYmA==", "integrity": "sha512-SnGhLiE5rlK0ofq8kzuDkM0g7FN1s5VYY+YSMTibP7CqShxCQvqtNxTARS4xX4PFJfHjG0ZQYX9iGzI3FQh5Aw==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
@@ -1629,9 +1629,9 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/@types/react": { "node_modules/@types/react": {
"version": "19.1.7", "version": "19.1.8",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.1.7.tgz", "resolved": "https://registry.npmjs.org/@types/react/-/react-19.1.8.tgz",
"integrity": "sha512-BnsPLV43ddr05N71gaGzyZ5hzkCmGwhMvYc8zmvI8Ci1bRkkDSzDDVfAXfN2tk748OwI7ediiPX6PfT9p0QGVg==", "integrity": "sha512-AwAfQ2Wa5bCx9WP8nZL2uMZWod7J7/JSplxbTmBQ5ms6QpqNYm672H0Vu9ZVKVngQ+ii4R/byguVEUZQyeg44g==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"csstype": "^3.0.2" "csstype": "^3.0.2"
@@ -1770,9 +1770,9 @@
} }
}, },
"node_modules/caniuse-lite": { "node_modules/caniuse-lite": {
"version": "1.0.30001721", "version": "1.0.30001723",
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001721.tgz", "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001723.tgz",
"integrity": "sha512-cOuvmUVtKrtEaoKiO0rSc29jcjwMwX5tOHDy4MgVFEWiUXj4uBMJkwI8MDySkgXidpMiHUcviogAvFi4pA2hDQ==", "integrity": "sha512-1R/elMjtehrFejxwmexeXAtae5UO9iSyFn6G/I806CYC/BLyyBk1EPhrKBkWhy6wM6Xnm47dSJQec+tLJ39WHw==",
"dev": true, "dev": true,
"funding": [ "funding": [
{ {
@@ -1914,9 +1914,9 @@
} }
}, },
"node_modules/decode-named-character-reference": { "node_modules/decode-named-character-reference": {
"version": "1.1.0", "version": "1.2.0",
"resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.1.0.tgz", "resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.2.0.tgz",
"integrity": "sha512-Wy+JTSbFThEOXQIR2L6mxJvEs+veIzpmqD7ynWxMXGpnk3smkHQOp6forLdHsKpAMW9iJpaBBIxz285t1n1C3w==", "integrity": "sha512-c6fcElNV6ShtZXmsgNgFFV5tVX2PaV4g+MOAkb8eXHvn6sryJBrZa9r0zV6+dtTyoCKxtDy5tyQ5ZwQuidtd+Q==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"character-entities": "^2.0.0" "character-entities": "^2.0.0"
@@ -1959,9 +1959,9 @@
} }
}, },
"node_modules/electron-to-chromium": { "node_modules/electron-to-chromium": {
"version": "1.5.166", "version": "1.5.169",
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.166.tgz", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.169.tgz",
"integrity": "sha512-QPWqHL0BglzPYyJJ1zSSmwFFL6MFXhbACOCcsCdUMCkzPdS9/OIBVxg516X/Ado2qwAq8k0nJJ7phQPCqiaFAw==", "integrity": "sha512-q7SQx6mkLy0GTJK9K9OiWeaBMV4XQtBSdf6MJUzDB/H/5tFXfIiX38Lci1Kl6SsgiEhz1SQI1ejEOU5asWEhwQ==",
"dev": true, "dev": true,
"license": "ISC" "license": "ISC"
}, },
@@ -3144,9 +3144,9 @@
} }
}, },
"node_modules/postcss": { "node_modules/postcss": {
"version": "8.5.4", "version": "8.5.6",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.4.tgz", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz",
"integrity": "sha512-QSa9EBe+uwlGTFmHsPKokv3B/oEMQZxfqW0QqNCyhpa6mB1afzulwn8hihglqAb2pOw+BJgNlmXQ8la2VeHB7w==", "integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==",
"dev": true, "dev": true,
"funding": [ "funding": [
{ {
@@ -3342,9 +3342,9 @@
} }
}, },
"node_modules/rollup": { "node_modules/rollup": {
"version": "4.42.0", "version": "4.43.0",
"resolved": "https://registry.npmjs.org/rollup/-/rollup-4.42.0.tgz", "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.43.0.tgz",
"integrity": "sha512-LW+Vse3BJPyGJGAJt1j8pWDKPd73QM8cRXYK1IxOBgL2AGLu7Xd2YOW0M2sLUBCkF5MshXXtMApyEAEzMVMsnw==", "integrity": "sha512-wdN2Kd3Twh8MAEOEJZsuxuLKCsBEo4PVNLK6tQWAn10VhsVewQLzcucMgLolRlhFybGxfclbPeEYBaP6RvUFGg==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
@@ -3358,26 +3358,26 @@
"npm": ">=8.0.0" "npm": ">=8.0.0"
}, },
"optionalDependencies": { "optionalDependencies": {
"@rollup/rollup-android-arm-eabi": "4.42.0", "@rollup/rollup-android-arm-eabi": "4.43.0",
"@rollup/rollup-android-arm64": "4.42.0", "@rollup/rollup-android-arm64": "4.43.0",
"@rollup/rollup-darwin-arm64": "4.42.0", "@rollup/rollup-darwin-arm64": "4.43.0",
"@rollup/rollup-darwin-x64": "4.42.0", "@rollup/rollup-darwin-x64": "4.43.0",
"@rollup/rollup-freebsd-arm64": "4.42.0", "@rollup/rollup-freebsd-arm64": "4.43.0",
"@rollup/rollup-freebsd-x64": "4.42.0", "@rollup/rollup-freebsd-x64": "4.43.0",
"@rollup/rollup-linux-arm-gnueabihf": "4.42.0", "@rollup/rollup-linux-arm-gnueabihf": "4.43.0",
"@rollup/rollup-linux-arm-musleabihf": "4.42.0", "@rollup/rollup-linux-arm-musleabihf": "4.43.0",
"@rollup/rollup-linux-arm64-gnu": "4.42.0", "@rollup/rollup-linux-arm64-gnu": "4.43.0",
"@rollup/rollup-linux-arm64-musl": "4.42.0", "@rollup/rollup-linux-arm64-musl": "4.43.0",
"@rollup/rollup-linux-loongarch64-gnu": "4.42.0", "@rollup/rollup-linux-loongarch64-gnu": "4.43.0",
"@rollup/rollup-linux-powerpc64le-gnu": "4.42.0", "@rollup/rollup-linux-powerpc64le-gnu": "4.43.0",
"@rollup/rollup-linux-riscv64-gnu": "4.42.0", "@rollup/rollup-linux-riscv64-gnu": "4.43.0",
"@rollup/rollup-linux-riscv64-musl": "4.42.0", "@rollup/rollup-linux-riscv64-musl": "4.43.0",
"@rollup/rollup-linux-s390x-gnu": "4.42.0", "@rollup/rollup-linux-s390x-gnu": "4.43.0",
"@rollup/rollup-linux-x64-gnu": "4.42.0", "@rollup/rollup-linux-x64-gnu": "4.43.0",
"@rollup/rollup-linux-x64-musl": "4.42.0", "@rollup/rollup-linux-x64-musl": "4.43.0",
"@rollup/rollup-win32-arm64-msvc": "4.42.0", "@rollup/rollup-win32-arm64-msvc": "4.43.0",
"@rollup/rollup-win32-ia32-msvc": "4.42.0", "@rollup/rollup-win32-ia32-msvc": "4.43.0",
"@rollup/rollup-win32-x64-msvc": "4.42.0", "@rollup/rollup-win32-x64-msvc": "4.43.0",
"fsevents": "~2.3.2" "fsevents": "~2.3.2"
} }
}, },
@@ -3448,18 +3448,18 @@
} }
}, },
"node_modules/style-to-js": { "node_modules/style-to-js": {
"version": "1.1.16", "version": "1.1.17",
"resolved": "https://registry.npmjs.org/style-to-js/-/style-to-js-1.1.16.tgz", "resolved": "https://registry.npmjs.org/style-to-js/-/style-to-js-1.1.17.tgz",
"integrity": "sha512-/Q6ld50hKYPH3d/r6nr117TZkHR0w0kGGIVfpG9N6D8NymRPM9RqCUv4pRpJ62E5DqOYx2AFpbZMyCPnjQCnOw==", "integrity": "sha512-xQcBGDxJb6jjFCTzvQtfiPn6YvvP2O8U1MDIPNfJQlWMYfktPy+iGsHE7cssjs7y84d9fQaK4UF3RIJaAHSoYA==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"style-to-object": "1.0.8" "style-to-object": "1.0.9"
} }
}, },
"node_modules/style-to-object": { "node_modules/style-to-object": {
"version": "1.0.8", "version": "1.0.9",
"resolved": "https://registry.npmjs.org/style-to-object/-/style-to-object-1.0.8.tgz", "resolved": "https://registry.npmjs.org/style-to-object/-/style-to-object-1.0.9.tgz",
"integrity": "sha512-xT47I/Eo0rwJmaXC4oilDGDWLohVhR6o/xAQcPQN8q6QBuZVL8qMYL85kLmST5cPjAorwvqIA4qXTRQoYHaL6g==", "integrity": "sha512-G4qppLgKu/k6FwRpHiGiKPaPTFcG3g4wNVX/Qsfu+RqQM30E7Tyu/TEgxcL9PNLF5pdRLwQdE3YKKf+KF2Dzlw==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"inline-style-parser": "0.2.4" "inline-style-parser": "0.2.4"

View File

@@ -14,7 +14,7 @@
"@emotion/react": "latest", "@emotion/react": "latest",
"@emotion/styled": "latest", "@emotion/styled": "latest",
"@mui/icons-material": "^7.1.1", "@mui/icons-material": "^7.1.1",
"@mui/material": "latest", "@mui/material": "^7.1.1",
"react": "19.1.0", "react": "19.1.0",
"react-dom": "19.1.0", "react-dom": "19.1.0",
"react-markdown": "^10.0.0", "react-markdown": "^10.0.0",

View File

@@ -31,7 +31,7 @@ import {
Stack, Stack,
Button, Button,
} from '@mui/material'; } from '@mui/material';
import Grid from '@mui/material/Grid2'; import Grid from '@mui/material/Grid';
import { parseDocument, Document, YAMLSeq, YAMLMap, Scalar } from 'yaml' import { parseDocument, Document, YAMLSeq, YAMLMap, Scalar } from 'yaml'
import StepCard from './StepCard'; import StepCard from './StepCard';

View File

@@ -25,7 +25,7 @@ import {
Typography, Typography,
InputAdornment, InputAdornment,
} from '@mui/material'; } from '@mui/material';
import Grid from '@mui/material/Grid2'; import Grid from '@mui/material/Grid';
import DragIndicatorIcon from '@mui/icons-material/DragIndicator'; import DragIndicatorIcon from '@mui/icons-material/DragIndicator';
import Visibility from '@mui/icons-material/Visibility'; import Visibility from '@mui/icons-material/Visibility';
import VisibilityOff from '@mui/icons-material/VisibilityOff'; import VisibilityOff from '@mui/icons-material/VisibilityOff';

View File

@@ -14,7 +14,7 @@ You will need to provide your phone number and a 2FA code the first time you run
import os import os
from telethon.sync import TelegramClient from telethon.sync import TelegramClient
from loguru import logger from auto_archiver.utils.custom_logger import logger
# Create a # Create a
@@ -24,4 +24,4 @@ SESSION_FILE = "secrets/anon-insta"
os.makedirs("secrets", exist_ok=True) os.makedirs("secrets", exist_ok=True)
with TelegramClient(SESSION_FILE, API_ID, API_HASH) as client: with TelegramClient(SESSION_FILE, API_ID, API_HASH) as client:
logger.success(f"New session file created: {SESSION_FILE}.session") logger.success(f"new session file created: {SESSION_FILE}.session")

View File

@@ -7,7 +7,7 @@ from tempfile import TemporaryDirectory
from auto_archiver.utils import url as UrlUtil from auto_archiver.utils import url as UrlUtil
from auto_archiver.core.consts import MODULE_TYPES as CONF_MODULE_TYPES from auto_archiver.core.consts import MODULE_TYPES as CONF_MODULE_TYPES
from loguru import logger from auto_archiver.utils.custom_logger import logger
if TYPE_CHECKING: if TYPE_CHECKING:
from .module import ModuleFactory from .module import ModuleFactory

View File

@@ -10,7 +10,7 @@ from ruamel.yaml import YAML, CommentedMap
import json import json
import os import os
from loguru import logger from auto_archiver.utils.custom_logger import logger
from copy import deepcopy from copy import deepcopy
from auto_archiver.core.consts import MODULE_TYPES from auto_archiver.core.consts import MODULE_TYPES
@@ -118,8 +118,7 @@ class DefaultValidatingParser(argparse.ArgumentParser):
""" """
Override of error to format a nicer looking error message using logger Override of error to format a nicer looking error message using logger
""" """
logger.error("Problem with configuration file (tip: use --help to see the available options):") logger.error(f"Problem with configuration file (tip: use --help to see the available options): \n{message}")
logger.error(message)
self.exit(2) self.exit(2)
def parse_known_args(self, args=None, namespace=None): def parse_known_args(self, args=None, namespace=None):
@@ -136,8 +135,7 @@ class DefaultValidatingParser(argparse.ArgumentParser):
try: try:
self._check_value(action, action.default) self._check_value(action, action.default)
except argparse.ArgumentError as e: except argparse.ArgumentError as e:
logger.error(f"You have an invalid setting in your configuration file ({action.dest}):") logger.error(f"You have an invalid setting in your configuration file ({action.dest}):\n {e}")
logger.error(e)
exit() exit()
return super().parse_known_args(args, namespace) return super().parse_known_args(args, namespace)

View File

@@ -12,7 +12,7 @@ from contextlib import suppress
import mimetypes import mimetypes
import os import os
import requests import requests
from loguru import logger from auto_archiver.utils.custom_logger import logger
from retrying import retry from retrying import retry
import re import re
@@ -94,7 +94,7 @@ class Extractor(BaseModule):
to_filename = to_filename[-64:] to_filename = to_filename[-64:]
to_filename = os.path.join(self.tmp_dir, to_filename) to_filename = os.path.join(self.tmp_dir, to_filename)
if verbose: if verbose:
logger.debug(f"downloading {url[0:50]=} {to_filename=}") logger.debug(f"Downloading {to_filename=}")
headers = { headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36" "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36"
} }
@@ -117,7 +117,7 @@ class Extractor(BaseModule):
return to_filename return to_filename
except requests.RequestException as e: except requests.RequestException as e:
logger.warning(f"Failed to fetch the Media URL: {str(e)[:250]}") logger.warning(f"Failed to fetch the Media URL: {e}")
if try_best_quality: if try_best_quality:
return None, url return None, url

View File

@@ -11,7 +11,7 @@ from dataclasses import dataclass, field
from dataclasses_json import dataclass_json, config from dataclasses_json import dataclass_json, config
import mimetypes import mimetypes
from loguru import logger from auto_archiver.utils.custom_logger import logger
@dataclass_json # annotation order matters @dataclass_json # annotation order matters
@@ -86,7 +86,7 @@ class Media:
@property # getter .mimetype @property # getter .mimetype
def mimetype(self) -> str: def mimetype(self) -> str:
if not self.filename or len(self.filename) == 0: if not self.filename or len(self.filename) == 0:
logger.warning(f"cannot get mimetype from media without filename: {self}") logger.warning(f"Cannot get mimetype from media without filename: {self}")
return "" return ""
if not self._mimetype: if not self._mimetype:
self._mimetype = mimetypes.guess_type(self.filename)[0] self._mimetype = mimetypes.guess_type(self.filename)[0]
@@ -116,13 +116,12 @@ class Media:
# self.is_video() should be used together with this method # self.is_video() should be used together with this method
try: try:
streams = ffmpeg.probe(self.filename, select_streams="v")["streams"] streams = ffmpeg.probe(self.filename, select_streams="v")["streams"]
logger.debug(f"STREAMS FOR {self.filename} {streams}") logger.debug(f"Streams for {self.filename}: {streams}")
return any(s.get("duration_ts", 0) > 0 for s in streams) return any(s.get("duration_ts", 0) > 0 for s in streams)
except Error: except Error:
return False # ffmpeg errors when reading bad files return False # ffmpeg errors when reading bad files
except Exception as e: except Exception as e:
logger.error(e) logger.error(f"{e}: {traceback.format_exc()}")
logger.error(traceback.format_exc())
try: try:
fsize = os.path.getsize(self.filename) fsize = os.path.getsize(self.filename)
return fsize > 20_000 return fsize > 20_000

View File

@@ -17,7 +17,7 @@ from dataclasses_json import dataclass_json
import datetime import datetime
from urllib.parse import urlparse from urllib.parse import urlparse
from dateutil.parser import parse as parse_dt from dateutil.parser import parse as parse_dt
from loguru import logger from auto_archiver.utils.custom_logger import logger
from .media import Media from .media import Media

View File

@@ -16,7 +16,7 @@ import sys
from importlib.util import find_spec from importlib.util import find_spec
import os import os
from os.path import join from os.path import join
from loguru import logger from auto_archiver.utils.custom_logger import logger
import auto_archiver import auto_archiver
from auto_archiver.core.consts import DEFAULT_MANIFEST, MANIFEST_FILE, SetupError from auto_archiver.core.consts import DEFAULT_MANIFEST, MANIFEST_FILE, SetupError

View File

@@ -15,9 +15,11 @@ import traceback
from copy import copy from copy import copy
from rich_argparse import RichHelpFormatter from rich_argparse import RichHelpFormatter
from loguru import logger from auto_archiver.utils.custom_logger import format_for_human_readable_console, logger
import requests import requests
from auto_archiver.utils.misc import random_str
from .metadata import Metadata, Media from .metadata import Metadata, Media
from auto_archiver.version import __version__ from auto_archiver.version import __version__
from .config import ( from .config import (
@@ -342,7 +344,14 @@ Here's how that would look: \n\nsteps:\n extractors:\n - [your_extractor_name_
# add other logging info # add other logging info
if self.logger_id is None: # note - need direct comparison to None since need to consider falsy value 0 if self.logger_id is None: # note - need direct comparison to None since need to consider falsy value 0
use_level = logging_config["level"] use_level = logging_config["level"]
self.logger_id = logger.add(sys.stderr, level=use_level) self.logger_id = logger.add(
sys.stderr,
level=use_level,
catch=True,
format="<level>{extra[serialized]}</level>"
if logging_config.get("format", "").lower() == "json"
else format_for_human_readable_console(),
)
rotation = logging_config["rotation"] rotation = logging_config["rotation"]
log_file = logging_config["file"] log_file = logging_config["file"]
@@ -356,9 +365,10 @@ Here's how that would look: \n\nsteps:\n extractors:\n - [your_extractor_name_
f"{log_file}.{i}_{level.lower()}", f"{log_file}.{i}_{level.lower()}",
filter=lambda rec, lvl=level: rec["level"].name == lvl, filter=lambda rec, lvl=level: rec["level"].name == lvl,
rotation=rotation, rotation=rotation,
format="{extra[serialized]}",
) )
elif log_file: elif log_file:
logger.add(log_file, rotation=rotation, level=use_level) logger.add(log_file, rotation=rotation, level=use_level, format="{extra[serialized]}")
def install_modules(self, modules_by_type): def install_modules(self, modules_by_type):
""" """
@@ -466,13 +476,9 @@ Here's how that would look: \n\nsteps:\n extractors:\n - [your_extractor_name_
update_cmd = "`docker pull bellingcat/auto-archiver:latest`" update_cmd = "`docker pull bellingcat/auto-archiver:latest`"
else: else:
update_cmd = "`pip install --upgrade auto-archiver`" update_cmd = "`pip install --upgrade auto-archiver`"
logger.warning("")
logger.warning("********* IMPORTANT: UPDATE AVAILABLE ********")
logger.warning( logger.warning(
f"A new version of auto-archiver is available (v{latest_version}, you have v{current_version})" f"\n********* IMPORTANT: UPDATE AVAILABLE ********\nA new version of auto-archiver is available (v{latest_version}, you have v{current_version})\nMake sure to update to the latest version using: {update_cmd}\n"
) )
logger.warning(f"Make sure to update to the latest version using: {update_cmd}")
logger.warning("")
def setup(self, args: list): def setup(self, args: list):
""" """
@@ -522,7 +528,7 @@ Here's how that would look: \n\nsteps:\n extractors:\n - [your_extractor_name_
self.setup(args) self.setup(args)
return self.feed() return self.feed()
except Exception as e: except Exception as e:
logger.error(e) logger.error(f"{e}: {traceback.format_exc()}")
exit(1) exit(1)
def cleanup(self) -> None: def cleanup(self) -> None:
@@ -534,8 +540,10 @@ Here's how that would look: \n\nsteps:\n extractors:\n - [your_extractor_name_
url_count = 0 url_count = 0
for feeder in self.feeders: for feeder in self.feeders:
for item in feeder: for item in feeder:
yield self.feed_item(item) with logger.contextualize(url=item.get_url(), trace=random_str(12)):
url_count += 1 logger.info("Started processing")
yield self.feed_item(item)
url_count += 1
logger.info(f"Processed {url_count} URL(s)") logger.info(f"Processed {url_count} URL(s)")
self.cleanup() self.cleanup()
@@ -555,13 +563,13 @@ Here's how that would look: \n\nsteps:\n extractors:\n - [your_extractor_name_
return self.archive(item) return self.archive(item)
except KeyboardInterrupt: except KeyboardInterrupt:
# catches keyboard interruptions to do a clean exit # catches keyboard interruptions to do a clean exit
logger.warning(f"caught interrupt on {item=}") logger.warning("Caught interrupt")
for d in self.databases: for d in self.databases:
d.aborted(item) d.aborted(item)
self.cleanup() self.cleanup()
exit() exit()
except Exception as e: except Exception as e:
logger.error(f"Got unexpected error on item {item}: {e}\n{traceback.format_exc()}") logger.error(f"Got unexpected error: {e}\n{traceback.format_exc()}")
for d in self.databases: for d in self.databases:
if isinstance(e, AssertionError): if isinstance(e, AssertionError):
d.failed(item, str(e)) d.failed(item, str(e))
@@ -589,7 +597,7 @@ Here's how that would look: \n\nsteps:\n extractors:\n - [your_extractor_name_
try: try:
check_url_or_raise(original_url) check_url_or_raise(original_url)
except ValueError as e: except ValueError as e:
logger.error(f"Error archiving URL {original_url}: {e}") logger.error(f"Error archiving: {e}")
raise e raise e
# 1 - sanitize - each archiver is responsible for cleaning/expanding its own URLs # 1 - sanitize - each archiver is responsible for cleaning/expanding its own URLs
@@ -599,7 +607,7 @@ Here's how that would look: \n\nsteps:\n extractors:\n - [your_extractor_name_
result.set_url(url) result.set_url(url)
if original_url != url: if original_url != url:
logger.debug(f"Sanitized URL from {original_url} to {url}") logger.debug(f"Sanitized URL to {url}")
result.set("original_url", original_url) result.set("original_url", original_url)
# 2 - notify start to DBs, propagate already archived if feature enabled in DBs # 2 - notify start to DBs, propagate already archived if feature enabled in DBs
@@ -614,25 +622,25 @@ Here's how that would look: \n\nsteps:\n extractors:\n - [your_extractor_name_
try: try:
d.done(cached_result, cached=True) d.done(cached_result, cached=True)
except Exception as e: except Exception as e:
logger.error(f"ERROR database {d.name}: {e}: {traceback.format_exc()}") logger.error(f"Database {d.name}: {e}: {traceback.format_exc()}")
return cached_result return cached_result
# 3 - call extractors until one succeeds # 3 - call extractors until one succeeds
for a in self.extractors: for a in self.extractors:
logger.info(f"Trying extractor {a.name} for {url}") logger.info(f"Trying extractor {a.name}")
try: try:
result.merge(a.download(result)) result.merge(a.download(result))
if result.is_success(): if result.is_success():
break break
except Exception as e: except Exception as e:
logger.error(f"ERROR archiver {a.name}: {e}: {traceback.format_exc()}") logger.error(f"Extractor {a.name}: {e}: {traceback.format_exc()}")
# 4 - call enrichers to work with archived content # 4 - call enrichers to work with archived content
for e in self.enrichers: for e in self.enrichers:
try: try:
e.enrich(result) e.enrich(result)
except Exception as exc: except Exception as exc:
logger.error(f"ERROR enricher {e.name}: {exc}: {traceback.format_exc()}") logger.error(f"Enricher {e.name}: {exc}: {traceback.format_exc()}")
# 5 - store all downloaded/generated media # 5 - store all downloaded/generated media
result.store(storages=self.storages) result.store(storages=self.storages)
@@ -651,7 +659,7 @@ Here's how that would look: \n\nsteps:\n extractors:\n - [your_extractor_name_
try: try:
d.done(result) d.done(result)
except Exception as e: except Exception as e:
logger.error(f"ERROR database {d.name}: {e}: {traceback.format_exc()}") logger.error(f"Database {d.name}: {e}: {traceback.format_exc()}")
return result return result

View File

@@ -24,7 +24,7 @@ from abc import abstractmethod
from typing import IO from typing import IO
import os import os
from loguru import logger from auto_archiver.utils.custom_logger import logger
from slugify import slugify from slugify import slugify
from auto_archiver.utils.misc import random_str from auto_archiver.utils.misc import random_str

View File

@@ -7,7 +7,7 @@ from urllib.parse import urljoin
import glob import glob
import importlib.util import importlib.util
from loguru import logger from auto_archiver.utils.custom_logger import logger
import selenium import selenium
from seleniumbase import SB from seleniumbase import SB
@@ -57,7 +57,7 @@ class AntibotExtractorEnricher(Extractor, Enricher):
continue # Skip imported modules/classes/functions continue # Skip imported modules/classes/functions
if isinstance(obj, type) and issubclass(obj, Dropin): if isinstance(obj, type) and issubclass(obj, Dropin):
dropins.append(obj) dropins.append(obj)
logger.debug(f"ANTIBOT loaded drop-in classes: {', '.join([d.__name__ for d in dropins])}") logger.debug(f"Loaded drop-in classes: {', '.join([d.__name__ for d in dropins])}")
return dropins return dropins
def sanitize_url(self, url: str) -> str: def sanitize_url(self, url: str) -> str:
@@ -81,24 +81,29 @@ class AntibotExtractorEnricher(Extractor, Enricher):
os.makedirs(self.user_data_dir, exist_ok=True) os.makedirs(self.user_data_dir, exist_ok=True)
def enrich(self, to_enrich: Metadata, custom_data_dir: bool = True) -> bool: def enrich(self, to_enrich: Metadata, custom_data_dir: bool = True) -> bool:
if to_enrich.get_media_by_id("html_source_code"):
logger.info("Antibot has already been executed, skipping.")
return True
using_user_data_dir = self.user_data_dir if custom_data_dir else None using_user_data_dir = self.user_data_dir if custom_data_dir else None
url = to_enrich.get_url() url = to_enrich.get_url()
url_sample = url[:75]
try: try:
with SB(uc=True, agent=self.agent, headed=None, user_data_dir=using_user_data_dir, proxy=self.proxy) as sb: with SB(uc=True, agent=self.agent, headed=None, user_data_dir=using_user_data_dir, proxy=self.proxy) as sb:
logger.info(f"ANTIBOT selenium browser is up with agent {self.agent}, opening {url_sample}...") logger.info(f"Selenium browser is up with agent {self.agent}, opening url...")
sb.uc_open_with_reconnect(url, 4) sb.uc_open_with_reconnect(url, 4)
logger.debug(f"ANTIBOT handling CAPTCHAs for {url_sample}...") logger.debug("Handling CAPTCHAs for...")
sb.uc_gui_handle_cf() sb.uc_gui_handle_cf()
sb.uc_gui_click_rc() # NB: using handle instead of click breaks some sites like reddit, for now we separate here but can have dropins deciding this in the future sb.uc_gui_click_rc() # NB: using handle instead of click breaks some sites like reddit, for now we separate here but can have dropins deciding this in the future
dropin = self._get_suitable_dropin(url, sb) dropin = self._get_suitable_dropin(url, sb)
dropin.open_page(url) if not dropin.open_page(url):
# TODO: could we detect deleted videos?
logger.warning("Failed to open drop-in page")
return False
if self.detect_auth_wall and self._hit_auth_wall(sb): if self.detect_auth_wall and (dropin.hit_auth_wall() and self._hit_auth_wall(sb)):
logger.warning(f"ANTIBOT SKIP since auth wall or CAPTCHA was detected for {url_sample}") logger.warning("Skipping since auth wall or CAPTCHA was detected")
return False return False
sb.wait_for_ready_state_complete() sb.wait_for_ready_state_complete()
@@ -125,18 +130,18 @@ class AntibotExtractorEnricher(Extractor, Enricher):
js_css_selector=dropin.js_for_video_css_selectors(), js_css_selector=dropin.js_for_video_css_selectors(),
max_media=self.max_download_videos - downloaded_videos, max_media=self.max_download_videos - downloaded_videos,
) )
logger.info(f"ANTIBOT completed for {url_sample}") logger.info("Completed")
return to_enrich return to_enrich
except selenium.common.exceptions.SessionNotCreatedException as e: except selenium.common.exceptions.SessionNotCreatedException as e:
if custom_data_dir: # the retry logic only works once if custom_data_dir: # the retry logic only works once
logger.error( logger.error(
f"ANTIBOT session not created error: {e}. Please remove the user_data_dir {self.user_data_dir} and try again, will retry without user data dir though." f"Session not created error: {e}. Please remove the user_data_dir {self.user_data_dir} and try again, will retry without user data dir though."
) )
return self.enrich(to_enrich, custom_data_dir=False) return self.enrich(to_enrich, custom_data_dir=False)
raise e # re-raise raise e # re-raise
except Exception as e: except Exception as e:
logger.error(f"ANTIBOT runtime error: {e}: {traceback.format_exc()}") logger.error(f"Runtime error: {e}: {traceback.format_exc()}")
return False return False
def _get_suitable_dropin(self, url: str, sb: SB): def _get_suitable_dropin(self, url: str, sb: SB):
@@ -146,7 +151,7 @@ class AntibotExtractorEnricher(Extractor, Enricher):
""" """
for dropin in self.dropins: for dropin in self.dropins:
if dropin.suitable(url): if dropin.suitable(url):
logger.debug(f"ANTIBOT using drop-in {dropin.__name__} for {url}") logger.debug(f"Using drop-in {dropin.__name__}")
return dropin(sb, self) return dropin(sb, self)
return DefaultDropin(sb, self) return DefaultDropin(sb, self)
@@ -275,8 +280,14 @@ class AntibotExtractorEnricher(Extractor, Enricher):
return return
url = to_enrich.get_url() url = to_enrich.get_url()
all_urls = set() all_urls = set()
logger.debug(f"Extracting media for {js_css_selector=}")
try:
sources = sb.execute_script(js_css_selector)
except selenium.common.exceptions.JavascriptException as e:
logger.error(f"Error executing JavaScript selector {js_css_selector}: {e}")
return
sources = sb.execute_script(js_css_selector)
# js_for_css_selectors # js_for_css_selectors
for src in sources: for src in sources:
if len(all_urls) >= max_media: if len(all_urls) >= max_media:

View File

@@ -1,6 +1,8 @@
import json
import os import os
import traceback
from typing import Mapping from typing import Mapping
from loguru import logger from auto_archiver.utils.custom_logger import logger
from seleniumbase import SB from seleniumbase import SB
import yt_dlp import yt_dlp
@@ -73,8 +75,11 @@ class Dropin:
You can overwrite this instead of `images_selector` for more control over scraped images. You can overwrite this instead of `images_selector` for more control over scraped images.
""" """
if not self.images_selectors():
return "return [];"
safe_selector = json.dumps(self.images_selectors())
return f""" return f"""
return Array.from(document.querySelectorAll("{self.images_selectors()}")).map(el => el.src || el.href).filter(Boolean); return Array.from(document.querySelectorAll({safe_selector})).map(el => el.src || el.href).filter(Boolean);
""" """
def js_for_video_css_selectors(self) -> str: def js_for_video_css_selectors(self) -> str:
@@ -83,8 +88,11 @@ class Dropin:
You can overwrite this instead of `video_selector` for more control over scraped videos. You can overwrite this instead of `video_selector` for more control over scraped videos.
""" """
if not self.video_selectors():
return "return [];"
safe_selector = json.dumps(self.video_selectors())
return f""" return f"""
return Array.from(document.querySelectorAll("{self.video_selectors()}")).map(el => el.src || el.href).filter(Boolean); return Array.from(document.querySelectorAll({safe_selector})).map(el => el.src || el.href).filter(Boolean);
""" """
def open_page(self, url) -> bool: def open_page(self, url) -> bool:
@@ -102,6 +110,12 @@ class Dropin:
""" """
return 0, 0 return 0, 0
def hit_auth_wall(self) -> bool:
"""
Custom check to see if the current page is behind an authentication wall, if True is returned the default global auth wall detector is used instead. If false, no auth wall is detected and the page is considered open.
"""
return True
def _get_username_password(self, site) -> tuple[str, str]: def _get_username_password(self, site) -> tuple[str, str]:
""" """
Get the username and password for the site from the extractor's auth data. Get the username and password for the site from the extractor's auth data.
@@ -143,7 +157,7 @@ class Dropin:
with yt_dlp.YoutubeDL(validated_options) as ydl: with yt_dlp.YoutubeDL(validated_options) as ydl:
for url in video_urls: for url in video_urls:
try: try:
logger.debug(f"Downloading video from URL: {url}") logger.debug(f"Downloading video from url: {url}")
info = ydl.extract_info(url, download=True) info = ydl.extract_info(url, download=True)
filename = ydl_entry_to_filename(ydl, info) filename = ydl_entry_to_filename(ydl, info)
if not filename: # Failed to download video. if not filename: # Failed to download video.
@@ -155,5 +169,5 @@ class Dropin:
to_enrich.add_media(media) to_enrich.add_media(media)
downloaded += 1 downloaded += 1
except Exception as e: except Exception as e:
logger.error(f"Error downloading {url}: {e}") logger.error(f"Download failed: {e} {traceback.format_exc()}")
return downloaded return downloaded

View File

@@ -1,5 +1,5 @@
from typing import Mapping from typing import Mapping
from loguru import logger from auto_archiver.utils.custom_logger import logger
from auto_archiver.modules.antibot_extractor_enricher.dropin import Dropin from auto_archiver.modules.antibot_extractor_enricher.dropin import Dropin
@@ -62,7 +62,7 @@ class LinkedinDropin(Dropin):
self.sb.wait_for_ready_state_complete() self.sb.wait_for_ready_state_complete()
username, password = self._get_username_password("linkedin.com") username, password = self._get_username_password("linkedin.com")
logger.debug("LinkedinDropin Logging in to Linkedin with username: {}", username) logger.debug("Logging in to Linkedin with username: {}", username)
self.sb.type("#username", username) self.sb.type("#username", username)
self.sb.type("#password", password) self.sb.type("#password", password)
self.sb.click_if_visible("#password-visibility-toggle", timeout=0.5) self.sb.click_if_visible("#password-visibility-toggle", timeout=0.5)

View File

@@ -3,7 +3,7 @@ from typing import Mapping
from auto_archiver.core.metadata import Metadata from auto_archiver.core.metadata import Metadata
from auto_archiver.modules.antibot_extractor_enricher.dropin import Dropin from auto_archiver.modules.antibot_extractor_enricher.dropin import Dropin
from loguru import logger from auto_archiver.utils.custom_logger import logger
class RedditDropin(Dropin): class RedditDropin(Dropin):
@@ -50,7 +50,7 @@ class RedditDropin(Dropin):
self._close_cookies_banner() self._close_cookies_banner()
username, password = self._get_username_password("reddit.com") username, password = self._get_username_password("reddit.com")
logger.debug("RedditDropin Logging in to Reddit with username: {}", username) logger.debug("Logging in to Reddit with username: {}", username)
self.sb.type("#login-username", username) self.sb.type("#login-username", username)
self.sb.type("#login-password", password) self.sb.type("#login-password", password)
@@ -68,7 +68,7 @@ class RedditDropin(Dropin):
self.sb.click_link_text("Log in") self.sb.click_link_text("Log in")
self.sb.wait_for_ready_state_complete() self.sb.wait_for_ready_state_complete()
if self.sb.is_text_visible("Welcome back"): if self.sb.is_text_visible("Welcome back"):
logger.debug("RedditDropin Login successful") logger.debug("Login successful")
self.sb.click_if_visible("this link") self.sb.click_if_visible("this link")
def _close_cookies_banner(self): def _close_cookies_banner(self):
@@ -88,5 +88,5 @@ class RedditDropin(Dropin):
.map(el => el.src || el.href) .map(el => el.src || el.href)
.filter(url => url && /\.(m3u8|mpd|ism)$/.test(url)); .filter(url => url && /\.(m3u8|mpd|ism)$/.test(url));
""") """)
logger.debug("RedditDropin Found {} video URLs", len(filtered_urls)) logger.debug("Found {} video URLs", len(filtered_urls))
return 0, self._download_videos_with_ytdlp(filtered_urls, to_enrich) return 0, self._download_videos_with_ytdlp(filtered_urls, to_enrich)

View File

@@ -0,0 +1,56 @@
from contextlib import suppress
from typing import Mapping
from auto_archiver.utils.custom_logger import logger
from auto_archiver.modules.antibot_extractor_enricher.dropin import Dropin
class TikTokDropin(Dropin):
"""
A class to handle TikTok drop-in functionality for the antibot extractor enricher module.
"""
def documentation() -> Mapping[str, str]:
return {
"name": "TikTok Dropin",
"description": "Handles TikTok posts and works without authentication.\nNOTE: This dropin is highly susceptible to TikTok's bot detection mechanisms and may not work reliably if you reuse the same IP. The GenericExtractor is recommended for TikTok posts, as it handles video/image download more reliable. In the future we plan to implement better anti captcha measures for this dropin.",
"site": "tiktok.com",
}
@staticmethod
def suitable(url: str) -> bool:
return "tiktok.com" in url
@staticmethod
def images_selectors() -> str:
return '[data-e2e="detail-photo"] img'
@staticmethod
def video_selectors() -> str:
return None # TikTok videos should be handled by the generic extractor
def open_page(self, url) -> bool:
self.sb.wait_for_ready_state_complete()
self._close_cookies_banner()
# TODO: implement login logic
if url != self.sb.get_current_url():
return False
if self.sb.is_text_visible("Video currently unavailable"):
logger.debug("Video may have been removed or is private.")
return False
return True
def hit_auth_wall(self) -> bool:
return False # TikTok does not require authentication for public posts
def _close_cookies_banner(self):
with suppress(Exception): # selenium.common.exceptions.JavascriptException
self.sb.execute_script("""
document
.querySelector("tiktok-cookie-banner")
.shadowRoot.querySelector("faceplate-dialog")
.querySelector("button")
.click()
""")
self.sb.click_if_visible("Skip")

View File

@@ -4,7 +4,7 @@ from typing import Mapping
from auto_archiver.core.metadata import Metadata from auto_archiver.core.metadata import Metadata
from auto_archiver.modules.antibot_extractor_enricher.dropin import Dropin from auto_archiver.modules.antibot_extractor_enricher.dropin import Dropin
from loguru import logger from auto_archiver.utils.custom_logger import logger
class VkDropin(Dropin): class VkDropin(Dropin):

View File

@@ -2,7 +2,7 @@ from typing import Union
import os import os
import requests import requests
from loguru import logger from auto_archiver.utils.custom_logger import logger
from auto_archiver.core import Database from auto_archiver.core import Database
from auto_archiver.core import Metadata from auto_archiver.core import Metadata
@@ -36,9 +36,9 @@ class AAApiDb(Database):
if not self.store_results: if not self.store_results:
return return
if cached: if cached:
logger.debug(f"skipping saving archive of {item.get_url()} to the AA API because it was cached") logger.debug("Skipping saving archive to AA API because it was cached")
return return
logger.debug(f"saving archive of {item.get_url()} to the AA API.") logger.debug("Saving archive to the AA API.")
payload = { payload = {
"author_id": self.author_id, "author_id": self.author_id,

View File

@@ -3,7 +3,7 @@ import os
from typing import IO, Iterator, Optional, Union from typing import IO, Iterator, Optional, Union
import requests import requests
from loguru import logger from auto_archiver.utils.custom_logger import logger
from auto_archiver.core import Database, Feeder, Media, Metadata, Storage from auto_archiver.core import Database, Feeder, Media, Metadata, Storage
from auto_archiver.utils import calculate_file_hash from auto_archiver.utils import calculate_file_hash
@@ -66,13 +66,13 @@ class AtlosFeederDbStorage(Feeder, Database, Storage):
"""Mark an item as failed in Atlos, if the ID exists.""" """Mark an item as failed in Atlos, if the ID exists."""
atlos_id = item.metadata.get("atlos_id") atlos_id = item.metadata.get("atlos_id")
if not atlos_id: if not atlos_id:
logger.info(f"Item {item.get_url()} has no Atlos ID, skipping") logger.info("No Atlos ID available, skipping")
return return
self._post( self._post(
f"/api/v2/source_material/metadata/{atlos_id}/auto_archiver", f"/api/v2/source_material/metadata/{atlos_id}/auto_archiver",
json={"metadata": {"processed": True, "status": "error", "error": reason}}, json={"metadata": {"processed": True, "status": "error", "error": reason}},
) )
logger.info(f"Stored failure for {item.get_url()} (ID {atlos_id}) on Atlos: {reason}") logger.info(f"Stored failure ID {atlos_id} on Atlos: {reason}")
def fetch(self, item: Metadata) -> Union[Metadata, bool]: def fetch(self, item: Metadata) -> Union[Metadata, bool]:
"""check and fetch if the given item has been archived already, each """check and fetch if the given item has been archived already, each
@@ -88,7 +88,7 @@ class AtlosFeederDbStorage(Feeder, Database, Storage):
"""Mark an item as successfully archived in Atlos.""" """Mark an item as successfully archived in Atlos."""
atlos_id = item.metadata.get("atlos_id") atlos_id = item.metadata.get("atlos_id")
if not atlos_id: if not atlos_id:
logger.info(f"Item {item.get_url()} has no Atlos ID, skipping") logger.info("Item has no Atlos ID, skipping")
return return
self._post( self._post(
f"/api/v2/source_material/metadata/{atlos_id}/auto_archiver", f"/api/v2/source_material/metadata/{atlos_id}/auto_archiver",
@@ -100,7 +100,7 @@ class AtlosFeederDbStorage(Feeder, Database, Storage):
} }
}, },
) )
logger.info(f"Stored success for {item.get_url()} (ID {atlos_id}) on Atlos") logger.info(f"Stored success ID {atlos_id} on Atlos")
# ! Atlos Module - Storage Methods # ! Atlos Module - Storage Methods

View File

@@ -1,5 +1,3 @@
from loguru import logger
from auto_archiver.core.feeder import Feeder from auto_archiver.core.feeder import Feeder
from auto_archiver.core.metadata import Metadata from auto_archiver.core.metadata import Metadata
from auto_archiver.core.consts import SetupError from auto_archiver.core.consts import SetupError
@@ -16,8 +14,5 @@ class CLIFeeder(Feeder):
def __iter__(self) -> Metadata: def __iter__(self) -> Metadata:
urls = self.config["urls"] urls = self.config["urls"]
for url in urls: for url in urls:
logger.debug(f"Processing {url}")
m = Metadata().set_url(url) m = Metadata().set_url(url)
yield m yield m
logger.success(f"Processed {len(urls)} URL(s)")

View File

@@ -1,4 +1,4 @@
from loguru import logger from auto_archiver.utils.custom_logger import logger
from auto_archiver.core import Database from auto_archiver.core import Database
from auto_archiver.core import Metadata from auto_archiver.core import Metadata

View File

@@ -1,5 +1,5 @@
import os import os
from loguru import logger from auto_archiver.utils.custom_logger import logger
from csv import DictWriter from csv import DictWriter
from dataclasses import asdict from dataclasses import asdict

View File

@@ -1,4 +1,4 @@
from loguru import logger from auto_archiver.utils.custom_logger import logger
import csv import csv
from auto_archiver.core import Feeder from auto_archiver.core import Feeder
@@ -35,5 +35,4 @@ class CSVFeeder(Feeder):
logger.warning(f"Not a valid URL in row: {row}, skipping") logger.warning(f"Not a valid URL in row: {row}, skipping")
continue continue
url = row[url_column] url = row[url_column]
logger.debug(f"Processing {url}")
yield Metadata().set_url(url) yield Metadata().set_url(url)

View File

@@ -8,7 +8,7 @@ from google.oauth2 import service_account
from google.oauth2.credentials import Credentials from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload from googleapiclient.http import MediaFileUpload
from loguru import logger from auto_archiver.utils.custom_logger import logger
from auto_archiver.core import Media from auto_archiver.core import Media
from auto_archiver.core import Storage from auto_archiver.core import Storage
@@ -62,7 +62,7 @@ class GDriveStorage(Storage):
parent_id, folder_id = self.root_folder_id, None parent_id, folder_id = self.root_folder_id, None
path_parts = media.key.split(os.path.sep) path_parts = media.key.split(os.path.sep)
filename = path_parts[-1] filename = path_parts[-1]
logger.info(f"looking for folders for {path_parts[0:-1]} before getting url for {filename=}") logger.info(f"Looking for folders for {path_parts[0:-1]} before getting url for {filename=}")
for folder in path_parts[0:-1]: for folder in path_parts[0:-1]:
folder_id = self._get_id_from_parent_and_name(parent_id, folder, use_mime_type=True, raise_on_missing=True) folder_id = self._get_id_from_parent_and_name(parent_id, folder, use_mime_type=True, raise_on_missing=True)
parent_id = folder_id parent_id = folder_id
@@ -70,7 +70,7 @@ class GDriveStorage(Storage):
file_id = self._get_id_from_parent_and_name(folder_id, filename, raise_on_missing=True) file_id = self._get_id_from_parent_and_name(folder_id, filename, raise_on_missing=True)
if not file_id: if not file_id:
# #
logger.info(f"file {filename} not found in folder {folder_id}") logger.info(f"File {filename} not found in folder {folder_id}")
return None return None
return f"https://drive.google.com/file/d/{file_id}/view?usp=sharing" return f"https://drive.google.com/file/d/{file_id}/view?usp=sharing"
@@ -83,7 +83,7 @@ class GDriveStorage(Storage):
parent_id, upload_to = self.root_folder_id, None parent_id, upload_to = self.root_folder_id, None
path_parts = media.key.split(os.path.sep) path_parts = media.key.split(os.path.sep)
filename = path_parts[-1] filename = path_parts[-1]
logger.info(f"checking folders {path_parts[0:-1]} exist (or creating) before uploading {filename=}") logger.info(f"Checking folders {path_parts[0:-1]} exist (or creating) before uploading {filename=}")
for folder in path_parts[0:-1]: for folder in path_parts[0:-1]:
upload_to = self._get_id_from_parent_and_name(parent_id, folder, use_mime_type=True, raise_on_missing=False) upload_to = self._get_id_from_parent_and_name(parent_id, folder, use_mime_type=True, raise_on_missing=False)
if upload_to is None: if upload_to is None:
@@ -91,7 +91,7 @@ class GDriveStorage(Storage):
parent_id = upload_to parent_id = upload_to
# upload file to gd # upload file to gd
logger.debug(f"uploading {filename=} to folder id {upload_to}") logger.debug(f"Uploading {filename=} to folder id {upload_to}")
file_metadata = {"name": [filename], "parents": [upload_to]} file_metadata = {"name": [filename], "parents": [upload_to]}
try: try:
media = MediaFileUpload(media.filename, resumable=True) media = MediaFileUpload(media.filename, resumable=True)
@@ -100,11 +100,11 @@ class GDriveStorage(Storage):
.create(supportsAllDrives=True, body=file_metadata, media_body=media, fields="id") .create(supportsAllDrives=True, body=file_metadata, media_body=media, fields="id")
.execute() .execute()
) )
logger.debug(f"uploadf: uploaded file {gd_file['id']} successfully in folder={upload_to}") logger.debug(f"Uploadf: uploaded file {gd_file['id']} successfully in folder={upload_to}")
except FileNotFoundError as e: except FileNotFoundError as e:
logger.error(f"gd uploadf: file not found {media.filename=} - {e}") logger.error(f"GD uploadf: file not found {media.filename=} - {e}")
except Exception as e: except Exception as e:
logger.error(f"gd uploadf: error uploading {media.filename=} to {upload_to} - {e}") logger.error(f"GD uploadf: error uploading {media.filename=} to {upload_to} - {e}")
# must be implemented even if unused # must be implemented even if unused
def uploadf(self, file: IO[bytes], key: str, **kwargs: dict) -> bool: def uploadf(self, file: IO[bytes], key: str, **kwargs: dict) -> bool:
@@ -133,7 +133,7 @@ class GDriveStorage(Storage):
self.api_cache = getattr(self, "api_cache", {}) self.api_cache = getattr(self, "api_cache", {})
cache_key = f"{parent_id}_{name}_{use_mime_type}" cache_key = f"{parent_id}_{name}_{use_mime_type}"
if cache_key in self.api_cache: if cache_key in self.api_cache:
logger.debug(f"cache hit for {cache_key=}") logger.debug(f"Cache hit for {cache_key=}")
return self.api_cache[cache_key] return self.api_cache[cache_key]
# API logic # API logic
@@ -168,7 +168,7 @@ class GDriveStorage(Storage):
else: else:
logger.debug(f"{debug_header} not found, attempt {attempt + 1}/{retries}.") logger.debug(f"{debug_header} not found, attempt {attempt + 1}/{retries}.")
if attempt < retries - 1: if attempt < retries - 1:
logger.debug(f"sleeping for {sleep_seconds} second(s)") logger.debug(f"Sleeping for {sleep_seconds} second(s)")
time.sleep(sleep_seconds) time.sleep(sleep_seconds)
if raise_on_missing: if raise_on_missing:

View File

@@ -58,7 +58,11 @@ If you are having issues with the extractor, you can review the version of `yt-d
}, },
"proxy": { "proxy": {
"default": "", "default": "",
"help": "http/socks (https seems to not work atm) proxy to use for the webdriver, eg https://proxy-user:password@proxy-ip:port", "help": "http/https/socks proxy to use for the webdriver, eg https://proxy-user:password@proxy-ip:port",
},
"proxy_on_failure_only": {
"default": True,
"help": "Applies only if a proxy is set. In that case if this setting is True, the extractor will only use the proxy if the initial request fails; if it is False, the extractor will always use the proxy.",
}, },
"end_means_success": { "end_means_success": {
"default": True, "default": True,

View File

@@ -1,4 +1,4 @@
from loguru import logger from auto_archiver.utils.custom_logger import logger
from auto_archiver.core.extractor import Extractor from auto_archiver.core.extractor import Extractor
from auto_archiver.core.metadata import Metadata, Media from auto_archiver.core.metadata import Metadata, Media

View File

@@ -4,6 +4,7 @@ import datetime
import os import os
import importlib import importlib
import subprocess import subprocess
import traceback
import zipfile import zipfile
from typing import Generator, Type from typing import Generator, Type
@@ -14,7 +15,7 @@ from yt_dlp.extractor.common import InfoExtractor
from yt_dlp.utils import MaxDownloadsReached from yt_dlp.utils import MaxDownloadsReached
import pysubs2 import pysubs2
from loguru import logger from auto_archiver.utils.custom_logger import logger
from auto_archiver.core.extractor import Extractor from auto_archiver.core.extractor import Extractor
from auto_archiver.core import Metadata, Media from auto_archiver.core import Metadata, Media
@@ -63,8 +64,7 @@ class GenericExtractor(Extractor):
if os.environ.get("AUTO_ARCHIVER_ALLOW_RESTART", "1") != "1": if os.environ.get("AUTO_ARCHIVER_ALLOW_RESTART", "1") != "1":
logger.warning("yt-dlp or plugin was updated — please restart auto-archiver manually") logger.warning("yt-dlp or plugin was updated — please restart auto-archiver manually")
else: else:
logger.warning("yt-dlp or plugin was updated — restarting auto-archiver") logger.warning("yt-dlp or plugin was updated — restarting auto-archiver\n ======= RESTARTING ======= ")
logger.warning(" ======= RESTARTING ======= ")
os.execv(sys.executable, [sys.executable] + sys.argv) os.execv(sys.executable, [sys.executable] + sys.argv)
def update_package(self, package_name: str) -> bool: def update_package(self, package_name: str) -> bool:
@@ -80,7 +80,7 @@ class GenericExtractor(Extractor):
return True return True
logger.info(f"{package_name} already up to date") logger.info(f"{package_name} already up to date")
except Exception as e: except Exception as e:
logger.error(f"Error updating {package_name}: {e}") logger.error(f"Failed to update {package_name}: {e}")
return False return False
def setup_po_tokens(self) -> None: def setup_po_tokens(self) -> None:
@@ -206,7 +206,7 @@ class GenericExtractor(Extractor):
media = Media(cover_image_path) media = Media(cover_image_path)
metadata.add_media(media, id="cover") metadata.add_media(media, id="cover")
except Exception as e: except Exception as e:
logger.error(f"Error downloading cover image {thumbnail_url}: {e}") logger.error(f"Could not download cover image {thumbnail_url}: {e}")
dropin = self.dropin_for_name(info_extractor.ie_key()) dropin = self.dropin_for_name(info_extractor.ie_key())
if dropin: if dropin:
@@ -306,9 +306,9 @@ class GenericExtractor(Extractor):
result.set_url(url) result.set_url(url)
if "description" in video_data and not result.get("content"): if "description" in video_data and not result.get("content"):
result.set_content(video_data.get("description")) result.set_content(video_data.pop("description"))
# extract comments if enabled # extract comments if enabled
if self.comments and video_data.get("comments", []) is not None: if self.comments and video_data.get("comments", None) is not None:
result.set( result.set(
"comments", "comments",
[ [
@@ -375,7 +375,7 @@ class GenericExtractor(Extractor):
if "entries" in data: if "entries" in data:
entries = data.get("entries", []) entries = data.get("entries", [])
if not len(entries): if not len(entries):
logger.info("YoutubeDLArchiver could not find any video") logger.info("GenericExtractor could not find any video")
return False return False
else: else:
entries = [data] entries = [data]
@@ -407,9 +407,9 @@ class GenericExtractor(Extractor):
logger.error(f"Error loading subtitle file {val.get('filepath')}: {e}") logger.error(f"Error loading subtitle file {val.get('filepath')}: {e}")
result.add_media(new_media) result.add_media(new_media)
except Exception as e: except Exception as e:
logger.error(f"Error processing entry {entry}: {e}") logger.error(f"Error processing entry {str(entry)[:256]}: {e} {traceback.format_exc()}")
if not len(result.media): if not len(result.media):
logger.info(f"No media found for entry {entry}, skipping.") logger.info(f"No media found for entry {str(entry)[:256]}, skipping.")
return False return False
return self.add_metadata(data, info_extractor, url, result) return self.add_metadata(data, info_extractor, url, result)
@@ -503,6 +503,9 @@ class GenericExtractor(Extractor):
try: try:
result = self.get_metadata_for_post(info_extractor, url, ydl) result = self.get_metadata_for_post(info_extractor, url, ydl)
except (yt_dlp.utils.DownloadError, yt_dlp.utils.ExtractorError) as post_e: except (yt_dlp.utils.DownloadError, yt_dlp.utils.ExtractorError) as post_e:
if "NSFW tweet requires authentication." in str(post_e):
logger.warning(str(post_e))
return False
logger.error("Error downloading metadata for post: {error}", error=str(post_e)) logger.error("Error downloading metadata for post: {error}", error=str(post_e))
return False return False
except Exception as generic_e: except Exception as generic_e:
@@ -514,7 +517,7 @@ class GenericExtractor(Extractor):
) )
return False return False
if result: if result and not result.is_success():
extractor_name = "yt-dlp" extractor_name = "yt-dlp"
if info_extractor: if info_extractor:
extractor_name += f"_{info_extractor.ie_key()}" extractor_name += f"_{info_extractor.ie_key()}"
@@ -526,7 +529,7 @@ class GenericExtractor(Extractor):
return result return result
def download(self, item: Metadata) -> Metadata: def download(self, item: Metadata, skip_proxy: bool = False) -> Metadata:
url = item.get_url() url = item.get_url()
# TODO: this is a temporary hack until this issue is closed: https://github.com/yt-dlp/yt-dlp/issues/11025 # TODO: this is a temporary hack until this issue is closed: https://github.com/yt-dlp/yt-dlp/issues/11025
@@ -534,6 +537,16 @@ class GenericExtractor(Extractor):
url = url.replace("https://ya.ru", "https://yandex.ru") url = url.replace("https://ya.ru", "https://yandex.ru")
item.set("replaced_url", url) item.set("replaced_url", url)
# proxy_on_failure_only logic
if self.proxy and self.proxy_on_failure_only and not skip_proxy:
# when proxy_on_failure_only is True, we first try to download without a proxy and only continue with execution if that fails
try:
if without_proxy := self.download(item, skip_proxy=True):
logger.info("Downloaded successfully without proxy.")
return without_proxy
except Exception:
logger.debug("Download without proxy failed, trying with proxy...")
ydl_options = [ ydl_options = [
"-o", "-o",
os.path.join(self.tmp_dir, "%(id)s.%(ext)s"), os.path.join(self.tmp_dir, "%(id)s.%(ext)s"),
@@ -547,7 +560,7 @@ class GenericExtractor(Extractor):
] ]
# proxy handling # proxy handling
if self.proxy: if self.proxy and not skip_proxy:
ydl_options.extend(["--proxy", self.proxy]) ydl_options.extend(["--proxy", self.proxy])
# max_downloads handling # max_downloads handling
@@ -560,17 +573,17 @@ class GenericExtractor(Extractor):
# order of importance: username/password -> api_key -> cookie -> cookies_from_browser -> cookies_file # order of importance: username/password -> api_key -> cookie -> cookies_from_browser -> cookies_file
if auth: if auth:
if "username" in auth and "password" in auth: if "username" in auth and "password" in auth:
logger.debug(f"Using provided auth username and password for {url}") logger.debug("Using provided auth username and password")
ydl_options.extend(("--username", auth["username"])) ydl_options.extend(("--username", auth["username"]))
ydl_options.extend(("--password", auth["password"])) ydl_options.extend(("--password", auth["password"]))
elif "cookie" in auth: elif "cookie" in auth:
logger.debug(f"Using provided auth cookie for {url}") logger.debug("Using provided auth cookie")
yt_dlp.utils.std_headers["cookie"] = auth["cookie"] yt_dlp.utils.std_headers["cookie"] = auth["cookie"]
elif "cookies_from_browser" in auth: elif "cookies_from_browser" in auth:
logger.debug(f"Using extracted cookies from browser {auth['cookies_from_browser']} for {url}") logger.debug(f"Using extracted cookies from browser {auth['cookies_from_browser']}")
ydl_options.extend(("--cookies-from-browser", auth["cookies_from_browser"])) ydl_options.extend(("--cookies-from-browser", auth["cookies_from_browser"]))
elif "cookies_file" in auth: elif "cookies_file" in auth:
logger.debug(f"Using cookies from file {auth['cookies_file']} for {url}") logger.debug(f"Using cookies from file {auth['cookies_file']}")
ydl_options.extend(("--cookies", auth["cookies_file"])) ydl_options.extend(("--cookies", auth["cookies_file"]))
# Applying user-defined extractor_args # Applying user-defined extractor_args
@@ -584,7 +597,7 @@ class GenericExtractor(Extractor):
ydl_options.extend(["--extractor-args", f"{key}:{arg_str}"]) ydl_options.extend(["--extractor-args", f"{key}:{arg_str}"])
if self.ytdlp_args: if self.ytdlp_args:
logger.debug("Adding additional ytdlp arguments: {self.ytdlp_args}") logger.debug(f"Adding additional ytdlp arguments: {self.ytdlp_args}")
ydl_options += self.ytdlp_args.split(" ") ydl_options += self.ytdlp_args.split(" ")
*_, validated_options = yt_dlp.parse_options(ydl_options) *_, validated_options = yt_dlp.parse_options(ydl_options)
@@ -592,9 +605,9 @@ class GenericExtractor(Extractor):
validated_options validated_options
) # allsubtitles and subtitleslangs not working as expected, so default lang is always "en" ) # allsubtitles and subtitleslangs not working as expected, so default lang is always "en"
result: Metadata = None
for info_extractor in self.suitable_extractors(url): for info_extractor in self.suitable_extractors(url):
result = self.download_for_extractor(info_extractor, url, ydl) local_result: Metadata = self.download_for_extractor(info_extractor, url, ydl)
if result: if local_result:
return result result = result.merge(local_result) if result else local_result
return result if result else False
return False

View File

@@ -1,5 +1,6 @@
import re
import requests import requests
from loguru import logger from auto_archiver.utils.custom_logger import logger
from yt_dlp.extractor.tiktok import TikTokIE, TikTokLiveIE, TikTokVMIE, TikTokUserIE from yt_dlp.extractor.tiktok import TikTokIE, TikTokLiveIE, TikTokVMIE, TikTokUserIE
@@ -14,70 +15,109 @@ class Tiktok(GenericDropin):
It's useful for capturing content that requires a login, like sensitive content. It's useful for capturing content that requires a login, like sensitive content.
""" """
# Regex pattern to match TikTok photo post URLs
PHOTO_URL_REGEX = r"https?://(?:www\.)?tiktok\.com/@[\w\.-]+/photo/\d+"
TIKWM_ENDPOINT = "https://www.tikwm.com/api/?url={url}" TIKWM_ENDPOINT = "https://www.tikwm.com/api/?url={url}"
def suitable(self, url, info_extractor) -> bool: def suitable(self, url, info_extractor) -> bool:
"""This dropin (which uses Tikvm) is suitable for *all* Tiktok type URLs - videos, lives, VMs, and users. """This dropin (which uses Tikvm) is suitable for *all* Tiktok type URLs - videos, lives, VMs, and users.
Return the 'suitable' method from the TikTokIE class.""" Return the 'suitable' method from the TikTokIE class."""
return any(extractor().suitable(url) for extractor in (TikTokIE, TikTokLiveIE, TikTokVMIE, TikTokUserIE)) return any(extractor().suitable(url) for extractor in (TikTokIE, TikTokLiveIE, TikTokVMIE, TikTokUserIE)) or (
re.match(self.PHOTO_URL_REGEX, url) is not None
)
def extract_post(self, url: str, ie_instance): def extract_post(self, url: str, ie_instance):
logger.debug(f"Using Tikwm API to attempt to download tiktok video from {url=}") logger.debug("Using Tikwm API to attempt to download tiktok video")
endpoint = self.TIKWM_ENDPOINT.format(url=url) endpoint = self.TIKWM_ENDPOINT.format(url=url)
r = requests.get(endpoint) r = requests.get(endpoint)
if r.status_code != 200: if r.status_code != 200:
raise ValueError(f"unexpected status code '{r.status_code}' from tikwm.com for {url=}:") raise ValueError(f"Unexpected status code '{r.status_code}' from tikwm.com")
try: try:
json_response = r.json() json_response = r.json()
except ValueError: except ValueError:
raise ValueError(f"failed to parse JSON response from tikwm.com for {url=}") raise ValueError("Failed to parse JSON response from tikwm.com")
if not json_response.get("msg") == "success" or not (api_data := json_response.get("data", {})): if not json_response.get("msg") == "success" or not (api_data := json_response.get("data", {})):
raise ValueError(f"failed to get a valid response from tikwm.com for {url=}: {repr(json_response)}") raise ValueError(f"Unable to download with tikwm.com: {repr(json_response)}")
# tries to get the non-watermarked version first # tries to get the non-watermarked version first
video_url = api_data.pop("play", api_data.pop("wmplay", None)) play_url = api_data.pop("play", api_data.pop("wmplay", None))
if not video_url: if play_url and "mime_type=audio" in play_url:
raise ValueError(f"no valid video URL found in response from tikwm.com for {url=}") play_url = None
if play_url:
api_data["video_url"] = video_url api_data["video_url"] = play_url
return api_data return api_data
def keys_to_clean(self, video_data: dict, info_extractor): def keys_to_clean(self, video_data: dict, info_extractor):
return ["video_url", "title", "create_time", "author", "cover", "origin_cover", "ai_dynamic_cover", "duration"] return [
"video_url",
"title",
"create_time",
"author",
"cover",
"origin_cover",
"ai_dynamic_cover",
"duration",
"size",
"wm_size",
"music",
"music_info",
"play_count",
"digg_count",
"comment_count",
"share_count",
"download_count",
"collect_count",
"anchors",
"anchors_extras",
"is_ad",
"commerce_info",
"commercial_video_info",
"item_comment_settings",
"mentioned_users",
] # all of these will be added via api_data in a single metadata field vs individual ones in the generic extractor
def create_metadata(self, post: dict, ie_instance, archiver, url): def create_metadata(self, post: dict, ie_instance, archiver, url):
# prepare result, start by downloading video # prepare result, start by downloading video
result = Metadata() result = Metadata()
video_url = post.pop("video_url") is_success = False
# get the cover if possible # get the cover if possible
cover_url = post.pop("origin_cover", post.pop("cover", post.pop("ai_dynamic_cover", None))) cover_url = post.pop("origin_cover", post.pop("cover", post.pop("ai_dynamic_cover", None)))
if cover_url and (cover_downloaded := archiver.download_from_url(cover_url)): if cover_url and (cover_downloaded := archiver.download_from_url(cover_url)):
result.add_media(Media(cover_downloaded)) result.add_media(Media(cover_downloaded))
# get the video or fail for image_url in post.pop("images", []):
video_downloaded = archiver.download_from_url(video_url, f"vid_{post.get('id', '')}") if image_downloaded := archiver.download_from_url(image_url):
if not video_downloaded: result.add_media(Media(image_downloaded))
logger.error(f"failed to download video from {video_url}") is_success = True # this is an images post and we got it/them
return False
video_media = Media(video_downloaded) # get the video if present, could be an image post
if duration := post.get("duration", None): if video_url := post.pop("video_url", None):
video_media.set("duration", duration) video_downloaded = archiver.download_from_url(video_url, f"vid_{post.get('id', '')}")
result.add_media(video_media) if not video_downloaded:
logger.error("Failed to download video")
return False
video_media = Media(video_downloaded)
if duration := post.pop("duration", None):
video_media.set("duration", duration)
result.add_media(video_media)
is_success = True # this is a video post and we got it
# add remaining metadata # add remaining metadata
result.set_title(post.get("title", "")) result.set_title(post.pop("title", ""))
if created_at := post.get("create_time", None): if created_at := post.pop("create_time", None):
result.set_timestamp(datetime.fromtimestamp(created_at, tz=timezone.utc)) result.set_timestamp(datetime.fromtimestamp(created_at, tz=timezone.utc))
if author := post.get("author", None): if author := post.pop("author", None):
result.set("author", author) result.set("author", author)
result.set("api_data", post) result.set("api_data", {k: v for k, v in post.items() if v})
if is_success:
result.success("yt-dlp_TikTok")
else:
raise ValueError("Unable to download any media from TikTok post, possibly deleted or private.")
return result return result

View File

@@ -1,7 +1,7 @@
import re import re
import mimetypes import mimetypes
from loguru import logger from auto_archiver.utils.custom_logger import logger
from slugify import slugify from slugify import slugify
from auto_archiver.core.metadata import Metadata, Media from auto_archiver.core.metadata import Metadata, Media

View File

@@ -10,11 +10,12 @@ The filtered rows are processed into `Metadata` objects.
""" """
import os import os
import traceback
from typing import Tuple, Union, Iterator from typing import Tuple, Union, Iterator
from urllib.parse import quote from urllib.parse import quote
import gspread import gspread
from loguru import logger from auto_archiver.utils.custom_logger import logger
from slugify import slugify from slugify import slugify
from retrying import retry from retrying import retry
@@ -31,28 +32,39 @@ class GsheetsFeederDB(Feeder, Database):
if not self.sheet and not self.sheet_id: if not self.sheet and not self.sheet_id:
raise ValueError("You need to define either a 'sheet' name or a 'sheet_id' in your manifest.") raise ValueError("You need to define either a 'sheet' name or a 'sheet_id' in your manifest.")
def open_sheet(self): @retry(
wait_exponential_multiplier=1,
stop_max_attempt_number=6,
)
def open_sheet(self) -> gspread.Spreadsheet:
if self.sheet: if self.sheet:
return self.gsheets_client.open(self.sheet) return self.gsheets_client.open(self.sheet)
else: else:
return self.gsheets_client.open_by_key(self.sheet_id) return self.gsheets_client.open_by_key(self.sheet_id)
def __iter__(self) -> Iterator[Metadata]: @retry(
sh = self.open_sheet() wait_exponential_multiplier=1,
for ii, worksheet in enumerate(sh.worksheets()): stop_max_attempt_number=6,
if not self.should_process_sheet(worksheet.title): )
logger.debug(f"SKIPPED worksheet '{worksheet.title}' due to allow/block rules") def enumerate_sheets(self, sheet) -> Iterator[gspread.Worksheet]:
continue for worksheet in sheet.worksheets():
logger.info(f"Opening worksheet {ii=}: {worksheet.title=} header={self.header}") yield worksheet
gw = GWorksheet(worksheet, header_row=self.header, columns=self.columns)
if len(missing_cols := self.missing_required_columns(gw)):
logger.debug(
f"SKIPPED worksheet '{worksheet.title}' due to missing required column(s) for {missing_cols}"
)
continue
# process and yield metadata here: def __iter__(self) -> Iterator[Metadata]:
yield from self._process_rows(gw) spreadsheet = self.open_sheet()
for worksheet in self.enumerate_sheets(spreadsheet):
with logger.contextualize(worksheet=f"{spreadsheet.title}:{worksheet.title}"):
if not self.should_process_sheet(worksheet.title):
logger.debug("Skipped worksheet due to allow/block rules")
continue
logger.info(f"Opening worksheet header={self.header}")
gw = GWorksheet(worksheet, header_row=self.header, columns=self.columns)
if len(missing_cols := self.missing_required_columns(gw)):
logger.debug(f"Skipped worksheet due to missing required column(s) for {missing_cols}")
continue
# process and yield metadata here:
yield from self._process_rows(gw)
logger.info(f"Finished worksheet {worksheet.title}") logger.info(f"Finished worksheet {worksheet.title}")
def _process_rows(self, gw: GWorksheet): def _process_rows(self, gw: GWorksheet):
@@ -69,7 +81,9 @@ class GsheetsFeederDB(Feeder, Database):
# All checks done - archival process starts here # All checks done - archival process starts here
m = Metadata().set_url(url) m = Metadata().set_url(url)
self._set_context(m, gw, row) self._set_context(m, gw, row)
yield m
with logger.contextualize(row=row):
yield m
def _set_context(self, m: Metadata, gw: GWorksheet, row: int) -> Metadata: def _set_context(self, m: Metadata, gw: GWorksheet, row: int) -> Metadata:
# TODO: Check folder value not being recognised # TODO: Check folder value not being recognised
@@ -99,16 +113,16 @@ class GsheetsFeederDB(Feeder, Database):
return missing return missing
def started(self, item: Metadata) -> None: def started(self, item: Metadata) -> None:
logger.info(f"STARTED {item}") logger.info("STARTED")
gw, row = self._retrieve_gsheet(item) gw, row = self._retrieve_gsheet(item)
gw.set_cell(row, "status", "Archive in progress") gw.set_cell(row, "status", "Archive in progress")
def failed(self, item: Metadata, reason: str) -> None: def failed(self, item: Metadata, reason: str) -> None:
logger.error(f"FAILED {item}") logger.error("FAILED")
self._safe_status_update(item, f"Archive failed {reason}") self._safe_status_update(item, f"Archive failed {reason}")
def aborted(self, item: Metadata) -> None: def aborted(self, item: Metadata) -> None:
logger.warning(f"ABORTED {item}") logger.warning("ABORTED")
self._safe_status_update(item, "") self._safe_status_update(item, "")
def fetch(self, item: Metadata) -> Union[Metadata, bool]: def fetch(self, item: Metadata) -> Union[Metadata, bool]:
@@ -117,13 +131,13 @@ class GsheetsFeederDB(Feeder, Database):
def done(self, item: Metadata, cached: bool = False) -> None: def done(self, item: Metadata, cached: bool = False) -> None:
"""archival result ready - should be saved to DB""" """archival result ready - should be saved to DB"""
logger.success(f"DONE {item.get_url()}")
gw, row = self._retrieve_gsheet(item) gw, row = self._retrieve_gsheet(item)
# self._safe_status_update(item, 'done')
cell_updates = [] cell_updates = []
row_values = gw.get_row(row) row_values = gw.get_row(row)
logger.info("DONE")
def batch_if_valid(col, val, final_value=None): def batch_if_valid(col, val, final_value=None):
final_value = final_value or val final_value = final_value or val
try: try:
@@ -175,9 +189,7 @@ class GsheetsFeederDB(Feeder, Database):
) )
@retry( @retry(
wait_incrementing_start=1000, wait_exponential_multiplier=1,
wait_incrementing_increment=3000,
wait_incrementing_max=20_000,
stop_max_attempt_number=5, stop_max_attempt_number=5,
) )
def batch_set_cell_with_retry(gw, cell_updates: list): def batch_set_cell_with_retry(gw, cell_updates: list):
@@ -190,15 +202,13 @@ class GsheetsFeederDB(Feeder, Database):
gw, row = self._retrieve_gsheet(item) gw, row = self._retrieve_gsheet(item)
gw.set_cell(row, "status", new_status) gw.set_cell(row, "status", new_status)
except Exception as e: except Exception as e:
logger.debug(f"Unable to update sheet: {e}") logger.debug(f"Unable to update sheet: {e}: {traceback.format_exc()}")
def _retrieve_gsheet(self, item: Metadata) -> Tuple[GWorksheet, int]: def _retrieve_gsheet(self, item: Metadata) -> Tuple[GWorksheet, int]:
if gsheet := item.get_context("gsheet"): if gsheet := item.get_context("gsheet"):
gw: GWorksheet = gsheet.get("worksheet") gw: GWorksheet = gsheet.get("worksheet")
row: int = gsheet.get("row") row: int = gsheet.get("row")
elif self.sheet_id: elif self.sheet_id:
logger.error( logger.error("Unable to retrieve Gsheet, GsheetDB must be used alongside GsheetFeeder.")
f"Unable to retrieve Gsheet for {item.get_url()}, GsheetDB must be used alongside GsheetFeeder."
)
return gw, row return gw, row

View File

@@ -1,4 +1,5 @@
from gspread import utils from gspread import utils
from retrying import retry
class GWorksheet: class GWorksheet:
@@ -26,6 +27,10 @@ class GWorksheet:
"replaywebpage": "replaywebpage", "replaywebpage": "replaywebpage",
} }
@retry(
wait_exponential_multiplier=1,
stop_max_attempt_number=6,
)
def __init__(self, worksheet, columns=COLUMN_NAMES, header_row=1): def __init__(self, worksheet, columns=COLUMN_NAMES, header_row=1):
self.wks = worksheet self.wks = worksheet
self.columns = columns self.columns = columns

View File

@@ -9,7 +9,7 @@ making it suitable for handling large files efficiently.
""" """
import hashlib import hashlib
from loguru import logger from auto_archiver.utils.custom_logger import logger
from auto_archiver.core import Enricher from auto_archiver.core import Enricher
from auto_archiver.core import Metadata from auto_archiver.core import Metadata
@@ -22,8 +22,7 @@ class HashEnricher(Enricher):
""" """
def enrich(self, to_enrich: Metadata) -> None: def enrich(self, to_enrich: Metadata) -> None:
url = to_enrich.get_url() logger.debug(f"Calculating media hashes with algo={self.algorithm}")
logger.debug(f"calculating media hashes for {url=} (using {self.algorithm})")
for i, m in enumerate(to_enrich.media): for i, m in enumerate(to_enrich.media):
if len(hd := self.calculate_hash(m.filename)): if len(hd := self.calculate_hash(m.filename)):

View File

@@ -4,7 +4,7 @@ import os
import pathlib import pathlib
from jinja2 import Environment, FileSystemLoader from jinja2 import Environment, FileSystemLoader
from urllib.parse import quote from urllib.parse import quote
from loguru import logger from auto_archiver.utils.custom_logger import logger
import json import json
import base64 import base64
@@ -35,7 +35,7 @@ class HtmlFormatter(Formatter):
def format(self, item: Metadata) -> Media: def format(self, item: Metadata) -> Media:
url = item.get_url() url = item.get_url()
if item.is_empty(): if item.is_empty():
logger.debug(f"[SKIP] FORMAT there is no media or metadata to format: {url=}") logger.debug("Nothing to format, skipping")
return return
content = self.template.render( content = self.template.render(

View File

@@ -22,7 +22,7 @@
"full_profile_max_posts": { "full_profile_max_posts": {
"default": 0, "default": 0,
"type": "int", "type": "int",
"help": "Use to limit the number of posts to download when full_profile is true. 0 means no limit. limit is applied softly since posts are fetched in batch, once to: posts, tagged posts, and highlights", "help": "Use to limit the number of posts to download when full_profile is true or when a URL for multiple posts is passed (like /stories /highlights ...). 0 means no limit. when full_profile is true the order of downloaded content is stories -> posts -> tagged posts -> highlights, so a value of 10 could download 2 stories, 7 posts, 1 tagged posts, and 0 highlights.",
}, },
"minimize_json_output": { "minimize_json_output": {
"default": True, "default": True,

View File

@@ -8,11 +8,13 @@ data, reducing JSON output size, and handling large profiles.
""" """
import math
import re import re
from datetime import datetime from datetime import datetime
import traceback
import requests import requests
from loguru import logger from auto_archiver.utils.custom_logger import logger
from retrying import retry from retrying import retry
from tqdm import tqdm from tqdm import tqdm
@@ -35,17 +37,19 @@ class InstagramAPIExtractor(Extractor):
def setup(self) -> None: def setup(self) -> None:
if self.api_endpoint[-1] == "/": if self.api_endpoint[-1] == "/":
self.api_endpoint = self.api_endpoint[:-1] self.api_endpoint = self.api_endpoint[:-1]
self.full_profile_max_posts = int(self.full_profile_max_posts or 0)
if self.full_profile_max_posts == 0:
self.full_profile_max_posts = math.inf
def download(self, item: Metadata) -> Metadata: def download(self, item: Metadata) -> Metadata:
url = item.get_url() url = item.get_url()
url.replace("instagr.com", "instagram.com").replace("instagr.am", "instagram.com") url.replace("instagr.com", "instagram.com").replace("instagr.am", "instagram.com")
insta_matches = self.valid_url.findall(url) insta_matches = self.valid_url.findall(url)
logger.info(f"{insta_matches=}")
if not len(insta_matches) or len(insta_matches[0]) != 3: if not len(insta_matches) or len(insta_matches[0]) != 3:
return return
if len(insta_matches) > 1: if len(insta_matches) > 1:
logger.warning(f"Multiple instagram matches found in {url=}, using the first one") logger.debug("Multiple instagram matches found, using the first one")
return return
g1, g2, g3 = insta_matches[0][0], insta_matches[0][1], insta_matches[0][2] g1, g2, g3 = insta_matches[0][0], insta_matches[0][1], insta_matches[0][2]
if g1 == "": if g1 == "":
@@ -61,13 +65,13 @@ class InstagramAPIExtractor(Extractor):
return self.download_post(item, id=g3, context="story") return self.download_post(item, id=g3, context="story")
return self.download_stories(item, g2) return self.download_stories(item, g2)
else: else:
logger.warning(f"Unknown instagram regex group match {g1=} found in {url=}") logger.warning(f"Unknown instagram regex group match {g1=}")
return return
@retry(wait_random_min=1000, wait_random_max=3000, stop_max_attempt_number=5) @retry(wait_random_min=1000, wait_random_max=3000, stop_max_attempt_number=5)
def call_api(self, path: str, params: dict) -> dict: def call_api(self, path: str, params: dict) -> dict:
headers = {"accept": "application/json", "x-access-key": self.access_token} headers = {"accept": "application/json", "x-access-key": self.access_token}
logger.debug(f"calling {self.api_endpoint}/{path} with {params=}") logger.debug(f"Calling {self.api_endpoint}/{path} with {params=}")
return requests.get(f"{self.api_endpoint}/{path}", headers=headers, params=params).json() return requests.get(f"{self.api_endpoint}/{path}", headers=headers, params=params).json()
def cleanup_dict(self, d: dict | list) -> dict: def cleanup_dict(self, d: dict | list) -> dict:
@@ -97,65 +101,84 @@ class InstagramAPIExtractor(Extractor):
filename = self.download_from_url(pic_url) filename = self.download_from_url(pic_url)
result.add_media(Media(filename=filename), id="profile_picture") result.add_media(Media(filename=filename), id="profile_picture")
count_posts = 0
if self.full_profile: if self.full_profile:
user_id = user.get("pk") user_id = user.get("pk")
# download all stories # download all stories
try: try:
stories = self._download_stories_reusable(result, username) stories = self._download_stories_reusable(
result, username, max_to_download=self.full_profile_max_posts - count_posts
)
count_posts += len(stories)
result.set("#stories", len(stories)) result.set("#stories", len(stories))
except Exception as e: except Exception as e:
result.append("errors", f"Error downloading stories for {username}") result.append("errors", f"Error downloading stories for {username}")
logger.error(f"Error downloading stories for {username}: {e}") logger.error(f"Error downloading stories for {username}: {e} {traceback.format_exc()}")
# download all posts # download all posts
try: try:
self.download_all_posts(result, user_id) if count_posts < self.full_profile_max_posts:
count_posts += self.download_all_posts(
result, user_id, max_to_download=self.full_profile_max_posts - count_posts
)
except Exception as e: except Exception as e:
result.append("errors", f"Error downloading posts for {username}") result.append("errors", f"Error downloading posts for {username}")
logger.error(f"Error downloading posts for {username}: {e}") logger.error(f"Error downloading posts for {username}: {e} {traceback.format_exc()}")
# download all tagged # download all tagged
try: try:
self.download_all_tagged(result, user_id) if count_posts < self.full_profile_max_posts:
count_posts += self.download_all_tagged(
result, user_id, max_to_download=self.full_profile_max_posts - count_posts
)
except Exception as e: except Exception as e:
result.append("errors", f"Error downloading tagged posts for {username}") result.append("errors", f"Error downloading tagged posts for {username}")
logger.error(f"Error downloading tagged posts for {username}: {e}") logger.error(f"Error downloading tagged posts for {username}: {e} {traceback.format_exc()}")
# download all highlights # download all highlights
try: try:
self.download_all_highlights(result, username, user_id) if count_posts < self.full_profile_max_posts:
count_posts += self.download_all_highlights(
result, username, user_id, max_to_download=self.full_profile_max_posts - count_posts
)
except Exception as e: except Exception as e:
result.append("errors", f"Error downloading highlights for {username}") result.append("errors", f"Error downloading highlights for {username}")
logger.error(f"Error downloading highlights for {username}: {e}") logger.error(f"Error downloading highlights for {username}: {e} {traceback.format_exc()}")
result.set_url(url) # reset as scrape_item modifies it result.set_url(url) # reset as scrape_item modifies it
return result.success("insta profile") return result.success("insta profile")
def download_all_highlights(self, result, username, user_id): def download_all_highlights(self, result, username, user_id, max_to_download: int) -> int:
count_highlights = 0 count_highlights = 0
highlights = self.call_api("v1/user/highlights", {"user_id": user_id}) highlights = self.call_api("v1/user/highlights", {"user_id": user_id})
highlights = highlights[: min(max_to_download, len(highlights))] # newest to oldest
for h in highlights: for h in highlights:
try: try:
h_info = self._download_highlights_reusable(result, h.get("pk")) h_info = self._download_highlights_reusable(result, h.get("pk"), max_to_download=max_to_download)
count_highlights += len(h_info.get("items", [])) count_highlights += len(h_info.get("items", []))
except Exception as e: except Exception as e:
result.append( result.append(
"errors", "errors",
f"Error downloading highlight id{h.get('pk')} for {username}", f"Error downloading highlight id{h.get('pk')} for {username}",
) )
logger.error(f"Error downloading highlight id{h.get('pk')} for {username}: {e}") logger.error(
if self.full_profile_max_posts and count_highlights >= self.full_profile_max_posts: f"Error downloading highlight id{h.get('pk')} for {username}: {e} {traceback.format_exc()}"
logger.info(f"HIGHLIGHTS reached full_profile_max_posts={self.full_profile_max_posts}") )
if count_highlights >= max_to_download:
logger.debug(f"HIGHLIGHTS reached max_to_download={self.full_profile_max_posts}")
break break
result.set("#highlights", count_highlights) result.set("#highlights", count_highlights)
return count_highlights
def download_post(self, result: Metadata, code: str = None, id: str = None, context: str = None) -> Metadata: def download_post(self, result: Metadata, code: str = None, id: str = None, context: str = "") -> Metadata:
if id: if id:
post = self.call_api("v1/media/by/id", {"id": id}) post = self.call_api("v1/media/by/id", {"id": id})
else: else:
post = self.call_api("v1/media/by/code", {"code": code}) post = self.call_api("v1/media/by/code", {"code": code})
assert post, f"Post {id or code} not found" assert post, f"Post {id or code} not found"
result.set(f"{context}_data", post)
if caption_text := post.get("caption_text"): if caption_text := post.get("caption_text"):
result.set_title(caption_text) result.set_title(caption_text)
@@ -166,13 +189,13 @@ class InstagramAPIExtractor(Extractor):
return result.success(f"insta {context or 'post'}") return result.success(f"insta {context or 'post'}")
def download_highlights(self, result: Metadata, id: str) -> Metadata: def download_highlights(self, result: Metadata, id: str) -> Metadata:
h_info = self._download_highlights_reusable(result, id) h_info = self._download_highlights_reusable(result, id, self.full_profile_max_posts)
items = len(h_info.get("items", [])) items = len(h_info.get("items", []))
del h_info["items"] del h_info["items"]
result.set_title(h_info.get("title")).set("data", h_info).set("#reels", items) result.set_title(h_info.get("title")).set("data", h_info).set("#reels", items)
return result.success("insta highlights") return result.success("insta highlights")
def _download_highlights_reusable(self, result: Metadata, id: str) -> dict: def _download_highlights_reusable(self, result: Metadata, id: str, max_to_download: int) -> dict:
full_h = self.call_api("v2/highlight/by/id", {"id": id}) full_h = self.call_api("v2/highlight/by/id", {"id": id})
h_info = full_h.get("response", {}).get("reels", {}).get(f"highlight:{id}") h_info = full_h.get("response", {}).get("reels", {}).get(f"highlight:{id}")
assert h_info, f"Highlight {id} not found: {full_h=}" assert h_info, f"Highlight {id} not found: {full_h=}"
@@ -182,38 +205,39 @@ class InstagramAPIExtractor(Extractor):
result.add_media(Media(filename=filename), id=f"cover_media highlight {id}") result.add_media(Media(filename=filename), id=f"cover_media highlight {id}")
items = h_info.get("items", [])[::-1] # newest to oldest items = h_info.get("items", [])[::-1] # newest to oldest
items = items[: min(max_to_download, len(items))]
for h in tqdm(items, desc="downloading highlights", unit="highlight"): for h in tqdm(items, desc="downloading highlights", unit="highlight"):
try: try:
self.scrape_item(result, h, "highlight") self.scrape_item(result, h, "highlight")
except Exception as e: except Exception as e:
result.append("errors", f"Error downloading highlight {h.get('id')}") result.append("errors", f"Error downloading highlight {h.get('id')}")
logger.error(f"Error downloading highlight, skipping {h.get('id')}: {e}") logger.error(f"Error downloading highlight, skipping {h.get('id')}: {e} {traceback.format_exc()}")
return h_info return h_info
def download_stories(self, result: Metadata, username: str) -> Metadata: def download_stories(self, result: Metadata, username: str) -> Metadata:
now = datetime.now().strftime("%Y-%m-%d_%H-%M") now = datetime.now().strftime("%Y-%m-%d_%H-%M")
stories = self._download_stories_reusable(result, username) stories = self._download_stories_reusable(result, username, max_to_download=self.full_profile_max_posts)
if stories == []: if stories == []:
return result.success("insta no story") return result.success("insta no story")
result.set_title(f"stories {username} at {now}").set("#stories", len(stories)) result.set_title(f"stories {username} at {now}").set("#stories", len(stories))
return result.success(f"insta stories {now}") return result.success(f"insta stories {now}")
def _download_stories_reusable(self, result: Metadata, username: str) -> list[dict]: def _download_stories_reusable(self, result: Metadata, username: str, max_to_download: int) -> list[dict]:
stories = self.call_api("v1/user/stories/by/username", {"username": username}) stories = self.call_api("v1/user/stories/by/username", {"username": username})
if not stories or not len(stories): if not stories or not len(stories):
return [] return []
stories = stories[::-1] # newest to oldest stories = stories[::-1][: min(max_to_download, len(stories))] # newest to oldest
for s in tqdm(stories, desc="downloading stories", unit="story"): for s in tqdm(stories, desc="downloading stories", unit="story"):
try: try:
self.scrape_item(result, s, "story") self.scrape_item(result, s, "story")
except Exception as e: except Exception as e:
result.append("errors", f"Error downloading story {s.get('id')}") result.append("errors", f"Error downloading story {s.get('id')}")
logger.error(f"Error downloading story, skipping {s.get('id')}: {e}") logger.error(f"Error downloading story, skipping {s.get('id')}: {e} {traceback.format_exc()}")
return stories return stories
def download_all_posts(self, result: Metadata, user_id: str): def download_all_posts(self, result: Metadata, user_id: str, max_to_download: int) -> int:
end_cursor = None end_cursor = None
pbar = tqdm(desc="downloading posts") pbar = tqdm(desc="downloading posts")
@@ -223,22 +247,23 @@ class InstagramAPIExtractor(Extractor):
if not posts or not isinstance(posts, list) or len(posts) != 2: if not posts or not isinstance(posts, list) or len(posts) != 2:
break break
posts, end_cursor = posts[0], posts[1] posts, end_cursor = posts[0], posts[1]
logger.info(f"parsing {len(posts)} posts, next {end_cursor=}") posts = posts[: min(max_to_download, len(posts))]
logger.info(f"Parsing {len(posts)} posts, next {end_cursor=} {post_count=} {max_to_download=}")
for p in posts: for p in posts:
try: try:
self.scrape_item(result, p, "post") self.scrape_item(result, p, "post")
except Exception as e: except Exception as e:
result.append("errors", f"Error downloading post {p.get('id')}") result.append("errors", f"Error downloading post {p.get('id')}")
logger.error(f"Error downloading post, skipping {p.get('id')}: {e}") logger.error(f"Error downloading post, skipping {p.get('id')}: {e} {traceback.format_exc()}")
pbar.update(1) pbar.update(1)
post_count += 1 post_count += 1
if self.full_profile_max_posts and post_count >= self.full_profile_max_posts: if post_count >= max_to_download:
logger.info(f"POSTS reached full_profile_max_posts={self.full_profile_max_posts}") logger.info(f"POSTS reached max_to_download={self.full_profile_max_posts}")
break break
result.set("#posts", post_count) result.set("#posts", post_count)
return post_count
def download_all_tagged(self, result: Metadata, user_id: str): def download_all_tagged(self, result: Metadata, user_id: str, max_to_download: int) -> int:
next_page_id = "" next_page_id = ""
pbar = tqdm(desc="downloading tagged posts") pbar = tqdm(desc="downloading tagged posts")
@@ -250,22 +275,23 @@ class InstagramAPIExtractor(Extractor):
break break
next_page_id = resp.get("next_page_id") next_page_id = resp.get("next_page_id")
logger.info(f"parsing {len(posts)} tagged posts, next {next_page_id=}") logger.info(f"Parsing {len(posts)} tagged posts, next {next_page_id=}")
posts = posts[: min(max_to_download, len(posts))]
for p in posts: for p in posts:
try: try:
self.scrape_item(result, p, "tagged") self.scrape_item(result, p, "tagged")
except Exception as e: except Exception as e:
result.append("errors", f"Error downloading tagged post {p.get('id')}") result.append("errors", f"Error downloading tagged post {p.get('id')}")
logger.error(f"Error downloading tagged post, skipping {p.get('id')}: {e}") logger.error(f"Error downloading tagged post, skipping {p.get('id')}: {e} {traceback.format_exc()}")
pbar.update(1) pbar.update(1)
tagged_count += 1 tagged_count += 1
if self.full_profile_max_posts and tagged_count >= self.full_profile_max_posts: if tagged_count >= max_to_download:
logger.info(f"TAGS reached full_profile_max_posts={self.full_profile_max_posts}") logger.info(f"TAGS reached max_to_download={self.full_profile_max_posts}")
break break
result.set("#tagged", tagged_count) result.set("#tagged", tagged_count)
return tagged_count
### reusable parsing utils below # reusable parsing utils below
def scrape_item(self, result: Metadata, item: dict, context: str = None) -> dict: def scrape_item(self, result: Metadata, item: dict, context: str = None) -> dict:
""" """

View File

@@ -7,8 +7,9 @@ highlights, and tagged posts. Authentication is required via username/password o
import re import re
import os import os
import shutil import shutil
import traceback
import instaloader import instaloader
from loguru import logger from auto_archiver.utils.custom_logger import logger
from auto_archiver.core import Extractor from auto_archiver.core import Extractor
from auto_archiver.core import Metadata from auto_archiver.core import Metadata
@@ -29,8 +30,9 @@ class InstagramExtractor(Extractor):
# TODO: links to stories # TODO: links to stories
def setup(self) -> None: def setup(self) -> None:
logger.warning("Instagram Extractor is not actively maintained, and may not work as expected.") logger.warning(
logger.warning("Please consider using the Instagram Tbot Extractor or Instagram API Extractor instead.") "Instagram Extractor is not actively maintained, and may not work as expected.\nPlease consider using the Instagram Tbot Extractor or Instagram API Extractor instead."
)
self.insta = instaloader.Instaloader( self.insta = instaloader.Instaloader(
download_geotags=True, download_geotags=True,
@@ -43,8 +45,7 @@ class InstagramExtractor(Extractor):
self.insta.load_session_from_file(self.username, self.session_file) self.insta.load_session_from_file(self.username, self.session_file)
except Exception: except Exception:
try: try:
logger.debug("Session file failed", exc_info=True) logger.info("No valid session file found - Attempting login with username and password.")
logger.info("No valid session file found - Attempting login with use and password.")
self.insta.login(self.username, self.password) self.insta.login(self.username, self.password)
self.insta.save_session_to_file(self.session_file) self.insta.save_session_to_file(self.session_file)
except Exception as e: except Exception as e:
@@ -79,7 +80,7 @@ class InstagramExtractor(Extractor):
return result return result
def download_post(self, url: str, post_id: str) -> Metadata: def download_post(self, url: str, post_id: str) -> Metadata:
logger.debug(f"Instagram {post_id=} detected in {url=}") logger.debug(f"Instagram {post_id=} detected")
post = instaloader.Post.from_shortcode(self.insta.context, post_id) post = instaloader.Post.from_shortcode(self.insta.context, post_id)
if self.insta.download_post(post, target=post.owner_username): if self.insta.download_post(post, target=post.owner_username):
@@ -87,7 +88,7 @@ class InstagramExtractor(Extractor):
def download_profile(self, url: str, username: str) -> Metadata: def download_profile(self, url: str, username: str) -> Metadata:
# gets posts, posts where username is tagged, igtv postss, stories, and highlights # gets posts, posts where username is tagged, igtv postss, stories, and highlights
logger.debug(f"Instagram {username=} detected in {url=}") logger.debug(f"Instagram {username=} detected")
profile = instaloader.Profile.from_username(self.insta.context, username) profile = instaloader.Profile.from_username(self.insta.context, username)
try: try:
@@ -95,27 +96,27 @@ class InstagramExtractor(Extractor):
try: try:
self.insta.download_post(post, target=f"profile_post_{post.owner_username}") self.insta.download_post(post, target=f"profile_post_{post.owner_username}")
except Exception as e: except Exception as e:
logger.error(f"Failed to download post: {post.shortcode}: {e}") logger.error(f"Failed to download post: {post.shortcode}: {e} {traceback.format_exc()}")
except Exception as e: except Exception as e:
logger.error(f"Failed profile.get_posts: {e}") logger.error(f"Failed profile.get_posts: {e}: {traceback.format_exc()}")
try: try:
for post in profile.get_tagged_posts(): for post in profile.get_tagged_posts():
try: try:
self.insta.download_post(post, target=f"tagged_post_{post.owner_username}") self.insta.download_post(post, target=f"tagged_post_{post.owner_username}")
except Exception as e: except Exception as e:
logger.error(f"Failed to download tagged post: {post.shortcode}: {e}") logger.error(f"Failed to download tagged post: {post.shortcode}: {e} {traceback.format_exc()}")
except Exception as e: except Exception as e:
logger.error(f"Failed profile.get_tagged_posts: {e}") logger.error(f"Failed profile.get_tagged_posts: {e} {traceback.format_exc()}")
try: try:
for post in profile.get_igtv_posts(): for post in profile.get_igtv_posts():
try: try:
self.insta.download_post(post, target=f"igtv_post_{post.owner_username}") self.insta.download_post(post, target=f"igtv_post_{post.owner_username}")
except Exception as e: except Exception as e:
logger.error(f"Failed to download igtv post: {post.shortcode}: {e}") logger.error(f"Failed to download igtv post: {post.shortcode}: {e} {traceback.format_exc()}")
except Exception as e: except Exception as e:
logger.error(f"Failed profile.get_igtv_posts: {e}") logger.error(f"Failed profile.get_igtv_posts: {e} {traceback.format_exc()}")
try: try:
for story in self.insta.get_stories([profile.userid]): for story in self.insta.get_stories([profile.userid]):
@@ -123,9 +124,9 @@ class InstagramExtractor(Extractor):
try: try:
self.insta.download_storyitem(item, target=f"story_item_{story.owner_username}") self.insta.download_storyitem(item, target=f"story_item_{story.owner_username}")
except Exception as e: except Exception as e:
logger.error(f"Failed to download story item: {item}: {e}") logger.error(f"Failed to download story item: {item}: {e} {traceback.format_exc()}")
except Exception as e: except Exception as e:
logger.error(f"Failed get_stories: {e}") logger.error(f"Failed get_stories: {e} {traceback.format_exc()}")
try: try:
for highlight in self.insta.get_highlights(profile.userid): for highlight in self.insta.get_highlights(profile.userid):
@@ -133,9 +134,9 @@ class InstagramExtractor(Extractor):
try: try:
self.insta.download_storyitem(item, target=f"highlight_item_{highlight.owner_username}") self.insta.download_storyitem(item, target=f"highlight_item_{highlight.owner_username}")
except Exception as e: except Exception as e:
logger.error(f"Failed to download highlight item: {item}: {e}") logger.error(f"Failed to download highlight item: {item}: {e} {traceback.format_exc()}")
except Exception as e: except Exception as e:
logger.error(f"Failed get_highlights: {e}") logger.error(f"Failed get_highlights: {e} {traceback.format_exc()}")
return self.process_downloads(url, f"@{username}", profile._asdict(), None) return self.process_downloads(url, f"@{username}", profile._asdict(), None)
@@ -158,4 +159,4 @@ class InstagramExtractor(Extractor):
return result.success("instagram") return result.success("instagram")
except Exception as e: except Exception as e:
logger.error(f"Could not fetch instagram post {url} due to: {e}") logger.error(f"Could not fetch instagram post due to: {e} {traceback.format_exc()}")

View File

@@ -12,7 +12,7 @@ import shutil
import time import time
from sqlite3 import OperationalError from sqlite3 import OperationalError
from loguru import logger from auto_archiver.utils.custom_logger import logger
from telethon.sync import TelegramClient from telethon.sync import TelegramClient
from auto_archiver.core import Extractor from auto_archiver.core import Extractor
@@ -32,7 +32,7 @@ class InstagramTbotExtractor(Extractor):
1. makes a copy of session_file that is removed in cleanup 1. makes a copy of session_file that is removed in cleanup
2. checks if the session file is valid 2. checks if the session file is valid
""" """
logger.info(f"SETUP {self.name} checking login...") logger.debug(f"SETUP {self.name} checking login...")
self._prepare_session_file() self._prepare_session_file()
self._initialize_telegram_client() self._initialize_telegram_client()
@@ -58,10 +58,10 @@ class InstagramTbotExtractor(Extractor):
"If you do, disable at least one of the archivers for the first-time setup of the telethon session: {e}" "If you do, disable at least one of the archivers for the first-time setup of the telethon session: {e}"
) )
with self.client.start(): with self.client.start():
logger.info(f"SETUP {self.name} login works.") logger.debug(f"SETUP {self.name} login works.")
def cleanup(self) -> None: def cleanup(self) -> None:
logger.info(f"CLEANUP {self.name}.") logger.debug(f"CLEANUP {self.name}.")
session_file_name = self.session_file + ".session" session_file_name = self.session_file + ".session"
if os.path.exists(session_file_name): if os.path.exists(session_file_name):
os.remove(session_file_name) os.remove(session_file_name)
@@ -79,17 +79,17 @@ class InstagramTbotExtractor(Extractor):
# This may be outdated and replaced by the below message, but keeping until confirmed # This may be outdated and replaced by the below message, but keeping until confirmed
if "You must enter a URL to a post" in message: if "You must enter a URL to a post" in message:
logger.debug(f"invalid link {url=} for {self.name}: {message}") logger.debug(f"Invalid link for {self.name}: {message}")
return False return False
if "Media not found or unavailable" in message: if "Media not found or unavailable" in message:
logger.debug(f"No media found for link {url=} for {self.name}: {message}") logger.debug(f"No media found for {self.name}: {message}")
return False return False
if message: if message:
result.set_content(message).set_title(message[:128]) result.set_content(message).set_title(message[:128])
elif result.is_empty(): elif result.is_empty():
logger.debug(f"No media found for link {url=} for {self.name}: {message}") logger.debug(f"No media found for {self.name}: {message}")
return False return False
return result.success("insta-via-bot") return result.success("insta-via-bot")

View File

@@ -1,5 +1,5 @@
import json import json
from loguru import logger from auto_archiver.utils.custom_logger import logger
import os import os
from auto_archiver.core import Enricher from auto_archiver.core import Enricher
@@ -8,9 +8,7 @@ from auto_archiver.core import Media, Metadata
class JsonEnricher(Enricher): class JsonEnricher(Enricher):
def enrich(self, to_enrich: Metadata) -> None: def enrich(self, to_enrich: Metadata) -> None:
url = to_enrich.get_url() logger.debug("Enriching as JSON")
logger.debug(f"JSON Enricher for {url=}")
item_path = os.path.join(self.tmp_dir, "metadata.json") item_path = os.path.join(self.tmp_dir, "metadata.json")
with open(item_path, mode="w", encoding="utf-8") as outf: with open(item_path, mode="w", encoding="utf-8") as outf:

View File

@@ -1,7 +1,7 @@
import shutil import shutil
from typing import IO from typing import IO
import os import os
from loguru import logger from auto_archiver.utils.custom_logger import logger
from auto_archiver.core import Media from auto_archiver.core import Media
from auto_archiver.core import Storage from auto_archiver.core import Storage
@@ -38,8 +38,7 @@ class LocalStorage(Storage):
os.makedirs(os.path.dirname(dest), exist_ok=True) os.makedirs(os.path.dirname(dest), exist_ok=True)
logger.debug(f"[{self.__class__.__name__}] storing file {media.filename} with key {media.key} to {dest}") logger.debug(f"[{self.__class__.__name__}] storing file {media.filename} with key {media.key} to {dest}")
res = shutil.copy2(media.filename, dest) shutil.copy2(media.filename, dest)
logger.info(res)
return True return True
# must be implemented even if unused # must be implemented even if unused

View File

@@ -1,6 +1,6 @@
import datetime import datetime
import os import os
from loguru import logger from auto_archiver.utils.custom_logger import logger
from auto_archiver.core import Enricher from auto_archiver.core import Enricher
from auto_archiver.core import Metadata from auto_archiver.core import Metadata
@@ -12,20 +12,17 @@ class MetaEnricher(Enricher):
""" """
def enrich(self, to_enrich: Metadata) -> None: def enrich(self, to_enrich: Metadata) -> None:
url = to_enrich.get_url()
if to_enrich.is_empty(): if to_enrich.is_empty():
logger.debug(f"[SKIP] META_ENRICHER there is no media or metadata to enrich: {url=}") logger.debug("[SKIP] META_ENRICHER there is no media or metadata to enrich")
return return
logger.debug(f"calculating archive metadata information for {url=}") logger.debug("Calculating archive metadata information")
self.enrich_file_sizes(to_enrich) self.enrich_file_sizes(to_enrich)
self.enrich_archive_duration(to_enrich) self.enrich_archive_duration(to_enrich)
def enrich_file_sizes(self, to_enrich: Metadata): def enrich_file_sizes(self, to_enrich: Metadata):
logger.debug( logger.debug(f"Calculating archive file sizes for {len(to_enrich.media)} media files")
f"calculating archive file sizes for url={to_enrich.get_url()} ({len(to_enrich.media)} media files)"
)
total_size = 0 total_size = 0
for media in to_enrich.get_all_media(): for media in to_enrich.get_all_media():
file_stats = os.stat(media.filename) file_stats = os.stat(media.filename)
@@ -44,7 +41,7 @@ class MetaEnricher(Enricher):
size /= 1024 size /= 1024
def enrich_archive_duration(self, to_enrich): def enrich_archive_duration(self, to_enrich):
logger.debug(f"calculating archive duration for url={to_enrich.get_url()} ") logger.debug("Calculating archive duration")
archive_duration = datetime.datetime.now(datetime.timezone.utc) - to_enrich.get("_processed_at") archive_duration = datetime.datetime.now(datetime.timezone.utc) - to_enrich.get("_processed_at")
to_enrich.set("archive_duration_seconds", archive_duration.seconds) to_enrich.set("archive_duration_seconds", archive_duration.seconds)

View File

@@ -1,6 +1,6 @@
import subprocess import subprocess
import traceback import traceback
from loguru import logger from auto_archiver.utils.custom_logger import logger
from auto_archiver.core import Enricher from auto_archiver.core import Enricher
from auto_archiver.core import Metadata from auto_archiver.core import Metadata
@@ -12,8 +12,7 @@ class MetadataEnricher(Enricher):
""" """
def enrich(self, to_enrich: Metadata) -> None: def enrich(self, to_enrich: Metadata) -> None:
url = to_enrich.get_url() logger.debug("Extracting EXIF metadata")
logger.debug(f"extracting EXIF metadata for {url=}")
for i, m in enumerate(to_enrich.media): for i, m in enumerate(to_enrich.media):
if len(md := self.get_metadata(m.filename)): if len(md := self.get_metadata(m.filename)):
@@ -31,8 +30,8 @@ class MetadataEnricher(Enricher):
field, value = line.strip().split(":", 1) field, value = line.strip().split(":", 1)
metadata[field.strip()] = value.strip() metadata[field.strip()] = value.strip()
return metadata return metadata
except FileNotFoundError: except FileNotFoundError as e:
logger.error("[exif_enricher] ExifTool not found. Make sure ExifTool is installed and added to PATH.") logger.error(f"ExifTool not found. Make sure ExifTool is installed and added to PATH. {e}")
except Exception as e: except Exception as e:
logger.error(f"Error occurred: {e}: {traceback.format_exc()}") logger.error(f"Error occurred: {e}: {traceback.format_exc()}")
return {} return {}

View File

@@ -1,6 +1,7 @@
import os import os
import traceback
from loguru import logger from auto_archiver.utils.custom_logger import logger
import opentimestamps import opentimestamps
from opentimestamps.calendar import RemoteCalendar, DEFAULT_CALENDAR_WHITELIST from opentimestamps.calendar import RemoteCalendar, DEFAULT_CALENDAR_WHITELIST
from opentimestamps.core.timestamp import Timestamp, DetachedTimestampFile from opentimestamps.core.timestamp import Timestamp, DetachedTimestampFile
@@ -14,13 +15,12 @@ from auto_archiver.utils.misc import get_current_timestamp
class OpentimestampsEnricher(Enricher): class OpentimestampsEnricher(Enricher):
def enrich(self, to_enrich: Metadata) -> None: def enrich(self, to_enrich: Metadata) -> None:
url = to_enrich.get_url() logger.debug("OpenTimestamps timestamping files")
logger.debug(f"OpenTimestamps timestamping files for {url=}")
# Get the media files to timestamp # Get the media files to timestamp
media_files = [m for m in to_enrich.media if m.filename and not m.get("opentimestamps")] media_files = [m for m in to_enrich.media if m.filename and not m.get("opentimestamps")]
if not media_files: if not media_files:
logger.debug(f"No files found to timestamp in {url=}") logger.debug("No files found to timestamp")
return return
timestamp_files = [] timestamp_files = []
@@ -94,7 +94,7 @@ class OpentimestampsEnricher(Enricher):
detached_timestamp.serialize(ctx) detached_timestamp.serialize(ctx)
f.write(ctx.getbytes()) f.write(ctx.getbytes())
except Exception as e: except Exception as e:
logger.warning(f"Failed to serialize timestamp file: {e}") logger.warning(f"Failed to serialize timestamp file: {e} {traceback.format_exc()}")
continue continue
# Create media for the timestamp file # Create media for the timestamp file
@@ -113,16 +113,16 @@ class OpentimestampsEnricher(Enricher):
media.set("opentimestamps", True) media.set("opentimestamps", True)
except Exception as e: except Exception as e:
logger.warning(f"Error while timestamping {media.filename}: {e}") logger.warning(f"Error while timestamping {media.filename}: {e} {traceback.format_exc()}")
# Add timestamp files to the metadata # Add timestamp files to the metadata
if timestamp_files: if timestamp_files:
to_enrich.set("opentimestamped", True) to_enrich.set("opentimestamped", True)
to_enrich.set("opentimestamps_count", len(timestamp_files)) to_enrich.set("opentimestamps_count", len(timestamp_files))
logger.info(f"{len(timestamp_files)} OpenTimestamps proofs created for {url=}") logger.info(f"{len(timestamp_files)} OpenTimestamps proofs created")
else: else:
to_enrich.set("opentimestamped", False) to_enrich.set("opentimestamped", False)
logger.warning(f"No successful timestamps created for {url=}") logger.warning("No successful timestamps created")
def verify_timestamp(self, detached_timestamp): def verify_timestamp(self, detached_timestamp):
""" """

View File

@@ -15,7 +15,7 @@ import traceback
import pdqhash import pdqhash
import numpy as np import numpy as np
from PIL import Image, UnidentifiedImageError from PIL import Image, UnidentifiedImageError
from loguru import logger from auto_archiver.utils.custom_logger import logger
from auto_archiver.core import Enricher from auto_archiver.core import Enricher
from auto_archiver.core import Metadata from auto_archiver.core import Metadata
@@ -28,8 +28,7 @@ class PdqHashEnricher(Enricher):
""" """
def enrich(self, to_enrich: Metadata) -> None: def enrich(self, to_enrich: Metadata) -> None:
url = to_enrich.get_url() logger.debug("Calculating perceptual hashes")
logger.debug(f"calculating perceptual hashes for {url=}")
media_with_hashes = [] media_with_hashes = []
for m in to_enrich.media: for m in to_enrich.media:
@@ -44,7 +43,7 @@ class PdqHashEnricher(Enricher):
media.set("pdq_hash", hd) media.set("pdq_hash", hd)
media_with_hashes.append(media.filename) media_with_hashes.append(media.filename)
logger.debug(f"calculated '{len(media_with_hashes)}' perceptual hashes for {url=}: {media_with_hashes}") logger.debug(f"Calculated '{len(media_with_hashes)}' perceptual hashes: {media_with_hashes}")
def calculate_pdq_hash(self, filename): def calculate_pdq_hash(self, filename):
# returns a hexadecimal string with the perceptual hash for the given filename # returns a hexadecimal string with the perceptual hash for the given filename

View File

@@ -2,7 +2,7 @@ from typing import IO
import boto3 import boto3
import os import os
from loguru import logger from auto_archiver.utils.custom_logger import logger
from auto_archiver.core import Media from auto_archiver.core import Media
from auto_archiver.core import Storage from auto_archiver.core import Storage
@@ -56,7 +56,7 @@ class S3Storage(Storage):
if existing_key := self.file_in_folder(path): if existing_key := self.file_in_folder(path):
media._key = existing_key media._key = existing_key
media.set("previously archived", True) media.set("previously archived", True)
logger.debug(f"skipping upload of {media.filename} because it already exists in {media.key}") logger.debug(f"Skipping upload of {media.filename} because it already exists in {media.key}")
return False return False
_, ext = os.path.splitext(media.key) _, ext = os.path.splitext(media.key)

View File

@@ -2,7 +2,7 @@ import ssl
import os import os
from slugify import slugify from slugify import slugify
from urllib.parse import urlparse from urllib.parse import urlparse
from loguru import logger from auto_archiver.utils.custom_logger import logger
from auto_archiver.core import Enricher from auto_archiver.core import Enricher
from auto_archiver.core import Metadata, Media from auto_archiver.core import Metadata, Media
@@ -19,10 +19,10 @@ class SSLEnricher(Enricher):
url = to_enrich.get_url() url = to_enrich.get_url()
parsed = urlparse(url) parsed = urlparse(url)
assert parsed.scheme in ["https"], f"Invalid URL scheme {url=}" assert parsed.scheme in ["https"], "Invalid URL scheme"
domain = parsed.netloc domain = parsed.netloc
logger.debug(f"fetching SSL certificate for {domain=} in {url=}") logger.debug(f"Fetching SSL certificate for {domain=}")
cert = ssl.get_server_certificate((domain, 443)) cert = ssl.get_server_certificate((domain, 443))
cert_fn = os.path.join(self.tmp_dir, f"{slugify(domain)}.pem") cert_fn = os.path.join(self.tmp_dir, f"{slugify(domain)}.pem")

View File

@@ -2,7 +2,7 @@ import requests
import re import re
import html import html
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
from loguru import logger from auto_archiver.utils.custom_logger import logger
from auto_archiver.core import Extractor from auto_archiver.core import Extractor
from auto_archiver.core import Metadata, Media from auto_archiver.core import Metadata, Media
@@ -38,7 +38,7 @@ class TelegramExtractor(Extractor):
video = s.find("video") video = s.find("video")
if video is None: if video is None:
logger.warning("could not find video") logger.warning("Could not find video")
image_tags = s.find_all(class_="tgme_widget_message_photo_wrap") image_tags = s.find_all(class_="tgme_widget_message_photo_wrap")
image_urls = [] image_urls = []

View File

@@ -5,6 +5,7 @@ import time
from pathlib import Path from pathlib import Path
from datetime import date from datetime import date
from telethon import functions
from telethon.sync import TelegramClient from telethon.sync import TelegramClient
from telethon.errors import ChannelInvalidError from telethon.errors import ChannelInvalidError
from telethon.tl.functions.messages import ImportChatInviteRequest from telethon.tl.functions.messages import ImportChatInviteRequest
@@ -16,7 +17,7 @@ from telethon.errors.rpcerrorlist import (
) )
from tqdm import tqdm from tqdm import tqdm
from loguru import logger from auto_archiver.utils.custom_logger import logger
from auto_archiver.core import Extractor from auto_archiver.core import Extractor
from auto_archiver.core import Metadata, Media from auto_archiver.core import Metadata, Media
@@ -24,7 +25,7 @@ from auto_archiver.utils import random_str
class TelethonExtractor(Extractor): class TelethonExtractor(Extractor):
valid_url = re.compile(r"https:\/\/t\.me(\/c){0,1}\/(.+)\/(\d+)") valid_url = re.compile(r"https:\/\/t\.me(\/c){0,1}\/(.+?)(\/s){0,1}\/(\d+)")
invite_pattern = re.compile(r"t.me(\/joinchat){0,1}\/\+?(.+)") invite_pattern = re.compile(r"t.me(\/joinchat){0,1}\/\+?(.+)")
def setup(self) -> None: def setup(self) -> None:
@@ -64,7 +65,7 @@ class TelethonExtractor(Extractor):
# get currently joined channels # get currently joined channels
# https://docs.telethon.dev/en/stable/modules/custom.html#module-telethon.tl.custom.dialog # https://docs.telethon.dev/en/stable/modules/custom.html#module-telethon.tl.custom.dialog
joined_channel_ids = [c.id for c in self.client.get_dialogs() if c.is_channel] joined_channel_ids = [c.id for c in self.client.get_dialogs() if c.is_channel]
logger.info(f"already part of {len(joined_channel_ids)} channels") logger.info(f"Already part of {len(joined_channel_ids)} channels")
i = 0 i = 0
pbar = tqdm(desc=f"joining {len(self.channel_invites)} invite links", total=len(self.channel_invites)) pbar = tqdm(desc=f"joining {len(self.channel_invites)} invite links", total=len(self.channel_invites))
@@ -79,22 +80,22 @@ class TelethonExtractor(Extractor):
else: else:
ent = self.client.get_entity(invite) # fails if not a member ent = self.client.get_entity(invite) # fails if not a member
logger.warning( logger.warning(
f"please add the property id='{ent.id}' to the 'channel_invites' configuration where {invite=}, not doing so can lead to a minutes-long setup time due to telegram's rate limiting." f"Please add the property id='{ent.id}' to the 'channel_invites' configuration where {invite=}, not doing so can lead to a minutes-long setup time due to telegram's rate limiting."
) )
except ValueError: except ValueError:
logger.info(f"joining new channel {invite=}") logger.info(f"Joining new channel {invite=}")
try: try:
self.client(ImportChatInviteRequest(match.group(2))) self.client(ImportChatInviteRequest(match.group(2)))
except UserAlreadyParticipantError: except UserAlreadyParticipantError:
logger.info(f"already joined {invite=}") logger.info(f"Already joined {invite=}")
except InviteRequestSentError: except InviteRequestSentError:
logger.warning(f"already sent a join request with {invite} still no answer") logger.warning(f"Already sent a join request with {invite} still no answer")
except InviteHashExpiredError: except InviteHashExpiredError:
logger.warning(f"{invite=} has expired please find a more recent one") logger.warning(f"{invite=} has expired please find a more recent one")
except Exception as e: except Exception as e:
logger.error(f"could not join channel with {invite=} due to {e}") logger.error(f"Could not join channel with {invite=} due to {e}")
except FloodWaitError as e: except FloodWaitError as e:
logger.warning(f"got a flood error, need to wait {e.seconds} seconds") logger.warning(f"Got a flood error, need to wait {e.seconds} seconds")
time.sleep(e.seconds) time.sleep(e.seconds)
continue continue
else: else:
@@ -116,68 +117,91 @@ class TelethonExtractor(Extractor):
url = item.get_url() url = item.get_url()
# detect URLs that we definitely cannot handle # detect URLs that we definitely cannot handle
match = self.valid_url.search(url) match = self.valid_url.search(url)
logger.debug(f"TELETHON: {match=}") logger.debug(f"Found telethon url {match=}")
if not match: if not match:
return False return False
is_private = match.group(1) == "/c" is_private = match.group(1) == "/c"
chat = int(match.group(2)) if is_private else match.group(2) chat = int(match.group(2)) if is_private else match.group(2)
post_id = int(match.group(3)) is_story = match.group(3) == "/s"
post_id = int(match.group(4))
result = Metadata() result = Metadata()
# NB: not using bot_token since then private channels cannot be archived: self.client.start(bot_token=self.bot_token) # NB: not using bot_token since then private channels cannot be archived: self.client.start(bot_token=self.bot_token)
with self.client.start(): with self.client.start():
# with self.client.start(bot_token=self.bot_token): # with self.client.start(bot_token=self.bot_token):
try: if is_story:
post = self.client.get_messages(chat, ids=post_id) try:
except ValueError as e: stories = self.client(functions.stories.GetStoriesByIDRequest(peer=chat, id=[post_id]))
logger.error(f"Could not fetch telegram {url} possibly it's private: {e}") if not stories.stories:
return False logger.info("No stories found, possibly it's private or the story has expired.")
except ChannelInvalidError as e: return False
logger.error( story = stories.stories[0]
f"Could not fetch telegram {url}. This error may be fixed if you setup a bot_token in addition to api_id and api_hash (but then private channels will not be archived, we need to update this logic to handle both): {e}" logger.debug(f"Got story {story.id=} {story.date=} {story.expire_date=}")
) result.set_timestamp(story.date).set("views", story.views.to_dict()).set(
return False "expire_date", story.expire_date
)
logger.debug(f"TELETHON GOT POST {post=}") # download the story media
if post is None: filename_dest = os.path.join(self.tmp_dir, f"{chat}_{post_id}", str(story.id))
return False if filename := self.client.download_media(story.media, filename_dest):
result.add_media(Media(filename))
except Exception as e:
logger.error(f"Error fetching story {post_id} from {chat}: {e}")
return False
else:
try:
post = self.client.get_messages(chat, ids=post_id)
except ValueError as e:
logger.error(f"Could not fetch telegram URL possibly it's private: {e}")
return False
except ChannelInvalidError as e:
logger.error(
f"Could not fetch telegram URL. This error may be fixed if you setup a bot_token in addition to api_id and api_hash (but then private channels will not be archived, we need to update this logic to handle both): {e}"
)
return False
media_posts = self._get_media_posts_in_group(chat, post) logger.debug(f"Got post {post=}")
logger.debug(f"got {len(media_posts)=} for {url=}") if post is None:
return False
tmp_dir = self.tmp_dir media_posts = self._get_media_posts_in_group(chat, post)
logger.debug(f"Got {len(media_posts)=}")
group_id = post.grouped_id if post.grouped_id is not None else post.id group_id = post.grouped_id if post.grouped_id is not None else post.id
title = post.message title = post.message
for mp in media_posts: for mp in media_posts:
if len(mp.message) > len(title): if len(mp.message) > len(title):
title = mp.message # save the longest text found (usually only 1) title = mp.message # save the longest text found (usually only 1)
# media can also be in entities # media can also be in entities
if mp.entities: if mp.entities:
other_media_urls = [ other_media_urls = [
e.url e.url
for e in mp.entities for e in mp.entities
if hasattr(e, "url") and e.url and self._guess_file_type(e.url) in ["video", "image", "audio"] if hasattr(e, "url")
] and e.url
if len(other_media_urls): and self._guess_file_type(e.url) in ["video", "image", "audio"]
logger.debug(f"Got {len(other_media_urls)} other media urls from {mp.id=}: {other_media_urls}") ]
for i, om_url in enumerate(other_media_urls): if len(other_media_urls):
filename = self.download_from_url(om_url, f"{chat}_{group_id}_{i}") logger.debug(
result.add_media(Media(filename=filename), id=f"{group_id}_{i}") f"Got {len(other_media_urls)} other media urls from {mp.id=}: {other_media_urls}"
)
for i, om_url in enumerate(other_media_urls):
filename = self.download_from_url(om_url, f"{chat}_{group_id}_{i}")
result.add_media(Media(filename=filename), id=f"{group_id}_{i}")
filename_dest = os.path.join(tmp_dir, f"{chat}_{group_id}", str(mp.id)) filename_dest = os.path.join(self.tmp_dir, f"{chat}_{group_id}", str(mp.id))
filename = self.client.download_media(mp.media, filename_dest) filename = self.client.download_media(mp.media, filename_dest)
if not filename: if not filename:
logger.debug(f"Empty media found, skipping {str(mp)=}") logger.debug(f"Empty media found, skipping {str(mp)=}")
continue continue
result.add_media(Media(filename)) result.add_media(Media(filename))
result.set_title(title).set_timestamp(post.date).set("api_data", post.to_dict()) result.set_title(title).set_timestamp(post.date).set("api_data", post.to_dict())
if post.message != title: if post.message != title:
result.set_content(post.message) result.set_content(post.message)
return result.success("telethon") return result.success("telethon")
def _get_media_posts_in_group(self, chat, original_post, max_amp=10): def _get_media_posts_in_group(self, chat, original_post, max_amp=10):

View File

@@ -9,7 +9,7 @@ and identify important moments without watching the entire video.
import ffmpeg import ffmpeg
import os import os
from loguru import logger from auto_archiver.utils.custom_logger import logger
from auto_archiver.core import Enricher from auto_archiver.core import Enricher
from auto_archiver.core import Media, Metadata from auto_archiver.core import Media, Metadata
@@ -27,12 +27,12 @@ class ThumbnailEnricher(Enricher):
Calculates how many thumbnails to generate and at which timestamps based on the video duration, the number of thumbnails per minute and the max number of thumbnails. Calculates how many thumbnails to generate and at which timestamps based on the video duration, the number of thumbnails per minute and the max number of thumbnails.
Thumbnails are equally distributed across the video duration. Thumbnails are equally distributed across the video duration.
""" """
logger.debug(f"generating thumbnails for {to_enrich.get_url()}") logger.debug("Generating thumbnails")
for m_id, m in enumerate(to_enrich.media[::]): for m_id, m in enumerate(to_enrich.media[::]):
if m.is_video(): if m.is_video():
folder = os.path.join(self.tmp_dir, random_str(24)) folder = os.path.join(self.tmp_dir, random_str(24))
os.makedirs(folder, exist_ok=True) os.makedirs(folder, exist_ok=True)
logger.debug(f"generating thumbnails for {m.filename}") logger.debug(f"Generating thumbnails for {m.filename}")
duration = m.get("duration") duration = m.get("duration")
try: try:
@@ -42,10 +42,10 @@ class ThumbnailEnricher(Enricher):
) )
to_enrich.media[m_id].set("duration", duration) to_enrich.media[m_id].set("duration", duration)
except Exception as e: except Exception as e:
logger.warning(f"failed to get duration with FFMPEG from {m.filename}: {e}") logger.warning(f"Failed to get duration with FFMPEG from {m.filename}: {e}")
if not duration or type(duration) not in [float, int] or duration <= 0: if not duration or type(duration) not in [float, int] or duration <= 0:
logger.warning(f"cannot generate thumbnails for {m.filename} without valid duration") logger.warning(f"Cannot generate thumbnails for {m.filename} without valid duration")
continue continue
num_thumbs = int(min(max(1, (duration / 60) * self.thumbnails_per_minute), self.max_thumbnails)) num_thumbs = int(min(max(1, (duration / 60) * self.thumbnails_per_minute), self.max_thumbnails))

View File

@@ -20,7 +20,7 @@
# "http://tsa.sinpe.fi.cr/tsaHttp/", # self-signed # "http://tsa.sinpe.fi.cr/tsaHttp/", # self-signed
# "http://tsa.cra.ge/signserver/tsa?workerName=qtsa", # self-signed # "http://tsa.cra.ge/signserver/tsa?workerName=qtsa", # self-signed
"http://tss.cnbs.gob.hn/TSS/HttpTspServer", "http://tss.cnbs.gob.hn/TSS/HttpTspServer",
"http://dss.nowina.lu/pki-factory/tsa/good-tsa", # "http://dss.nowina.lu/pki-factory/tsa/good-tsa",
# "https://freetsa.org/tsr", # self-signed # "https://freetsa.org/tsr", # self-signed
], ],
"help": "List of RFC3161 Time Stamp Authorities to use, separate with commas if passed via the command line.", "help": "List of RFC3161 Time Stamp Authorities to use, separate with commas if passed via the command line.",

View File

@@ -4,12 +4,12 @@ from importlib.metadata import version
import hashlib import hashlib
from slugify import slugify from slugify import slugify
from retrying import retry
import requests import requests
from loguru import logger from auto_archiver.utils.custom_logger import logger
from rfc3161_client import (decode_timestamp_response,TimestampRequestBuilder,TimeStampResponse, VerifierBuilder) from rfc3161_client import (decode_timestamp_response, TimestampRequestBuilder, TimeStampResponse, VerifierBuilder)
from rfc3161_client import VerificationError as Rfc3161VerificationError from rfc3161_client import VerificationError as Rfc3161VerificationError
from rfc3161_client.base import HashAlgorithm
from rfc3161_client.tsp import SignedData from rfc3161_client.tsp import SignedData
from cryptography import x509 from cryptography import x509
from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives import serialization
@@ -49,8 +49,7 @@ class TimestampingEnricher(Enricher):
self.session.close() self.session.close()
def enrich(self, to_enrich: Metadata) -> None: def enrich(self, to_enrich: Metadata) -> None:
url = to_enrich.get_url() logger.debug(f"RFC3161 timestamping existing files")
logger.debug(f"RFC3161 timestamping existing files for {url=}")
# create a new text file with the existing media hashes # create a new text file with the existing media hashes
hashes = [ hashes = [
@@ -58,10 +57,9 @@ class TimestampingEnricher(Enricher):
] ]
if not len(hashes): if not len(hashes):
logger.debug(f"No hashes found in {url=}") logger.debug(f"No hashes found")
return return
hashes_fn = os.path.join(self.tmp_dir, "hashes.txt") hashes_fn = os.path.join(self.tmp_dir, "hashes.txt")
data_to_sign = "\n".join(hashes) data_to_sign = "\n".join(hashes)
@@ -74,9 +72,9 @@ class TimestampingEnricher(Enricher):
try: try:
message = bytes(data_to_sign, encoding='utf8') message = bytes(data_to_sign, encoding='utf8')
logger.debug(f"Timestamping {url=} with {tsa_url=}") logger.debug(f"Timestamping with {tsa_url=}")
signed: TimeStampResponse = self.sign_data(tsa_url, message) signed: TimeStampResponse = self.sign_data(tsa_url, message)
# fail if there's any issue with the certificates, uses certifi list of trusted CAs or the user-defined `cert_authorities` # fail if there's any issue with the certificates, uses certifi list of trusted CAs or the user-defined `cert_authorities`
root_cert = self.verify_signed(signed, message) root_cert = self.verify_signed(signed, message)
@@ -92,7 +90,7 @@ class TimestampingEnricher(Enricher):
timestamp_token_path = self.save_timestamp_token(signed.time_stamp_token(), tsa_url) timestamp_token_path = self.save_timestamp_token(signed.time_stamp_token(), tsa_url)
timestamp_tokens.append(Media(filename=timestamp_token_path).set("tsa", tsa_url).set("cert_chain", cert_chain)) timestamp_tokens.append(Media(filename=timestamp_token_path).set("tsa", tsa_url).set("cert_chain", cert_chain))
except Exception as e: except Exception as e:
logger.warning(f"Error while timestamping {url=} with {tsa_url=}: {e}") logger.warning(f"Error while timestamping with {tsa_url=}: {e}")
if len(timestamp_tokens): if len(timestamp_tokens):
hashes_media.set("timestamp_authority_files", timestamp_tokens) hashes_media.set("timestamp_authority_files", timestamp_tokens)
@@ -101,9 +99,9 @@ class TimestampingEnricher(Enricher):
hashes_media.set("cryptography v", version("cryptography")) hashes_media.set("cryptography v", version("cryptography"))
to_enrich.add_media(hashes_media, id="timestamped_hashes") to_enrich.add_media(hashes_media, id="timestamped_hashes")
to_enrich.set("timestamped", True) to_enrich.set("timestamped", True)
logger.info(f"{len(timestamp_tokens)} timestamp tokens created for {url=}") logger.info(f"{len(timestamp_tokens)} timestamp tokens created")
else: else:
logger.warning(f"No successful timestamps for {url=}") logger.warning(f"No successful timestamps found")
def save_timestamp_token(self, timestamp_token: bytes, tsa_url: str) -> str: def save_timestamp_token(self, timestamp_token: bytes, tsa_url: str) -> str:
""" """
@@ -114,7 +112,7 @@ class TimestampingEnricher(Enricher):
f.write(timestamp_token) f.write(timestamp_token)
return tst_path return tst_path
def verify_signed(self, timestamp_response: TimeStampResponse, message: bytes) -> x509.Certificate: def verify_signed(self, timestamp_response: TimeStampResponse, message: bytes) -> x509.Certificate:
""" """
Verify a Signed Timestamp Response is trusted by a known Certificate Authority. Verify a Signed Timestamp Response is trusted by a known Certificate Authority.
@@ -137,7 +135,7 @@ class TimestampingEnricher(Enricher):
if not cert_authorities: if not cert_authorities:
raise ValueError(f"No trusted roots found in {trusted_root_path}.") raise ValueError(f"No trusted roots found in {trusted_root_path}.")
timestamp_certs = self.tst_certs(timestamp_response) timestamp_certs = self.tst_certs(timestamp_response)
intermediate_certs = timestamp_certs[1:-1] intermediate_certs = timestamp_certs[1:-1]
@@ -149,7 +147,7 @@ class TimestampingEnricher(Enricher):
message_hash = hashlib.sha256(message).digest() message_hash = hashlib.sha256(message).digest()
else: else:
raise ValueError(f"Unsupported hash algorithm: {hash_algorithm}") raise ValueError(f"Unsupported hash algorithm: {hash_algorithm}")
for certificate in cert_authorities: for certificate in cert_authorities:
builder = VerifierBuilder() builder = VerifierBuilder()
builder.add_root_certificate(certificate) builder.add_root_certificate(certificate)
@@ -159,7 +157,6 @@ class TimestampingEnricher(Enricher):
verifier = builder.build() verifier = builder.build()
try: try:
verifier.verify(timestamp_response, message_hash) verifier.verify(timestamp_response, message_hash)
return certificate return certificate
@@ -172,23 +169,38 @@ class TimestampingEnricher(Enricher):
# see https://github.com/sigstore/sigstore-python/blob/99948d5b80525a5a104e904ffea58169dc6e0629/sigstore/_internal/timestamp.py#L84-L121 # see https://github.com/sigstore/sigstore-python/blob/99948d5b80525a5a104e904ffea58169dc6e0629/sigstore/_internal/timestamp.py#L84-L121
timestamp_request = ( timestamp_request = (
TimestampRequestBuilder().data(bytes_data).nonce(nonce=True).build() TimestampRequestBuilder().data(bytes_data).nonce(nonce=True).build()
) )
try:
@retry(
wait_exponential_multiplier=1,
stop_max_attempt_number=2,
)
def sign_with_retry():
response = self.session.post(tsa_url, data=timestamp_request.as_bytes(), timeout=10) response = self.session.post(tsa_url, data=timestamp_request.as_bytes(), timeout=10)
response.raise_for_status() response.raise_for_status()
return response
try:
response = sign_with_retry()
except requests.RequestException as e: except requests.RequestException as e:
logger.error(f"Error while sending request to {tsa_url=}: {e}") logger.error(f"Error while sending request to {tsa_url=}: {e}")
raise raise
@retry(
wait_exponential_multiplier=1,
stop_max_attempt_number=2,
)
def decode_with_retry(response):
return decode_timestamp_response(response.content)
# Check that we can parse the response but do not *verify* it # Check that we can parse the response but do not *verify* it
try: try:
timestamp_response = decode_timestamp_response(response.content) timestamp_response = decode_with_retry(response)
except ValueError as e: except ValueError as e:
logger.error(f"Invalid timestamp response from server {tsa_url}: {e}") logger.error(f"Invalid timestamp response from server {tsa_url}: {e}")
raise raise
return timestamp_response return timestamp_response
def tst_certs(self, tsp_response: TimeStampResponse): def tst_certs(self, tsp_response: TimeStampResponse):
signed_data: SignedData = tsp_response.signed_data signed_data: SignedData = tsp_response.signed_data
certs = [x509.load_der_x509_certificate(c) for c in signed_data.certificates] certs = [x509.load_der_x509_certificate(c) for c in signed_data.certificates]
@@ -197,7 +209,7 @@ class TimestampingEnricher(Enricher):
if len(certs) == 1: if len(certs) == 1:
return certs return certs
while(len(ordered_certs) < len(certs)): while (len(ordered_certs) < len(certs)):
if len(ordered_certs) == 0: if len(ordered_certs) == 0:
for cert in certs: for cert in certs:
if not [c for c in certs if cert.subject == c.issuer]: if not [c for c in certs if cert.subject == c.issuer]:
@@ -221,7 +233,7 @@ class TimestampingEnricher(Enricher):
cert_chain = [] cert_chain = []
for i, cert in enumerate(certificates): for i, cert in enumerate(certificates):
cert_fn = os.path.join(self.tmp_dir, f"{i+1} {str(cert.serial_number)[:20]}.crt") cert_fn = os.path.join(self.tmp_dir, f"{i + 1} {str(cert.serial_number)[:20]}.crt")
with open(cert_fn, "wb") as f: with open(cert_fn, "wb") as f:
f.write(cert.public_bytes(encoding=serialization.Encoding.PEM)) f.write(cert.public_bytes(encoding=serialization.Encoding.PEM))
cert_chain.append(Media(filename=cert_fn).set("subject", cert.subject.get_attributes_for_oid(x509.NameOID.COMMON_NAME)[0].value)) cert_chain.append(Media(filename=cert_fn).set("subject", cert.subject.get_attributes_for_oid(x509.NameOID.COMMON_NAME)[0].value))

View File

@@ -4,7 +4,7 @@ import re
import mimetypes import mimetypes
import requests import requests
from loguru import logger from auto_archiver.utils.custom_logger import logger
from pytwitter import Api from pytwitter import Api
from slugify import slugify from slugify import slugify
@@ -45,10 +45,9 @@ class TwitterApiExtractor(Extractor):
if "https://t.co/" in url: if "https://t.co/" in url:
try: try:
r = requests.get(url, timeout=30) r = requests.get(url, timeout=30)
logger.debug(f"Expanded url {url} to {r.url}")
url = r.url url = r.url
except Exception: except Exception as e:
logger.error(f"Failed to expand url {url}") logger.error(f"Failed to expand Twitter URL: {e}")
return url return url
def download(self, item: Metadata) -> Metadata: def download(self, item: Metadata) -> Metadata:
@@ -67,7 +66,7 @@ class TwitterApiExtractor(Extractor):
return False, False return False, False
username, tweet_id = matches[0] # only one URL supported username, tweet_id = matches[0] # only one URL supported
logger.debug(f"Found {username=} and {tweet_id=} in {url=}") logger.debug(f"Found {username=} and {tweet_id=}")
return username, tweet_id return username, tweet_id
@@ -85,7 +84,7 @@ class TwitterApiExtractor(Extractor):
media_fields=["type", "duration_ms", "url", "variants"], media_fields=["type", "duration_ms", "url", "variants"],
tweet_fields=["attachments", "author_id", "created_at", "entities", "id", "text", "possibly_sensitive"], tweet_fields=["attachments", "author_id", "created_at", "entities", "id", "text", "possibly_sensitive"],
) )
logger.debug(tweet) logger.debug(f"Got {tweet=}")
except Exception as e: except Exception as e:
logger.error(f"Could not get tweet: {e}") logger.error(f"Could not get tweet: {e}")
return False return False

View File

@@ -4,7 +4,7 @@ import os
import shutil import shutil
import subprocess import subprocess
from zipfile import ZipFile from zipfile import ZipFile
from loguru import logger from auto_archiver.utils.custom_logger import logger
from warcio.archiveiterator import ArchiveIterator from warcio.archiveiterator import ArchiveIterator
from auto_archiver.core import Media, Metadata from auto_archiver.core import Media, Metadata
@@ -94,7 +94,7 @@ class WaczExtractorEnricher(Enricher, Extractor):
# call docker if explicitly enabled or we are running on the host (not in docker) # call docker if explicitly enabled or we are running on the host (not in docker)
if self.use_docker: if self.use_docker:
logger.debug(f"generating WACZ in Docker for {url=}") logger.debug("Generating WACZ in Docker")
logger.debug(f"{browsertrix_home_host=} {browsertrix_home_container=}") logger.debug(f"{browsertrix_home_host=} {browsertrix_home_container=}")
if self.docker_commands: if self.docker_commands:
cmd = self.docker_commands + cmd cmd = self.docker_commands + cmd
@@ -111,12 +111,12 @@ class WaczExtractorEnricher(Enricher, Extractor):
if self.profile: if self.profile:
profile_file = f"profile-{self.crawl_id}.tar.gz" profile_file = f"profile-{self.crawl_id}.tar.gz"
profile_fn = os.path.join(browsertrix_home_container, profile_file) profile_fn = os.path.join(browsertrix_home_container, profile_file)
logger.debug(f"copying {self.profile} to {profile_fn}") logger.debug(f"Copying {self.profile} to {profile_fn}")
shutil.copyfile(self.profile, profile_fn) shutil.copyfile(self.profile, profile_fn)
cmd.extend(["--profile", os.path.join("/crawls", profile_file)]) cmd.extend(["--profile", os.path.join("/crawls", profile_file)])
else: else:
logger.debug(f"generating WACZ without Docker for {url=}") logger.debug("Generating WACZ without Docker")
if self.profile: if self.profile:
cmd.extend(["--profile", os.path.join("/app", str(self.profile))]) cmd.extend(["--profile", os.path.join("/app", str(self.profile))])

View File

@@ -1,8 +1,8 @@
import json import json
from loguru import logger from auto_archiver.utils.custom_logger import logger
import time import time
import requests import requests
from urllib3.exceptions import MaxRetryError
from auto_archiver.core import Extractor, Enricher from auto_archiver.core import Extractor, Enricher
from auto_archiver.utils import url as UrlUtil from auto_archiver.utils import url as UrlUtil
from auto_archiver.core import Metadata from auto_archiver.core import Metadata
@@ -31,21 +31,28 @@ class WaybackExtractorEnricher(Enricher, Extractor):
url = to_enrich.get_url() url = to_enrich.get_url()
if UrlUtil.is_auth_wall(url): if UrlUtil.is_auth_wall(url):
logger.debug(f"[SKIP] WAYBACK since url is behind AUTH WALL: {url=}") logger.debug("[SKIP] WAYBACK since url is behind AUTH WALL")
return return
logger.debug(f"calling wayback for {url=}")
if to_enrich.get("wayback"): if to_enrich.get("wayback"):
logger.info(f"Wayback enricher had already been executed: {to_enrich.get('wayback')}") logger.info(f"Wayback enricher had already been executed: {to_enrich.get('wayback')}")
return True return True
logger.debug("Calling Wayback")
ia_headers = {"Accept": "application/json", "Authorization": f"LOW {self.key}:{self.secret}"} ia_headers = {"Accept": "application/json", "Authorization": f"LOW {self.key}:{self.secret}"}
post_data = {"url": url} post_data = {"url": url}
if self.if_not_archived_within: if self.if_not_archived_within:
post_data["if_not_archived_within"] = self.if_not_archived_within post_data["if_not_archived_within"] = self.if_not_archived_within
# see https://docs.google.com/document/d/1Nsv52MvSjbLb2PCpHlat0gkzw0EvtSgpKHu4mk0MnrA for more options # see https://docs.google.com/document/d/1Nsv52MvSjbLb2PCpHlat0gkzw0EvtSgpKHu4mk0MnrA for more options
r = requests.post("https://web.archive.org/save/", headers=ia_headers, data=post_data, proxies=proxies) try:
r = requests.post("https://web.archive.org/save/", headers=ia_headers, data=post_data, proxies=proxies)
except MaxRetryError as e:
logger.warning(
f"MaxRetryError during Wayback POST call to /save, this may be do to a high number of calls leading to rate limiting: {e}"
)
to_enrich.set("wayback", "failed: possible rate limit")
return False
if r.status_code != 200: if r.status_code != 200:
logger.error(em := f"Internet archive failed with status of {r.status_code}: {r.json()}") logger.error(em := f"Internet archive failed with status of {r.status_code}: {r.json()}")
@@ -68,7 +75,7 @@ class WaybackExtractorEnricher(Enricher, Extractor):
attempt = 1 attempt = 1
while not wayback_url and time.time() - start_time <= self.timeout: while not wayback_url and time.time() - start_time <= self.timeout:
try: try:
logger.debug(f"GETting status for {job_id=} on {url=} ({attempt=})") logger.debug(f"GETting status for {job_id=} ({attempt=})")
r_status = requests.get( r_status = requests.get(
f"https://web.archive.org/save/status/{job_id}", headers=ia_headers, proxies=proxies f"https://web.archive.org/save/status/{job_id}", headers=ia_headers, proxies=proxies
) )
@@ -76,16 +83,19 @@ class WaybackExtractorEnricher(Enricher, Extractor):
if r_status.status_code == 200 and r_json["status"] == "success": if r_status.status_code == 200 and r_json["status"] == "success":
wayback_url = f"https://web.archive.org/web/{r_json['timestamp']}/{r_json['original_url']}" wayback_url = f"https://web.archive.org/web/{r_json['timestamp']}/{r_json['original_url']}"
elif r_status.status_code != 200 or r_json["status"] != "pending": elif r_status.status_code != 200 or r_json["status"] != "pending":
if r_json.get("status_ext") in ["error:blocked-url", "error:unauthorized"]:
logger.warning("Wayback cannot currently archive the URL, skipping.")
to_enrich.set("wayback", r_json.get("status_ext"))
logger.error(f"Wayback failed with {r_json}") logger.error(f"Wayback failed with {r_json}")
return False return False
except requests.exceptions.RequestException as e: except requests.exceptions.RequestException as e:
logger.warning(f"RequestException: fetching status for {url=} due to: {e}") logger.warning(f"RequestException: fetching status due to: {e}")
break break
except json.decoder.JSONDecodeError: except json.decoder.JSONDecodeError:
logger.error(f"Expected a JSON from Wayback and got {r.text} for {url=}") logger.error(f"Expected a JSON from Wayback and got {r.text}")
break break
except Exception as e: except Exception as e:
logger.warning(f"error fetching status for {url=} due to: {e}") logger.warning(f"error fetching status due to: {e}")
if not wayback_url: if not wayback_url:
attempt += 1 attempt += 1
time.sleep(1) # TODO: can be improved with exponential backoff time.sleep(1) # TODO: can be improved with exponential backoff

View File

@@ -1,7 +1,7 @@
import traceback import traceback
import requests import requests
import time import time
from loguru import logger from auto_archiver.utils.custom_logger import logger
from auto_archiver.core import Enricher from auto_archiver.core import Enricher
from auto_archiver.core import Metadata, Media from auto_archiver.core import Metadata, Media
@@ -25,7 +25,7 @@ class WhisperEnricher(Enricher):
def enrich(self, to_enrich: Metadata) -> None: def enrich(self, to_enrich: Metadata) -> None:
url = to_enrich.get_url() url = to_enrich.get_url()
logger.debug(f"WHISPER[{self.action}]: iterating media items for {url=}.") logger.debug(f"WHISPER[{self.action}]: iterating media items")
job_results = {} job_results = {}
for i, m in enumerate(to_enrich.media): for i, m in enumerate(to_enrich.media):
@@ -35,7 +35,7 @@ class WhisperEnricher(Enricher):
try: try:
job_id = self.submit_job(m) job_id = self.submit_job(m)
job_results[job_id] = False job_results[job_id] = False
logger.debug(f"JOB SUBMITTED: {job_id=} for {m.key=}") logger.debug(f"Job submitted: {job_id=} for {m.key=}")
to_enrich.media[i].set("whisper_model", {"job_id": job_id}) to_enrich.media[i].set("whisper_model", {"job_id": job_id})
except Exception as e: except Exception as e:
logger.error( logger.error(
@@ -72,14 +72,14 @@ class WhisperEnricher(Enricher):
"type": self.action, "type": self.action,
# "language": "string" # may be a config # "language": "string" # may be a config
} }
logger.debug(f"calling API with {payload=}") logger.debug(f"Calling API with {payload=}")
response = requests.post( response = requests.post(
f"{self.api_endpoint}/jobs", json=payload, headers={"Authorization": f"Bearer {self.api_key}"} f"{self.api_endpoint}/jobs", json=payload, headers={"Authorization": f"Bearer {self.api_key}"}
) )
assert response.status_code == 201, ( assert response.status_code == 201, (
f"calling the whisper api {self.api_endpoint} returned a non-success code: {response.status_code}" f"calling the whisper api {self.api_endpoint} returned a non-success code: {response.status_code}"
) )
logger.debug(response.json()) logger.debug(f"Response from whisper API: {response.json()}")
return response.json()["id"] return response.json()["id"]
def check_jobs(self, job_results: dict): def check_jobs(self, job_results: dict):
@@ -115,7 +115,7 @@ class WhisperEnricher(Enricher):
assert r_res.status_code == 200, ( assert r_res.status_code == 200, (
f"Job artifacts did not respond with 200, instead with: {r_res.status_code}" f"Job artifacts did not respond with 200, instead with: {r_res.status_code}"
) )
logger.success(r_res.json()) logger.info(f"Job {job_id} completed successfully:{r_res.json()}")
result = {} result = {}
for art_id, artifact in enumerate(r_res.json()): for art_id, artifact in enumerate(r_res.json()):
subtitle = [] subtitle = []

View File

@@ -0,0 +1,59 @@
from loguru import logger
import json
def extract_location(record, short=False):
"""Extracts the file name, function name, and line number from the log record."""
if short:
return f"{record['file'].name}:{record['line']}"
return f"{record['file'].name}:{record['function']}:{record['line']}"
def extract_log_data(record):
subset = {
"level": record["level"].name,
"time": record["time"].isoformat(timespec="seconds"),
}
subset["loc"] = extract_location(record)
# This is where logger.contextualize() parameters can be added to the output
for extra_key in ["trace", "url", "worksheet", "row"]:
if extra_val := record.get("extra", {}).get(extra_key):
subset[extra_key] = extra_val
subset["message"] = record["message"]
if exception := record.get("exception"):
subset["exception"] = exception
return subset
def serialize_for_console(record):
subset = extract_log_data(record)
subset.pop("message", None)
subset.pop("level", None)
subset.pop("loc", None)
subset.pop("time", None)
if not subset:
return ""
return json.dumps(subset, ensure_ascii=False)
def serialize(record):
return json.dumps(extract_log_data(record), ensure_ascii=False)
def patching(record):
record["extra"]["serialized"] = serialize(record)
record["extra"]["serialize_for_console"] = serialize_for_console(record)
def format_for_human_readable_console():
return (
"<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | "
"<level>{level: <8}</level> | "
"<cyan>{file}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> | "
"{extra[serialize_for_console]} <level>{message}</level>"
)
logger = logger.patch(patching)

View File

@@ -6,8 +6,7 @@ import uuid
from datetime import datetime, timezone from datetime import datetime, timezone
from dateutil.parser import parse as parse_dt from dateutil.parser import parse as parse_dt
import requests from auto_archiver.utils.custom_logger import logger
from loguru import logger
def mkdir_if_not_exists(folder): def mkdir_if_not_exists(folder):
@@ -15,18 +14,6 @@ def mkdir_if_not_exists(folder):
os.makedirs(folder) os.makedirs(folder)
def expand_url(url):
# expand short URL links
if "https://t.co/" in url:
try:
r = requests.get(url)
logger.debug(f"Expanded url {url} to {r.url}")
return r.url
except Exception:
logger.error(f"Failed to expand url {url}")
return url
def getattr_or(o: object, prop: str, default=None): def getattr_or(o: object, prop: str, default=None):
try: try:
res = getattr(o, prop) res = getattr(o, prop)

View File

@@ -9,7 +9,7 @@ from tempfile import TemporaryDirectory
from typing import Dict, Tuple from typing import Dict, Tuple
import hashlib import hashlib
from loguru import logger from auto_archiver.utils.custom_logger import logger
import pytest import pytest
from auto_archiver.core.metadata import Metadata, Media from auto_archiver.core.metadata import Metadata, Media
from auto_archiver.core.module import ModuleFactory from auto_archiver.core.module import ModuleFactory

View File

@@ -1,6 +1,6 @@
from auto_archiver.core import Extractor from auto_archiver.core import Extractor
from loguru import logger from auto_archiver.utils.custom_logger import logger
class ExampleExtractor(Extractor): class ExampleExtractor(Extractor):

View File

@@ -1,6 +1,6 @@
from auto_archiver.core import Extractor, Enricher, Feeder, Database, Storage, Formatter, Metadata from auto_archiver.core import Extractor, Enricher, Feeder, Database, Storage, Formatter, Metadata
from loguru import logger from auto_archiver.utils.custom_logger import logger
class ExampleModule(Extractor, Enricher, Feeder, Database, Storage, Formatter): class ExampleModule(Extractor, Enricher, Feeder, Database, Storage, Formatter):

View File

@@ -29,7 +29,7 @@ def test_fetch_fail_status(api_db, metadata, mocker):
mock_get = mocker.patch("auto_archiver.modules.api_db.api_db.requests.get") mock_get = mocker.patch("auto_archiver.modules.api_db.api_db.requests.get")
mock_get.return_value.status_code = 400 mock_get.return_value.status_code = 400
mock_get.return_value.json.return_value = {} mock_get.return_value.json.return_value = {}
mock_error = mocker.patch("loguru.logger.error") mock_error = mocker.patch("auto_archiver.utils.custom_logger.logger.error")
assert api_db.fetch(metadata) is False assert api_db.fetch(metadata) is False
mock_error.assert_called_once_with("AA API FAIL (400): {}") mock_error.assert_called_once_with("AA API FAIL (400): {}")

View File

@@ -10,7 +10,10 @@ def mock_gworksheet(mocker):
mock_gworksheet = mocker.MagicMock(spec=GWorksheet) mock_gworksheet = mocker.MagicMock(spec=GWorksheet)
mock_gworksheet.col_exists.return_value = True mock_gworksheet.col_exists.return_value = True
mock_gworksheet.get_cell.return_value = "" mock_gworksheet.get_cell.return_value = ""
mock_gworksheet.get_row.return_value = {} mock_gworksheet.wks = mocker.MagicMock()
mock_gworksheet.wks.spreadsheet = mocker.MagicMock()
mock_gworksheet.wks.spreadsheet.title = "Test Spreadsheet"
mock_gworksheet.title = "Test Worksheet"
return mock_gworksheet return mock_gworksheet

View File

@@ -33,7 +33,6 @@ def test_enrich_skips_empty_metadata(meta_enricher, mock_metadata):
"""Test that enrich() does nothing when Metadata is empty.""" """Test that enrich() does nothing when Metadata is empty."""
mock_metadata.is_empty.return_value = True mock_metadata.is_empty.return_value = True
meta_enricher.enrich(mock_metadata) meta_enricher.enrich(mock_metadata)
mock_metadata.get_url.assert_called_once()
def test_enrich_file_sizes(meta_enricher, metadata, tmp_path): def test_enrich_file_sizes(meta_enricher, metadata, tmp_path):

View File

@@ -65,7 +65,7 @@ def test_enrich_empty_media(enricher, mocker):
def test_get_metadata_error_handling(enricher, mocker): def test_get_metadata_error_handling(enricher, mocker):
mocker.patch("subprocess.run", side_effect=Exception("Test error")) mocker.patch("subprocess.run", side_effect=Exception("Test error"))
mock_log = mocker.patch("loguru.logger.error") mock_log = mocker.patch("auto_archiver.utils.custom_logger.logger.error")
result = enricher.get_metadata("test.jpg") result = enricher.get_metadata("test.jpg")
assert result == {} assert result == {}
assert "Error occurred: " in mock_log.call_args[0][0] assert "Error occurred: " in mock_log.call_args[0][0]

View File

@@ -43,7 +43,7 @@ def test_enrich_skip_non_image(metadata_with_images, mocker):
def test_enrich_handles_corrupted_image(metadata_with_images, mocker): def test_enrich_handles_corrupted_image(metadata_with_images, mocker):
mocker.patch("PIL.Image.open", side_effect=UnidentifiedImageError("Corrupted image")) mocker.patch("PIL.Image.open", side_effect=UnidentifiedImageError("Corrupted image"))
mock_pdq = mocker.patch("pdqhash.compute") mock_pdq = mocker.patch("pdqhash.compute")
mock_logger = mocker.patch("loguru.logger.error") mock_logger = mocker.patch("auto_archiver.utils.custom_logger.logger.error")
enricher = PdqHashEnricher() enricher = PdqHashEnricher()
enricher.enrich(metadata_with_images) enricher.enrich(metadata_with_images)

View File

@@ -75,12 +75,12 @@ def test_enrich_thumbnail_limits(
def test_enrich_handles_probe_failure(thumbnail_enricher, metadata_with_video, mocker): def test_enrich_handles_probe_failure(thumbnail_enricher, metadata_with_video, mocker):
mocker.patch("ffmpeg.probe", side_effect=Exception("Probe error")) mocker.patch("ffmpeg.probe", side_effect=Exception("Probe error"))
mocker.patch("os.makedirs") mocker.patch("os.makedirs")
mock_logger = mocker.patch("loguru.logger.warning") mock_logger = mocker.patch("auto_archiver.utils.custom_logger.logger.warning")
mocker.patch.object(Media, "is_video", return_value=True) mocker.patch.object(Media, "is_video", return_value=True)
thumbnail_enricher.enrich(metadata_with_video) thumbnail_enricher.enrich(metadata_with_video)
# Ensure error was logged # Ensure error was logged
mock_logger.assert_called_with("cannot generate thumbnails for video.mp4 without valid duration") mock_logger.assert_called_with("Cannot generate thumbnails for video.mp4 without valid duration")
# Ensure no thumbnails were created # Ensure no thumbnails were created
thumbnails = metadata_with_video.media[0].get("thumbnails") thumbnails = metadata_with_video.media[0].get("thumbnails")
assert thumbnails is None assert thumbnails is None
@@ -128,12 +128,12 @@ def test_enrich_handles_short_video(
def test_uses_existing_duration_on_exception(thumbnail_enricher, metadata_with_video, mock_ffmpeg_environment, mocker): def test_uses_existing_duration_on_exception(thumbnail_enricher, metadata_with_video, mock_ffmpeg_environment, mocker):
mock_logger = mocker.patch("loguru.logger.warning") mock_logger = mocker.patch("auto_archiver.utils.custom_logger.logger.warning")
mock_probe = mocker.patch("ffmpeg.probe", side_effect=Exception("New probe error")) mock_probe = mocker.patch("ffmpeg.probe", side_effect=Exception("New probe error"))
metadata_with_video.media[0].set("duration", 3) metadata_with_video.media[0].set("duration", 3)
thumbnail_enricher.enrich(metadata_with_video) thumbnail_enricher.enrich(metadata_with_video)
mock_probe.assert_called_once() mock_probe.assert_called_once()
mock_logger.assert_called_with("failed to get duration with FFMPEG from video.mp4: New probe error") mock_logger.assert_called_with("Failed to get duration with FFMPEG from video.mp4: New probe error")
assert mock_ffmpeg_environment["mock_output"].run.call_count == 3 assert mock_ffmpeg_environment["mock_output"].run.call_count == 3

View File

@@ -46,7 +46,7 @@ def test_setup_with_docker(wacz_enricher, mocker):
def test_already_ran(wacz_enricher, metadata, mocker): def test_already_ran(wacz_enricher, metadata, mocker):
metadata.add_media(Media("test.wacz"), id="browsertrix") metadata.add_media(Media("test.wacz"), id="browsertrix")
mock_log = mocker.patch("loguru.logger.info") mock_log = mocker.patch("auto_archiver.utils.custom_logger.logger.info")
assert wacz_enricher.enrich(metadata) is True assert wacz_enricher.enrich(metadata) is True
assert "WACZ enricher had already been executed" in mock_log.call_args[0][0] assert "WACZ enricher had already been executed" in mock_log.call_args[0][0]
@@ -73,7 +73,7 @@ def test_download_success(wacz_enricher, mocker) -> None:
def test_enrich_already_executed(wacz_enricher, mocker) -> None: def test_enrich_already_executed(wacz_enricher, mocker) -> None:
"""Test enrich if already executed.""" """Test enrich if already executed."""
mock_log = mocker.patch("loguru.logger.info") mock_log = mocker.patch("auto_archiver.utils.custom_logger.logger.info")
metadata = Metadata().set_url("https://example.com") metadata = Metadata().set_url("https://example.com")
media = Media(filename="some_file.wacz") media = Media(filename="some_file.wacz")
metadata.add_media(media, id="browsertrix") metadata.add_media(media, id="browsertrix")

View File

@@ -5,6 +5,9 @@ from auto_archiver.modules.antibot_extractor_enricher.antibot_extractor_enricher
from .test_extractor_base import TestExtractorBase from .test_extractor_base import TestExtractorBase
CI = os.getenv("GITHUB_ACTIONS", "") == "true"
class DummySB: class DummySB:
def __init__(self, url="", title="", visible_texts=None, visible_elements=None): def __init__(self, url="", title="", visible_texts=None, visible_elements=None):
self._url = url self._url = url
@@ -51,14 +54,15 @@ class TestAntibotExtractorEnricher(TestExtractorBase):
@pytest.mark.download @pytest.mark.download
@pytest.mark.parametrize( @pytest.mark.parametrize(
"url,in_title,in_text,image_count,video_count", "url,in_title,in_text,image_count,video_count,skip_ci",
[ [
( (
"https://en.wikipedia.org/wiki/Western_barn_owl", "https://en.wikipedia.org/wiki/Western_barn_owl",
"western barn owl", "western barn owl",
"Tyto alba", "Tyto alba",
5, 4,
0, 0,
False,
), ),
( (
"https://www.bellingcat.com/news/2025/04/29/open-sources-show-myanmar-junta-airstrike-damages-despite-post-earthquake-ceasefire/", "https://www.bellingcat.com/news/2025/04/29/open-sources-show-myanmar-junta-airstrike-damages-despite-post-earthquake-ceasefire/",
@@ -66,6 +70,7 @@ class TestAntibotExtractorEnricher(TestExtractorBase):
"Bellingcat has geolocated", "Bellingcat has geolocated",
5, 5,
0, 0,
False,
), ),
( (
"https://www.bellingcat.com/news/2025/03/27/gaza-israel-palestine-shot-killed-injured-destroyed-dangerous-drone-journalists-in-gaza/", "https://www.bellingcat.com/news/2025/03/27/gaza-israel-palestine-shot-killed-injured-destroyed-dangerous-drone-journalists-in-gaza/",
@@ -73,6 +78,7 @@ class TestAntibotExtractorEnricher(TestExtractorBase):
"continued the work of Gazan journalists", "continued the work of Gazan journalists",
5, 5,
1, 1,
False,
), ),
( (
"https://www.bellingcat.com/about/general-information", "https://www.bellingcat.com/about/general-information",
@@ -80,6 +86,7 @@ class TestAntibotExtractorEnricher(TestExtractorBase):
"Stichting Bellingcat", "Stichting Bellingcat",
0, # SVGs are ignored 0, # SVGs are ignored
0, 0,
False,
), ),
( (
"https://vk.com/wikipedia?from=search&w=wall-36156673_20451", "https://vk.com/wikipedia?from=search&w=wall-36156673_20451",
@@ -87,13 +94,27 @@ class TestAntibotExtractorEnricher(TestExtractorBase):
"16 сентября 1985 года лейблом EMI Records.", "16 сентября 1985 года лейблом EMI Records.",
5, 5,
0, 0,
False,
),
(
"https://www.tiktok.com/@tracy_2424/photo/7418200173953830162",
"TikTok",
"Dito ko lang",
1,
0,
True,
), ),
], ],
) )
def test_download_pages_with_media(self, setup_module, make_item, url, in_title, in_text, image_count, video_count): def test_download_pages_with_media(
self, setup_module, make_item, url, in_title, in_text, image_count, video_count, skip_ci
):
""" """
Test downloading pages with media. Test downloading pages with media.
""" """
if CI and skip_ci:
pytest.skip("Skipping test in CI environment")
self.extractor = setup_module( self.extractor = setup_module(
self.extractor_module, self.extractor_module,
self.config self.config

View File

@@ -48,8 +48,6 @@ class TestGenericExtractor(TestExtractorBase):
("https://www.youtube.com/watch?v=5qap5aO4i9A", ["youtube"]), ("https://www.youtube.com/watch?v=5qap5aO4i9A", ["youtube"]),
("https://www.tiktok.com/@funnycats0ftiktok/video/7345101300750748970?lang=en", ["tiktok"]), ("https://www.tiktok.com/@funnycats0ftiktok/video/7345101300750748970?lang=en", ["tiktok"]),
("https://www.instagram.com/p/CU1J9JYJ9Zz/", ["instagram"]), ("https://www.instagram.com/p/CU1J9JYJ9Zz/", ["instagram"]),
("https://www.facebook.com/nytimes/videos/10160796550110716", ["facebook"]),
("https://www.facebook.com/BylineFest/photos/t.100057299682816/927879487315946/", ["facebook"]),
], ],
) )
def test_suitable_extractors(self, url, suitable_extractors): def test_suitable_extractors(self, url, suitable_extractors):
@@ -148,6 +146,7 @@ class TestGenericExtractor(TestExtractorBase):
def test_bluesky_download_video(self, make_item): def test_bluesky_download_video(self, make_item):
item = make_item("https://bsky.app/profile/bellingcat.com/post/3le2l4gsxlk2i") item = make_item("https://bsky.app/profile/bellingcat.com/post/3le2l4gsxlk2i")
result = self.extractor.download(item) result = self.extractor.download(item)
assert result.get_url() == "https://bsky.app/profile/bellingcat.com/post/3le2l4gsxlk2i"
assert result is not False assert result is not False
@pytest.mark.skipif(not TEST_TRUTH_SOCIAL, reason="Truth social download tests disabled in environment variables.") @pytest.mark.skipif(not TEST_TRUTH_SOCIAL, reason="Truth social download tests disabled in environment variables.")

View File

@@ -1,4 +1,5 @@
from datetime import datetime from datetime import datetime
import math
import pytest import pytest
@@ -147,14 +148,14 @@ class TestInstagramAPIExtractor(TestExtractorBase):
self.extractor.full_profile = True self.extractor.full_profile = True
mock_call.side_effect = [mock_user_response, mock_story_response] mock_call.side_effect = [mock_user_response, mock_story_response]
mock_highlights.return_value = None mock_highlights.return_value = 1
mock_stories.return_value = mock_story_response mock_stories.return_value = mock_story_response
mock_posts.return_value = None mock_posts.return_value = 2
mock_tagged.return_value = None mock_tagged.return_value = 3
result = self.extractor.download_profile(metadata, "test_user") result = self.extractor.download_profile(metadata, "test_user")
assert result.get("#stories") == len(mock_story_response) assert result.get("#stories") == len(mock_story_response)
mock_posts.assert_called_once_with(result, "123") mock_posts.assert_called_once_with(result, "123", max_to_download=math.inf)
assert "errors" not in result.metadata assert "errors" not in result.metadata
def test_download_profile_not_found(self, metadata, mocker): def test_download_profile_not_found(self, metadata, mocker):
@@ -175,10 +176,10 @@ class TestInstagramAPIExtractor(TestExtractorBase):
self.extractor.full_profile = True self.extractor.full_profile = True
mock_call.side_effect = [mock_user_response, Exception("Stories API failed"), Exception("Posts API failed")] mock_call.side_effect = [mock_user_response, Exception("Stories API failed"), Exception("Posts API failed")]
mock_highlights.return_value = None mock_highlights.return_value = 1
mock_tagged.return_value = None mock_tagged.return_value = 2
stories_tagged.return_value = None stories_tagged.return_value = None
mock_posts.return_value = None mock_posts.return_value = 4
result = self.extractor.download_profile(metadata, "test_user") result = self.extractor.download_profile(metadata, "test_user")
assert result.is_success() assert result.is_success()

View File

@@ -3,6 +3,8 @@ from datetime import date
import pytest import pytest
from auto_archiver.modules.telethon_extractor.telethon_extractor import TelethonExtractor
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def mock_client_setup(mocker): def mock_client_setup(mocker):
@@ -24,3 +26,37 @@ def test_setup_fails_clear_session_file(get_lazy_module, tmp_path, mocker):
assert session_file.exists() assert session_file.exists()
assert f"telethon-{date.today().strftime('%Y-%m-%d')}" in lazy_module._instance.session_file assert f"telethon-{date.today().strftime('%Y-%m-%d')}" in lazy_module._instance.session_file
assert os.path.exists(lazy_module._instance.session_file + ".session") assert os.path.exists(lazy_module._instance.session_file + ".session")
@pytest.mark.parametrize(
"url,expected",
[
("https://t.me/channel/123", True),
("https://t.me/c/123/456", True),
("https://t.me/channel/s/789", True),
("https://t.me/c/123/s/456", True),
("https://t.me/with_single/1234567?single", True),
("https://t.me/invalid", False),
("https://example.com/nottelegram/123", False),
],
)
def test_valid_url_regex(url, expected, get_lazy_module):
match = TelethonExtractor.valid_url.search(url)
assert bool(match) == expected
@pytest.mark.parametrize(
"invite,expected",
[
("t.me/joinchat/AAAAAE", True),
("t.me/+AAAAAE", True),
("t.me/AAAAAE", True),
("https://t.me/joinchat/AAAAAE", True),
("https://t.me/+AAAAAE", True),
("https://t.me/AAAAAE", True),
("https://example.com/AAAAAE", False),
],
)
def test_invite_pattern_regex(invite, expected, get_lazy_module):
match = TelethonExtractor.invite_pattern.search(invite)
assert bool(match) == expected

View File

@@ -55,6 +55,7 @@ class TestTiktokTikwmExtractor(TestExtractorBase):
("https://www.tiktok.com/@ggs68taiwan.official/video/7441821351142362375", True), ("https://www.tiktok.com/@ggs68taiwan.official/video/7441821351142362375", True),
("https://www.tiktok.com/t/ZP8YQ8e5j/", True), ("https://www.tiktok.com/t/ZP8YQ8e5j/", True),
("https://vt.tiktok.com/ZSMTJeqRP/", True), ("https://vt.tiktok.com/ZSMTJeqRP/", True),
("https://tiktok.com/@user/photo/123?lang=en", True),
], ],
) )
def test_is_suitable(self, url, is_suitable, tiktok_dropin): def test_is_suitable(self, url, is_suitable, tiktok_dropin):
@@ -68,10 +69,7 @@ class TestTiktokTikwmExtractor(TestExtractorBase):
mock_get.assert_called_once() mock_get.assert_called_once()
mock_get.return_value.json.assert_called_once() mock_get.return_value.json.assert_called_once()
# first message is just the 'Skipping using ytdlp to download files for TikTok' message # first message is just the 'Skipping using ytdlp to download files for TikTok' message
assert ( assert "Failed to parse JSON response from tikwm.com" in caplog.text
"failed to parse JSON response from tikwm.com for url='https://www.tiktok.com/@example/video/1234'"
in caplog.text
)
mock_get.return_value.json.side_effect = Exception mock_get.return_value.json.side_effect = Exception
with caplog.at_level("ERROR"): with caplog.at_level("ERROR"):
@@ -79,10 +77,7 @@ class TestTiktokTikwmExtractor(TestExtractorBase):
mock_get.assert_called() mock_get.assert_called()
assert mock_get.call_count == 2 assert mock_get.call_count == 2
assert mock_get.return_value.json.call_count == 2 assert mock_get.return_value.json.call_count == 2
assert ( assert "Failed to parse JSON response from tikwm.com" in caplog.text
"failed to parse JSON response from tikwm.com for url='https://www.tiktok.com/@example/video/1234'"
in caplog.text
)
@pytest.mark.parametrize( @pytest.mark.parametrize(
"response", "response",
@@ -98,27 +93,30 @@ class TestTiktokTikwmExtractor(TestExtractorBase):
assert self.extractor.download(make_item(self.VALID_EXAMPLE_URL)) is False assert self.extractor.download(make_item(self.VALID_EXAMPLE_URL)) is False
mock_get.assert_called_once() mock_get.assert_called_once()
mock_get.return_value.json.assert_called_once() mock_get.return_value.json.assert_called_once()
assert "failed to get a valid response from tikwm.com" in caplog.text assert "Unable to download with tikwm.com: " in caplog.text
@pytest.mark.parametrize( @pytest.mark.parametrize(
"response,has_vid", "response,is_success",
[ [
({"data": {"id": 123}}, False), ({"data": {"id": 123, "images": []}}, False),
({"data": {"wmplay": "url"}}, True), ({"data": {"wmplay": "url", "images": ["img1.jpg"]}}, True),
({"data": {"play": "url"}}, True), ({"data": {"play": "url", "images": ["img1.jpg"]}}, True),
({"data": {"images": ["img1.jpg"]}}, True),
], ],
) )
def test_correct_extraction(self, mock_get, make_item, response, has_vid, mocker): def test_correct_extraction(self, mock_get, make_item, response, is_success, mocker):
data = {k: v for k, v in response.get("data", {}).items()}
mock_get.return_value.status_code = 200 mock_get.return_value.status_code = 200
mock_get.return_value.json.return_value = {"msg": "success", **response} mock_get.return_value.json.return_value = {"msg": "success", **response}
result = self.extractor.download(make_item(self.VALID_EXAMPLE_URL)) result = self.extractor.download(make_item(self.VALID_EXAMPLE_URL))
if not has_vid: total_media = len(data.get("images", [])) + (1 if data.get("wmplay", data.get("play")) else 0)
assert result is False if is_success:
else:
assert result.is_success() assert result.is_success()
assert len(result.media) == 1 assert len(result.media) == total_media
else:
assert result is False
mock_get.assert_called() mock_get.assert_called()
assert mock_get.call_count == 1 + int(has_vid) assert mock_get.call_count == 1 + total_media
mock_get.return_value.json.assert_called_once() mock_get.return_value.json.assert_called_once()
def test_correct_data_extracted(self, mock_get, make_item): def test_correct_data_extracted(self, mock_get, make_item):
@@ -142,7 +140,9 @@ class TestTiktokTikwmExtractor(TestExtractorBase):
assert len(result.media) == 2 assert len(result.media) == 2
assert result.get_title() == "Title" assert result.get_title() == "Title"
assert result.get("author") == "Author" assert result.get("author") == "Author"
assert result.get("api_data") == {"other": "data", "id": 123} assert result.get("other") == "data"
assert result.get("comments") is None
assert result.get("api_data") == {"id": 123, "other": "data"}
assert result.media[1].get("duration") == 60 assert result.media[1].get("duration") == 60
assert result.get("timestamp") == datetime.fromtimestamp(1736301699, tz=timezone.utc) assert result.get("timestamp") == datetime.fromtimestamp(1736301699, tz=timezone.utc)

View File

@@ -13,7 +13,7 @@ class TestTwitterApiExtractor(TestExtractorBase):
config = { config = {
"bearer_tokens": [], "bearer_tokens": [],
"bearer_token": os.environ.get("TWITTER_BEARER_TOKEN", "TEST_KEY"), "bearer_token": os.environ.get("TWITTER_BEARER_TOKEN") or "TEST_KEY",
"consumer_key": os.environ.get("TWITTER_CONSUMER_KEY"), "consumer_key": os.environ.get("TWITTER_CONSUMER_KEY"),
"consumer_secret": os.environ.get("TWITTER_CONSUMER_SECRET"), "consumer_secret": os.environ.get("TWITTER_CONSUMER_SECRET"),
"access_token": os.environ.get("TWITTER_ACCESS_TOKEN"), "access_token": os.environ.get("TWITTER_ACCESS_TOKEN"),

View File

@@ -25,7 +25,7 @@ def orchestration_file(orchestration_file_path):
def autoarchiver(tmp_path, monkeypatch, request): def autoarchiver(tmp_path, monkeypatch, request):
def _autoarchiver(args=[]): def _autoarchiver(args=[]):
def cleanup(): def cleanup():
from loguru import logger from auto_archiver.utils.custom_logger import logger
if not logger._core.handlers.get(0): if not logger._core.handlers.get(0):
logger._core.handlers_count = 0 logger._core.handlers_count = 0

View File

@@ -118,8 +118,7 @@ def test_check_required_values(orchestrator, caplog, test_args):
with pytest.raises(SystemExit): with pytest.raises(SystemExit):
orchestrator.setup_config(test_args) orchestrator.setup_config(test_args)
assert "the following arguments are required: --example_module.required_field" in caplog.records[0].message
assert caplog.records[1].message == "the following arguments are required: --example_module.required_field"
def test_get_required_values_from_config(orchestrator, test_args, tmp_path): def test_get_required_values_from_config(orchestrator, test_args, tmp_path):

View File

@@ -6,7 +6,6 @@ import pytest
from auto_archiver.utils.misc import ( from auto_archiver.utils.misc import (
mkdir_if_not_exists, mkdir_if_not_exists,
expand_url,
getattr_or, getattr_or,
DateTimeEncoder, DateTimeEncoder,
dump_payload, dump_payload,
@@ -39,26 +38,6 @@ class TestDirectoryUtils:
assert existing_dir.exists() assert existing_dir.exists()
class TestURLExpansion:
@pytest.mark.parametrize(
"input_url,expected",
[("https://example.com", "https://example.com"), ("https://t.co/test", "https://expanded.url")],
)
def test_expand_url(self, input_url, expected, mocker):
mock_response = mocker.Mock()
mock_response.url = "https://expanded.url"
mocker.patch("requests.get", return_value=mock_response)
result = expand_url(input_url)
assert result == expected
def test_expand_url_handles_errors(self, caplog, mocker):
mocker.patch("requests.get", side_effect=Exception("Connection error"))
url = "https://t.co/error"
result = expand_url(url)
assert result == url
assert f"Failed to expand url {url}" in caplog.text
class TestAttributeHandling: class TestAttributeHandling:
class Sample: class Sample:
exists = "value" exists = "value"