Compare commits

..
945 Commits
Author SHA1 Message Date
Ozzie Isaacs e732b3b614 Output message only in production mode 2026-05-24 10:19:49 +02:00
Ozzie Isaacs 69f8767be5 Fixes from testrun 2026-05-17 10:21:19 +02:00
Ozzie Isaacs 6cbba6d170 Merge remote-tracking branch 'fix/commentxss' into Develop 2026-05-09 10:30:59 +02:00
Ozzie Isaacs 888ab4dc8f Update requirements 2026-05-09 10:28:12 +02:00
Ozzie Isaacs 753c19e700 Merge remote-tracking branch 'py314/py3.14-janeczku' into Develop 2026-05-09 10:24:58 +02:00
Ozzie Isaacs 4f9390332a Merge remote-tracking branch 'fix/attr' into Develop 2026-05-09 10:20:45 +02:00
Ozzie Isaacs ffddd85800 Merge remote-tracking branch 'fix/fixlter' into Develop 2026-05-09 10:19:57 +02:00
Ozzie Isaacs 652b0f20e0 Merge remote-tracking branch 'fix/token' into Develop 2026-05-09 10:17:57 +02:00
Ozzie Isaacs 598f08b916 Merge branch 'master' into Develop 2026-05-09 10:17:48 +02:00
Jacob Chapman 55cedba693 bump lxml to v6 for python 3.14 2026-04-29 22:05:40 -05:00
Jacob Chapman 10caf68d8b fix manifest reference 2026-04-29 22:05:40 -05:00
Ozzie Isaacs f4ed816f6e Fixes from testrun 2026-04-26 07:27:06 +02:00
Ozzie Isaacs ba77f41325 Merge remote-tracking branch 'fixes/notrace' 2026-04-25 16:04:51 +02:00
Ozzie Isaacs ea567fcbf0 Updated translation 2026-04-25 13:26:40 +02:00
Ozzie Isaacs edb05abcbe Merge remote-tracking branch 'tmp-orphan-on-download/fix-calibredb-cover-sibling' 2026-04-25 13:25:34 +02:00
Ozzie Isaacs 46811219ca Updated Requirements 2026-04-25 13:20:25 +02:00
Ozzie Isaacs 0aab0cac73 Merge remote-tracking branch 'tmp-orphan-on-download/fix-tmp-orphan-on-download' 2026-04-25 13:13:36 +02:00
Ozzie Isaacs 3257a36892 Merge remote-tracking branch 'ko/ko-translate-update' 2026-04-25 13:11:14 +02:00
limeade23 f10b680b0e Update Korean language 2026-04-23 17:41:46 +09:00
Ozzie Isaacs c2b1950cd5 Merge remote-tracking branch 'opds_date_update/fix-opds-atom-updated-reflects-modifications' 2026-04-20 15:55:24 +02:00
Ozzie Isaacs 00c8ff8ac4 Merge remote-tracking branch 'metadata-provider-none-crash/fix/metadata-provider-none-crash' 2026-04-20 15:49:26 +02:00
walrusec 0ca6e86177 Fix metadata search crash when ComicVine or Douban return None on error
Both comicvine.py and douban.py return None instead of [] when an HTTP
error occurs during a metadata search. The consumer in search_metadata.py
iterates the result directly, which raises TypeError: 'NoneType' object
is not iterable and crashes the server on single-threaded deployments.

Fixes #3606
2026-04-19 08:54:47 -04:00
haraldpdl ab17992ebb fix(opds): atom:updated reflects last modification, not date added
Books.atom_timestamp returned Books.timestamp (date added), which is
set at import and never changes. OPDS clients use atom:updated to
decide whether a book has changed on the server, so cover swaps,
metadata edits, and any other post-import change were invisible to
sync clients; they would keep serving the stale cover and title
until a manual refresh.

Atom RFC 4287 defines updated as "the most recent instant in time
when an entry or feed was modified", and Calibre already tracks that
field as last_modified, bumping it on every metadata and cover edit.
Switching the property to return last_modified (with a fallback to
timestamp when last_modified is NULL) aligns Calibre-Web's behaviour
with the Atom contract.

This change only affects the OPDS feed's atom:updated element. Kobo
sync uses its own last_modified comparison path, so it is unaffected.
2026-04-19 10:51:45 +02:00
haraldpdl 570371cc82 Don't write a cover sibling per download (--dont-save-cover)
calibredb export writes <uuid>.jpg next to <uuid>.<format> by
default, leaving an unused cover image in /tmp/calibre_web for
every download that goes through do_calibre_export. The cover
file is never read by calibre-web (cover serving uses a separate
path), so it is pure waste of disk space and IO.

Pass --dont-save-cover, paired with the existing --dont-write-opf,
to skip the unwanted side-effect at the source. Verified that
none of the three do_calibre_export call sites (download via
do_download_file, email via tasks/mail.py, kepubify via
tasks/convert.py) read the cover sibling.
2026-04-18 07:27:33 +02:00
haraldpdl 674b47bdbd Remove staged download from /tmp/calibre_web after response is sent
When config_embed_metadata is enabled with config_binariesdir or
config_kepubifypath set, do_download_file stages a copy of every
downloaded book under get_temp_dir() but never removes it. A bulk
OPDS or Kobo sync can fill the host filesystem in minutes; the
effect is amplified for comic formats (CBZ/CBR), where each
staged file can run to hundreds of MB or several GB. Once the
disk fills, downloads silently 404 and a container restart does
not recover the space.

Add an after_this_request hook that removes the staged copy after
the response is sent, gated on filename == get_temp_dir() so the
non-embed and gdrive-direct paths are untouched.
2026-04-18 07:12:38 +02:00
jvoisin 8cff413c4d Clean atributes as well in clean_string
`<img src=x onerror=alert(1)>` womp womp
2026-04-15 23:30:49 +02:00
jvoisin fd744af75d Don't give non-admin users a full stacktrace on 500
As `traceback.format_exc()` might contain internal file paths, library versions,
function names, and variable values.
2026-04-15 23:28:27 +02:00
jvoisin 6208d5e264 Correctly filter results kobo API
Multiple Kobo API endpoints use calibre_db.get_book_by_uuid() at db.py:748-749,
which performs a raw unfiltered query, meaning that common_filters() isn't
applied, so tag-based ACLs, language restrictions, and archived-book filtering
are all bypassed.
2026-04-15 23:14:09 +02:00
jvoisin 42dc36cc10 Escape comment columns names
Custom columns of type comments are rendered with `|safe` (disabling Jinja2
auto-escaping) and no `clean_string` sanitization. Compare with regular book
comments which correctly use `{{ entry.comments[0].text|clean_string|safe }}`.

Any user with edit permissions can set a custom comment column to
`<script>alert(document.cookie)</script>` and it will execute for every user who
views the book detail page or the OPDS feed. This is stored XSS with no
authentication barrier beyond edit permission.
2026-04-15 23:03:30 +02:00
jvoisin c23d35db4a Use 128 bits of entropy instead of only 32 in csp/ub.py
Remote login tokens are generated from only 4 bytes of randomness (32 bits = ~4
billion possibilities, 8 hex characters). The /ajax/verify_token endpoint at
remotelogin.py:98 has no rate limiting. The token is valid for 10 minutes.

At even modest request rates (10,000 req/sec), an attacker can test ~6 million
tokens during the 10-minute window , which isn't enough to exhaust the full
space, sure, but combined with multiple concurrent login sessions (each
generating a new token), or if the attacker can trigger the victim to initiate
remote login, the attack becomes more feasible. Compare with the Kobo auth
token which uses urandom(16) (128 bits).
2026-04-15 22:47:35 +02:00
Ozzie Isaacs fca580505c Fix typo 2026-04-15 20:31:40 +02:00
Ozzie Isaacs 19da54a7ae Merge remote-tracking branch 'fixes/escape_ldap' 2026-04-15 19:37:31 +02:00
Ozzie Isaacs 9c87f0fbde Merge remote-tracking branch 'fixes/fix_gdrive_md5' 2026-04-15 19:36:56 +02:00
Ozzie Isaacs e21f943712 Merge remote-tracking branch 'fixes/oauth_relink' 2026-04-15 19:36:48 +02:00
Ozzie Isaacs 4bb553f51d Merge remote-tracking branch 'fixes/noxxe' 2026-04-15 19:35:40 +02:00
Ozzie Isaacs 0615637f58 Merge remote-tracking branch 'fixes/nodebugleak' 2026-04-15 19:33:06 +02:00
Ozzie Isaacs a6c55deac6 Merge remote-tracking branch 'fixes/accessbp' 2026-04-15 19:31:29 +02:00
Ozzie Isaacs 2de8df7e0d Merge remote-tracking branch 'fixes/fix_kobo' 2026-04-15 19:28:55 +02:00
Ozzie Isaacs 4c1d7a9f6b Merge remote-tracking branch 'fixes/permshelf' 2026-04-15 19:28:12 +02:00
Ozzie Isaacs 9489905602 Merge remote-tracking branch 'fixes/chm' 2026-04-15 19:24:12 +02:00
Ozzie Isaacs 5e7c0c9d34 Merge remote-tracking branch 'fixes/sqlidb' 2026-04-15 19:23:01 +02:00
jvoisin b5da0df42a Prevent SQLI via dbpath
This is reachable only by the admin users, but is still a straightforward RCE
vector, if only via SQLite's `ATTACH DATABASE` trick
2026-04-14 23:23:12 +02:00
jvoisin 0959f84fd5 Use a sane permission for the encryption key file
The typical Linux umask of 0022, meaning the encrypted file is world-readable
(-rw-r--r--). Any OS-level user on the same system can read the key and decrypt
the encrypted credentials from app.db.
2026-04-14 23:08:35 +02:00
jvoisin 84777319d7 Fix access bypass on /show/ (serve_book)
The `serve_book` function uses `get_book()` which performs no access filtering:
it simply fetches by ID. Compare with `read_book` at web.py:1562 which
correctly uses `get_filtered_book()`. The `common_filters()` function enforces
per-user tag restrictions, language restrictions, and hidden-book rules.
2026-04-14 23:05:18 +02:00
jvoisin d85bef6c38 Don't leak credentials in debug_info
No need to dump Gmail OAuth client_secret, refresh_token, and
access_token in the debug ZIP in plaintext.
2026-04-14 22:55:08 +02:00
jvoisin 8ad9f4e3b7 Fix a dumb type condition in gdrive.py
hashlib.md5(dbpath) returns a hash object, not a hex string. Comparing a string
(md5Checksum) to a hash object with != always returns True. This means the
DB-replacement code path is always entered, allowing an attacker who sends a
forged notification (with the known static token) to trigger an arbitrary
metadata.db download from GDrive, replacing the live database.
2026-04-14 22:51:36 +02:00
jvoisin cde3888e17 Prevent LDAP injection in bind_user>get_object_details 2026-04-14 22:35:13 +02:00
jvoisin 387678a771 Prevent OAuth relinking.
When an OAuth provider_user_id is already linked to User A, and User B
authenticates with the same OAuth identity, User B is silently logged in as
User A. This is by design for single-user OAuth, but in a multi-user
environment it means: if an attacker gains access to the same OAuth provider
account (e.g., a shared GitHub org account, or by compromising the OAuth
provider), they can log in as the linked Calibre-Web user with no password
needed.
2026-04-14 22:28:06 +02:00
jvoisin c451daad3c Don't allow users to edit shelves they don't have permission to edit. 2026-04-14 22:25:36 +02:00
jvoisin 224915bba1 Prevent XXE in epub/fb2/goodreads API
The lxml.etree.fromstring() function use the default XML parser, which resolves
external entities because XML handling defaults in Python sucks. There is no
need for such dangerous misfeatures in calibre-web, so let's disable it.

A user able to upload epub/fb2 could add something like this to the file:

```xml
<?xml version="1.0"?>
<!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///etc/passwd">]>
<container><rootfiles><rootfile full-path="&xxe;"/></rootfiles></container>
```

and obtain the content of the `/etc/passwd` file, which is bad™.
2026-04-14 22:12:57 +02:00
jvoisin d598054195 Fix an IDOR in kobo tokens
Authenticated users shouldn't be able to generate/delete kobo auth tokens for
other users if they're not admin.
2026-04-14 22:10:30 +02:00
Ozzie Isaacs 088778969d Better error handling on series display in basic view 2026-04-06 15:28:10 +02:00
Ozzie Isaacs 0ed4d81da2 Better error handling on order parameter for sorting of user and books table 2026-04-06 15:12:09 +02:00
Ozzie Isaacs 9478325c23 Merge branch 'master' into Develop 2026-04-03 09:09:43 +02:00
Ozzie Isaacs 7c715f34dc Clean strings in comments before displaying 2026-04-03 09:01:01 +02:00
Ozzie Isaacs 00686ec1f2 Merge remote-tracking branch 'page_count/fix-series-list-view-sorts-by-name-instead-of-sort-field' 2026-03-07 10:24:58 +01:00
Ozzie Isaacs 83d331c89b Merge remote-tracking branch 'page_count/fix-kobo-prioritytimestamp-put-response' 2026-03-07 09:55:45 +01:00
Ozzie Isaacs f6338a9fda Merge remote-tracking branch 'filename/master' 2026-03-07 09:46:16 +01:00
Ozzie Isaacs 73efef17bd Merge branch 'master' into Develop 2026-03-07 09:36:19 +01:00
Ozzie Isaacs 74725b68b0 Merge remote-tracking branch 'it/patch-1' 2026-03-07 09:28:14 +01:00
mapi68 efbdd0b6e3 Update italian messages.po 2026-03-05 06:44:48 +01:00
jarynclouatre 1134f54be4 fix: series list view sorts by name instead of sort field
In series_list(), the SQLite query correctly orders results by
Series.sort, but a subsequent Python sorted() call (needed to
re-order after appending the "None" category entry) was using
Series.name as the sort key instead of Series.sort.

This caused series titles with leading articles (A, An, The) to
sort strictly alphabetically by the article rather than by the
meaningful word, e.g. "A Collins-Burke Mystery" appeared under
"A" instead of "C".

Fix by using Series.sort (with a fallback to Series.name if sort
is NULL) as the key in the Python re-sort, consistent with the
intent of the existing DB query.

Fixes #3583
2026-03-01 20:44:05 -06:00
jarynclouatre 2d4ca23d0c Kobo: include PriorityTimestamp in PUT /state response
Kobo: include PriorityTimestamp in PUT /state response
2026-03-01 18:19:40 -06:00
jarynclouatre 6157f5027c Update search_metadata.py
Fix TypeError when metadata provider returns None
2026-03-01 15:44:29 +01:00
Ozzie Isaacs 5e48a64b15 Merge remote-tracking branch 'opds-500-unauthenticated-request/fix/opds-500-unauthenticated-request' 2026-02-22 10:43:11 +01:00
Rafik Farhad 36a7ff19bc Fix AttributeError on unauthenticated OPDS requests
request_username() is used as flask-limiter's key_func for the OPDS
blueprint. The limiter evaluates key_func in a before_request handler,
before the route's auth decorator runs. When no Authorization header is
present, request.authorization is None, causing an AttributeError and
a 500 response instead of the expected 401.

Guard against None so unauthenticated requests fall back to an empty
string key, allowing the auth decorator to handle the 401 correctly.

Fixes #3592

Disclaimer: AI assisted—humans supervised.
2026-02-21 16:54:14 -06:00
Ozzie Isaacs 1b4f0d0967 Merge remote-tracking branch 'add-to-shelves-dropdown-menu/add-to-shelves-dropdown-menu' 2026-02-21 09:43:50 +01:00
Ozzie Isaacs 181117f916 Merge remote-tracking branch 'Kobo_sync/fix/kobo-library-sync-url-rewrite' 2026-02-21 09:42:09 +01:00
Ozzie Isaacs 32741be6c8 Merge remote-tracking branch 'kobo_sync/pr/fix-kobo-progress' 2026-02-21 09:31:56 +01:00
Ozzie Isaacs f64fe5d835 Merge remote-tracking branch 'Exclamationmark/chore_fix_error_messages' 2026-02-21 09:29:02 +01:00
Ozzie Isaacs 0db93a6036 Merge remote-tracking branch 'sort/master' 2026-02-21 09:27:04 +01:00
leahjessie a4bf028537 Fix Kobo popup when ProgressPercent is 0 by using is-not-None check instead of truthiness 2026-02-20 15:34:25 -08:00
AsukaVuuyn 47625a616d fix: support native UTF-8 downloaded filenames for browsers 2026-02-20 23:07:06 +08:00
Ozzie Isaacs 87635a5ace Merge branch 'Develop'
Update Requirements
Update Teststatus
2026-02-20 11:50:43 +01:00
Noé Sierra-Velasquez a9713bd497 Fix Kobo sync failure behind reverse proxy: rewrite library_sync URL in init response
The HandleInitRequest() function rewrites image URLs to point to the local
Calibre-Web instance, but library_sync was left pointing to storeapi.kobo.com.
This caused Kobo e-readers to call Kobo's servers for sync instead of the local
server, resulting in no books being synced when running behind a reverse proxy.
2026-02-19 20:34:50 +01:00
Ozzie Isaacs 8cef72b847 Updated requirements 2026-02-18 19:24:23 +01:00
Ozzie Isaacs fbed304df8 Better Fix for flask limiter 4.0 2026-02-18 19:11:38 +01:00
Ozzie Isaacs e3bf369ad6 Fix for flask limiter 4.0
Fix reseting flask_limiter keys
2026-02-18 18:59:29 +01:00
leahjessie d229f71151 Fix Kobo "Return to last page read" popup caused by float/int mismatch 2026-02-17 16:34:46 -08:00
Courville Software 3aef161cb8 fix title sort with "l'" in french
regex should not impose a space after "l'" otherwise detection for "L'arbre" fails.
2026-02-14 17:06:44 +01:00
Ozzie Isaacs cabcace3f0 Update translation
Fixes for flask_limiter version >4
2026-02-14 11:30:50 +01:00
Ozzie Isaacs 424e493946 Lower version of flask_limiter again 2026-02-14 11:30:15 +01:00
Ozzie Isaacs 848302f69e Merge branch 'master' into Develop 2026-02-14 10:21:05 +01:00
Ozzie Isaacs 8bdd95fc45 Fixes for flask_limiter > 4 2026-02-14 10:08:32 +01:00
Ozzie Isaacs 9c7a834cec Fix italian translation error 2026-02-13 19:18:00 +01:00
Ozzie Isaacs 51a2f36966 Revert flask_limiter version 2026-02-13 19:16:18 +01:00
Ozzie Isaacs b64645e5f5 Cover path is now selected based on correct setting and not if split_path is present or not (fix for #3527)
Version bump
Updated requirements
2026-02-08 12:12:34 +01:00
Ozzie Fernandez Isaacs bed8957eae Update pyproject.toml 2026-02-07 09:22:39 +01:00
Ozzie Fernandez Isaacs 0ce8c19e88 Update pyproject.toml 2026-02-06 21:59:49 +01:00
Ozzie Isaacs 5a1f3d8eec Version bump 2026-02-06 20:40:07 +01:00
lb803 315584690d remove exclamation marks 2026-02-05 21:40:45 +00:00
Ozzie Isaacs f14faff308 Merge remote-tracking branch 'cn/patch_cn' 2026-01-31 12:43:58 +01:00
Ozzie Isaacs 6f782c5687 Merge remote-tracking branch 'pt-br/translate-ptbr' 2026-01-31 12:40:01 +01:00
Ozzie Isaacs 7f7fc884c2 Fix for calibre 9.0 2026-01-31 12:31:44 +01:00
Webysther Sperandio 92084bab71 🌐 i18n(translations): typo 2026-01-31 05:51:04 +01:00
Webysther Sperandio f00471baf5 🌐 i18n(translations): add missing pt_BR translations in messages.po 2026-01-31 05:44:18 +01:00
Webysther Sperandio 9ed0774d19 doc: pt-br translation 2026-01-31 05:19:48 +01:00
Kamille eb20db55a4 Update Simplified Chinese 2026-01-31 11:25:50 +08:00
Webysther Sperandio a91724edb0 💄 style(css): include remove menu in dropdown scroll styling 2026-01-28 21:09:47 +01:00
Webysther Sperandio 5ad6b7fa64 💄 style(ui): limit add-to-shelves dropdown height
- 【style】 constrain add-to-shelves dropdown height and enable scroll
  - 【style】 prevent overly tall menus from overflowing the page
2026-01-26 19:39:36 +01:00
Webysther Sperandio c1be944a48 💄 style(ui): limit add-to-shelves dropdown height
- 【style】 constrain add-to-shelves dropdown height and enable scroll
  - 【style】 prevent overly tall menus from overflowing the page
2026-01-26 19:36:47 +01:00
Ozzie Isaacs e2c3c08d65 Merge remote-tracking branch 'origin/master' 2026-01-25 10:45:09 +01:00
Ozzie Isaacs 4fece545e4 Merge remote-tracking branch 'de/master' 2026-01-25 10:42:15 +01:00
Ozzie Isaacs 876a11dc58 Merge branch 'Develop'
Remove Get Parameter sort_param, where it is not valid (#3447)
Generate valid session-cookie-path(s) (fix for #3459)
Mass remove books from shelf (Fix for #3520)
2026-01-25 10:35:59 +01:00
Ozzie Isaacs 486914905e Merge branch 'Develop'
# Conflicts:
#	test/Calibre-Web TestSummary_Linux.html
2026-01-24 20:50:59 +01:00
Ozzie Isaacs d47af66499 Bugfix after testrun 2026-01-24 13:01:12 +01:00
Tom Chiverton 832ec80f1a Update README.md
Highlight how to enable uploads, as it's a FAQ
2026-01-21 18:46:47 +01:00
Kugeleis 85d1aab6a8 Add German translations for several UI strings 2026-01-18 18:07:51 +01:00
Ozzie Isaacs 8db0d004b6 Remove Get Parameter sort_param, where it is not valid (#3447) 2026-01-18 16:07:04 +01:00
Ozzie Isaacs c13eac91c8 Generate valid session-cookie-path(s) (fix for #3459) 2026-01-18 15:38:44 +01:00
Ozzie Isaacs cf3b619c73 Fix for #3520 (Mass remove books from shelf) 2026-01-18 12:59:40 +01:00
Ozzie Isaacs 269ab0e04e Fix for #3522 (Public registration does not apply default Allowed/Denied tags to new users ) 2026-01-17 12:27:16 +01:00
Ozzie Isaacs 47168f5ce9 Merge remote-tracking branch 'typo-epub-reader/webysther-deprecated-apple-meta' 2026-01-17 12:18:17 +01:00
Ozzie Isaacs 73d7306627 Merge remote-tracking branch 'typo-epub-reader/webysther-typo-epub-reader' 2026-01-17 12:16:45 +01:00
Ozzie Isaacs dd1cbb1018 Merge remote-tracking branch 'fr/patch-1' 2026-01-17 12:15:55 +01:00
Ozzie Isaacs 91fdf57b46 Update Teststatus 2026-01-17 12:14:13 +01:00
Webysther Sperandio d77d682ee0 Replace apple-mobile-web-app-capable with mobile-web-app-capable
https://web.dev/learn/pwa/web-app-manifest?hl=pt-br#designing_your_pwa_experience
2026-01-16 06:13:03 +01:00
Webysther Sperandio e2eed3d311 Update layout.html
https://web.dev/learn/pwa/web-app-manifest?hl=pt-br#designing_your_pwa_experience
2026-01-16 06:12:45 +01:00
Webysther Sperandio 54a47cfc18 Change meta tag for mobile web app capability
https://web.dev/learn/pwa/web-app-manifest?hl=pt-br#designing_your_pwa_experience
2026-01-16 06:12:21 +01:00
Webysther Sperandio b5dac9e1a7 Change meta tag for mobile web app capability
https://web.dev/learn/pwa/web-app-manifest?hl=pt-br#designing_your_pwa_experience
2026-01-16 06:12:02 +01:00
Webysther Sperandio b00abd283a Update readtxt.html
https://web.dev/learn/pwa/web-app-manifest?hl=pt-br#designing_your_pwa_experience
2026-01-16 06:11:29 +01:00
Webysther Sperandio 4821b2b34c Change meta tag from apple-mobile to mobile-web app
https://web.dev/learn/pwa/web-app-manifest?hl=pt-br#designing_your_pwa_experience
2026-01-16 06:10:54 +01:00
Webysther Sperandio 0e31be5357 Change meta tag for mobile web app capability
https://web.dev/learn/pwa/web-app-manifest?hl=pt-br#designing_your_pwa_experience
2026-01-16 06:10:36 +01:00
Webysther Sperandio dc19d40db1 Change meta tag for mobile web app capability
https://web.dev/learn/pwa/web-app-manifest?hl=pt-br#designing_your_pwa_experience
2026-01-16 06:10:05 +01:00
Webysther Sperandio 02b5409b95 TYPO
Fix theme selection prompt in read.html
2026-01-16 05:57:31 +01:00
Edouard Rouch 63cebcd849 Completed french translation
Added missing translations.
Corrected grammatical or spelling errors.
Harmonized recurring translations (Success !, Oops !, Show...)
2026-01-15 12:34:47 +01:00
Ozzie Isaacs 99e91e622e Change quoting of downloaded filename 2026-01-10 12:53:16 +01:00
Ozzie Isaacs 36ef81dd91 Make kobo resources editable (#3472) 2026-01-10 12:40:19 +01:00
Ozzie Isaacs 2700b4f0d1 Support kobo/auth/refresh endpoint 2026-01-10 12:20:52 +01:00
Ozzie Isaacs d73f9fdd6f Fix for #3515 (Exclude shelves with Advanced search not working correct) 2026-01-08 20:01:39 +01:00
Ozzie Isaacs be89c25a90 Merge branch 'master' into Develop 2026-01-08 19:58:48 +01:00
Ozzie Isaacs c5e9526fc8 Bugfix Exclude shelfs 2026-01-07 20:35:26 +01:00
Ozzie Isaacs a99960e6c5 Merge remote-tracking branch 'it/patch-1' 2026-01-05 15:06:41 +01:00
mapi68 8105f54ebb Update Italian language 2026-01-04 02:24:15 +01:00
Ozzie Isaacs d01010812b Merge remote-tracking branch 'fix_missing_progress_bar_for_cbz_file/fix_missing_progress_bar_for_cbz_file' 2025-12-29 14:37:11 +01:00
Julian_Chu 02fbef3dba Move progress css style to dedicated file
In kthoom implementation, there is also a DOM

    `<div id="progress"....>`

If this part of css style stays in main.css, it also effects the kthoom
implementation, therefore the progress bar will disappear when reading
comic files (such as cbz).
2025-12-29 18:49:44 +09:00
Ozzie Isaacs eb8b0096a1 Update Teststatus 2025-12-23 14:25:21 +01:00
Ozzie Isaacs 38b0af9ea2 Remove debug code 2025-12-20 13:22:20 +01:00
Ozzie Isaacs 83b5d0f22b Merge remote-tracking branch 'replace_archive_icon/chore_replace_archive_icon' 2025-12-14 14:45:46 +01:00
Ozzie Isaacs 38c58bd7c9 Merge remote-tracking branch 'pl/patch-1' 2025-12-14 14:44:46 +01:00
Ozzie Isaacs 6276806c0e Merge remote-tracking branch '401/patch-1' 2025-12-14 14:40:49 +01:00
Evan Goldenberg 97a8fc661f Send WWW-Authenticate header with 401 responses 2025-12-10 00:06:32 -08:00
lb803 0569c644a3 change archive button icon from glyphicon-trash to glyphicon-folder-open 2025-12-09 21:44:36 +00:00
szepix 3565e5f068 Updated polish translations
Did all missing translations
2025-12-08 12:53:57 +01:00
Ozzie Isaacs 8b8bc1b688 Merge remote-tracking branch 'show-shelf-size/show-shelf-size'
Added some missing texts to caliblur theme
Caliblur theme fix language icon
2025-12-07 19:32:40 +01:00
Ozzie Isaacs ff9dabadf1 Merge remote-tracking branch 'cache/master' 2025-12-07 18:27:58 +01:00
Ozzie Isaacs a75d0caa02 Merge remote-tracking branch 'it/patch-1' 2025-12-07 14:32:58 +01:00
Ozzie Isaacs eb872865a5 Merge Reader improvements 2025-12-07 14:31:16 +01:00
Ozzie Isaacs 8031fff5af Merge branch 'Develop' 2025-12-07 10:55:04 +01:00
Ozzie Isaacs ac1ae66246 Merge branch 'master' into Develop 2025-12-07 10:54:40 +01:00
mapi68 310443afc5 Update italian 2025-12-07 04:08:44 +01:00
Ozzie Isaacs 25c9aba469 Fix vertical scrollbar in list.html 2025-12-06 19:26:30 +01:00
Ozzie Isaacs 3a3c8ad2a4 Merge remote-tracking branch 'lock-header-sidebar' 2025-12-06 13:21:23 +01:00
Ozzie Isaacs 10816c7f6d Merge remote-tracking branch 'performance_optimize-search-queries/performance/optimize-search-queries' into Develop 2025-12-06 11:54:28 +01:00
Ozzie Isaacs adcfd8afe8 Merge remote-tracking branch 'cn/patch-1'
Updated requirements
2025-12-06 11:52:18 +01:00
Ozzie Isaacs 74a386a284 Merge branch 'master' into Develop 2025-12-06 11:50:00 +01:00
Ozzie Isaacs fceca5cc08 Merge remote-tracking branch 'performance_optimize-search-queries/performance/optimize-search-queries' into Develop
Updated Requirements
2025-12-06 11:36:02 +01:00
Arlen Cole 13b515d3ab Update Chinese translations in messages.po 2025-12-06 13:54:25 +08:00
Ozzie Isaacs d2015dd998 Optimized search query 2025-12-05 16:33:30 +01:00
Ozzie Isaacs 3959a8eddd Caliblur theme display fix
Rename Gooble Books Metadata provider
2025-12-04 18:52:30 +01:00
Ozzie Isaacs ca63d343bd Merge remote-tracking branch 'resolution/Develop' into Develop 2025-12-04 18:51:37 +01:00
Ozzie Isaacs ecc6e00bfc Sort names before trying to extract coverfile of comics 2025-12-04 14:19:58 +01:00
root c1114cd786 Fix display issue on small width resolution with fetch metadata form on caliblur theme
Renamed Google metadata provider to Google Books
2025-11-27 19:07:16 +00:00
Ozzie Isaacs cf01bd7ad4 Merge remote-tracking branch 'kobo_tree/fix/kobo-store-proxy-routing' 2025-11-22 15:32:30 +01:00
Ozzie Isaacs cf1b3bb37f Merge remote-tracking branch 'de/patch-1' 2025-11-22 15:29:39 +01:00
Ozzie Isaacs 70fefa2f11 Merge remote-tracking branch 'de/patch-1' 2025-11-22 15:17:49 +01:00
Ozzie Isaacs 80df8b1fa6 Merge remote-tracking branch 'ko/patch-1' 2025-11-22 15:16:13 +01:00
Ozzie Isaacs cac33165dc Merge remote-tracking branch 'fr/patch-1' 2025-11-22 15:14:59 +01:00
Ozzie Isaacs bf2ab66362 Merge remote-tracking branch 'ga/patch-1' 2025-11-22 15:13:49 +01:00
Ozzie Isaacs 5e14b4bf41 Merge remote-tracking branch 'ga/patch-2' 2025-11-22 15:13:13 +01:00
Ozzie Isaacs a6fdd8ab36 Updated testresults
Fix goodreads
Remove unused import
Limit number of routes for book pages
2025-11-22 15:06:40 +01:00
Félix Pardal González d091b9d8b9 Update Galician translations in messages.po
Edited msgstr entried adding translation to Galician.
2025-11-22 13:43:28 +01:00
Félix Pardal González 2eb7c0d3f0 Update Spanish translations for various messages
Reviewed msgid entries and added spanish translation in msgstr entries.
2025-11-22 13:30:53 +01:00
Nico31240 54eb30e2b9 Update messages.po French 2025-11-12 10:30:42 +01:00
shsm0520 47f44d71cf Update Korean translations in messages.po
updated translate
2025-11-05 21:54:59 -05:00
Aljosa Asanovic 654095054f fix(kobo): add catch-all route for proxying unknown product endpoints
The Kobo store proxy feature was failing with 404 errors for certain
store endpoints (e.g., /v1/products/featuredforkoboplus/) because
Flask's routing couldn't match these paths. This prevented the Discover
tab from working when "Proxy unknown requests to Kobo Store" was enabled.

Added catch-all routes using Flask's path converter to match any
/v1/products/* paths not handled by more specific routes, allowing
the proxy logic to properly redirect these requests to the official
Kobo store API.
2025-11-02 13:10:25 -05:00
alcibiadesc 8544702bb2 Add security fixes and improvements to search optimization
- Add FTS5 table existence check to avoid log spam on non-FTS databases
- Escape FTS5 special characters (quotes) to prevent query errors
- Wrap FTS5 search terms in quotes for phrase matching accuracy
- Improve logging: change author ordering debug to warning for visibility
- Add comment explaining author_sort data issues

These changes improve robustness and security without affecting performance.
2025-11-01 20:05:53 +01:00
alcibiadesc a3b5d2eac7 Optimize search performance for large libraries
This commit introduces several performance optimizations to the search
system, significantly reducing query times for large Calibre libraries.

Key improvements:

1. FTS5 Integration
   - Added FTS5 full-text search support with automatic fallback
   - Uses indexed search when available, providing sub-second results
   - Gracefully degrades to traditional search if FTS5 is unavailable

2. Query Optimization
   - Replaced expensive .any() subqueries with efficient JOIN-based
     subqueries for tags, series, authors, and publishers
   - Reduced SQL complexity and improved query planning
   - Added selectinload() for authors to prevent N+1 query problems

3. LIMIT+1 Pattern
   - Implemented LIMIT+1 estimation pattern in get_search_results()
   - Avoids expensive COUNT(*) operations on large result sets
   - Provides fast pagination without sacrificing accuracy

4. Author Ordering Optimization
   - Replaced nested database queries with O(1) dictionary lookups
   - Eliminated N+1 query anti-pattern in order_authors()
   - Reduced author sorting from O(n²) to O(n) complexity

Performance Impact:
In testing with a library of 129,000+ books, these optimizations reduced
search times from 3-9 seconds to 85-330ms, achieving 89-97% improvement
across different search types.

The changes maintain backward compatibility and include fallbacks for
environments without FTS5 support.
2025-11-01 19:48:16 +01:00
IgorKurkov bba7812a07 feat(epub.js): add autosaving of current book reading position in localStorage to open this book on the last read point 2025-10-29 22:20:08 +01:00
IgorKurkov 458d0d1e3d feat(read.html, epub): add custom theme selection with color picker, used pickr.js 2025-10-29 22:10:08 +01:00
IgorKurkov 6d6d5ac097 add books button, add page count on bottom and in settings, add swipe for closing sidebar, fix settings modal, fix few styles 2025-10-29 22:06:09 +01:00
IgorKurkov 560e8e132d add swipes by gestures in settings as an option, hammer.js for mobile 2025-10-29 20:37:15 +01:00
schnabelewobski 3433b62864 Update messages.po
Added some missing German translations.
2025-10-29 14:03:04 +01:00
IgorKurkov d8fbf967b3 add console process interruption by ctrl C 2025-10-26 21:28:58 +01:00
IgorKurkov 902368efa7 feat(epub.js): add saving for settings of the font family to localstorage 2025-10-26 18:47:56 +01:00
IgorKurkov c5571fc359 feat(epub.js): add font size selector with precised + and - controls 2025-10-26 18:40:52 +01:00
IgorKurkov 132c17151a feat(epub.js): add font size saving in localstorage like theme saving 2025-10-26 18:24:44 +01:00
IgorKurkov 1ce1aee35e fix(js reader): adjust height to dynamic viewport height, add amber theme 2025-10-26 18:23:07 +01:00
Sebastian Holzer 4dc8948199 Some more fixes for some German translations in messages.po
Added some more translations that I stumbled over. Also added my name to it.
Please note however, the translation in line 3120 (book will be deleted from database) and the next translation (from hard disk) don't work well that way in german. Please consider defining two separate translations (one with and one without the hard disk). The german translation grammatically works the way I committed it here, but it's really not how one would write it if they had a choice. The "gelöscht" should always be at the end in german.
2025-10-22 20:02:04 +02:00
Sebastian Holzer 7db6481704 Added missing and fixed some existing German translations in messages.po
Updated German translations in messages.po, correcting various phrases and ensuring consistency. But most importantly added missing translations. Didn't check all translations though, just those that catched my attention
2025-10-22 19:47:25 +02:00
Ozzie Isaacs 6b11d0b4f3 Removed fuzzy translated strings which cause error during language compiling 2025-09-12 08:50:03 +02:00
Ozzie Isaacs c30d550ee1 Merge remote-tracking branch 'zh_Hant_TW/master' 2025-09-12 08:32:05 +02:00
Ozzie Isaacs c902fe1c5a Merge remote-tracking branch 'fr/master' 2025-09-12 08:28:27 +02:00
Ozzie Isaacs a6fe639e2f Merge remote-tracking branch 'it/patch-1' 2025-09-12 08:27:55 +02:00
mapi68 e1bce5d5fe Update italian messages.po 2025-09-11 01:36:07 +02:00
Ganfoud 5057e68b84 Add files via upload
FR translation update
2025-09-10 21:26:01 +02:00
Finrod Chen f88e776b1f Update zh_Hant_TW translations. 2025-09-10 11:56:43 +08:00
Ganfoud 957c906e53 Add files via upload
added some fr translations
2025-09-09 22:21:02 +02:00
Ozzie Isaacs cfda7f109a Merge remote-tracking branch 'books_api/cjwin2000-google_books_apikey' 2025-09-09 09:59:49 +02:00
Ozzie Isaacs 9fcd636533 Omit exporting of api strings 2025-09-09 09:40:37 +02:00
Ozzie Isaacs 0e50794d9b Testrun 2025-09-09 09:08:37 +02:00
Ozzie Isaacs 714c19f558 Some code cosmetics 2025-09-08 17:31:43 +02:00
Ozzie Isaacs c2d2db913e Merge remote-tracking branch 'opds/opds_improvements' 2025-09-08 15:59:33 +02:00
Ozzie Isaacs e3537235ca Merge remote-tracking branch 'fix_booklist_read_status/fix_booklist_read_status' 2025-09-08 12:52:25 +02:00
Ozzie Isaacs dc5663f21f Merge remote-tracking branch 'nl/patch-1' 2025-09-08 12:22:27 +02:00
Ozzie Isaacs dcc091e354 Merge remote-tracking branch 'instapaper/patch-1' 2025-09-08 12:07:32 +02:00
Ozzie Isaacs 4ad747decf Merge branch 'Develop' 2025-09-08 12:06:11 +02:00
Ozzie Isaacs 0d07e445de Bugfix mass edit books 2025-09-08 12:05:59 +02:00
Hot Garbage 9e7efb187b kobo: add Instapaper config
Latest firmware version writes empty values for Instapaper parameters if missing from the /initialization response.
Add default values to `NATIVE_KOBO_RESOURCES`
2025-09-01 12:15:06 -07:00
Ozzie Isaacs d480c55bcb Uodate optional-requirements.txt 2025-08-25 15:52:41 +02:00
Ozzie Isaacs 0ff1feaef0 Update optional-requirements.txt (#3446) 2025-08-25 14:43:39 +02:00
Ozzie Isaacs 0bfe6de62a Add certifi to requirements for Mac computer (fix for #3385) 2025-08-24 11:02:50 +02:00
Ozzie Isaacs 776eeccc67 Version bump 2025-08-24 09:50:41 +02:00
rjaakke b632f1b9a2 Update get_filtered_book call to include archived books. 2025-08-18 20:31:31 +02:00
Syer10 9aab6d90f7 Keep tags since its now in html 2025-08-15 11:51:14 -04:00
Syer10 5cd914f007 Fix newlines 2025-08-15 11:41:38 -04:00
Syer10 3a899afcce Opds Improvements 2025-08-15 11:10:14 -04:00
Peter Kraus 7418c2c0b4 Update messages.po
Dutch translations almost completely finished
2025-08-15 15:39:07 +02:00
Ozzie Isaacs 91e36b2c7e Testrun
Use getPath more often
2025-08-09 12:11:11 +02:00
Ozzie Isaacs e86833a2a9 Updated requirements 2025-08-05 20:10:44 +02:00
Ozzie Isaacs f3a4df1759 Merge branch 'master' into Develop 2025-07-04 20:22:11 +02:00
Ozzie Isaacs 4fe28028ea Merge remote-tracking branch 'arabic/add-arabic-translation' 2025-06-29 09:46:23 +02:00
Ozzie Isaacs e2c88b3a33 Merge remote-tracking branch 'lazy/patch-1' 2025-06-29 09:29:43 +02:00
Ozzie Isaacs f58c8eb916 Merge remote-tracking branch 'lazy/master' 2025-06-29 09:28:34 +02:00
Ozzie Isaacs 8938598aab Merge remote-tracking branch 'caliblur_fixes/book-table-layout' into Develop 2025-06-29 09:01:11 +02:00
Ozzie Isaacs 7472cdf43f Merge remote-tracking branch 'caliblur_fixes/css-speedup' into Develop 2025-06-29 08:54:31 +02:00
Ozzie Isaacs 6f5af36ecf Merge remote-tracking branch 'identifiers/ebooks_identifier' 2025-06-28 14:01:41 +02:00
Ozzie Isaacs 7c1d372086 Updated translation 2025-06-28 13:59:55 +02:00
Ozzie Isaacs 37b9ee9b0d Merge remote-tracking branch 'updated_translation/patch-1' 2025-06-28 13:58:46 +02:00
Ozzie Isaacs bcfdeacf15 Decode calibre traceback to str 2025-06-28 13:54:03 +02:00
Usama Khalil cb588c2c82 Update messages.po
Correcting typo, separate line 9 & 10.
Poedit (v2.2) compined line 9 & 10 into one line.
2025-06-07 15:04:05 +03:00
Usama Khalil 0b777c47bb Add Arabic translation (messages.po & messages.mo) files. 100% done 2025-06-07 14:47:04 +03:00
Ozzie Isaacs 4dce8abb1d Merge remote-tracking branch '403/fix/thumnbails_route_sso' 2025-06-01 10:37:32 +02:00
Ozzie Isaacs f27d62e22c Merge remote-tracking branch 'overdrive/master' 2025-06-01 10:33:09 +02:00
Landon Cheek 0eb8583dce Allow POST requests issued during Overdrive book returns to be proxied
Addresses janeczku/calibre-web#3398
2025-05-23 12:37:45 -06:00
Kamil Markowicz 6f969ed6a6 fix: fixes 403 when using proxy auth
Resolves a 403 response when accessing /ajax/updateThumbnails from a
session authenticated by reverse proxy.

For some reason, the decorators are swapped on this route specifically,
but not the others. This brings the ordering to be consistent with other
routes. The login check should happen before the auth check now.
2025-05-09 22:31:06 -04:00
Oskar Manhart 707c41c48a feat: lazy-load images 2025-05-04 18:22:46 +02:00
Oskar Manhart 054256067a Merge remote-tracking branch 'upstream' 2025-05-04 11:46:07 +02:00
Asher Max Schweigart 8c0891a078 Updating translation files 2025-04-29 14:33:19 -04:00
Asher Max Schweigart cc0fbd7ce8 Adding Smashwords identifier 2025-04-29 14:31:19 -04:00
Asher Max Schweigart 4e245def8f Moving scrollbar to main panel instead of the body to lock header and sidebar in place 2025-04-29 14:20:17 -04:00
Asher Max Schweigart 50be750460 Updating translation files 2025-04-28 12:42:16 -04:00
Asher Max Schweigart 5127061775 Updating translation template 2025-04-28 12:22:28 -04:00
mapi68 0d2611c8a0 Update messages.po 2025-04-15 00:51:31 +02:00
Asher Max Schweigart 521b46e60d Adding eBooks.com identifier type 2025-04-14 14:05:26 -04:00
Missing Link 36a99b0b5c Fix traceback encoding 2025-04-12 03:59:32 +08:00
David Champion d32ad1d5ca Show shelf sizes in layout 2025-04-03 13:14:15 -07:00
quarz12 7029fa8b60 fix 2025-04-02 21:56:11 +02:00
quarz12 8c98b91a25 hide desktop navbar when in mobile resolution 2025-04-02 20:53:22 +02:00
Kevin Rauwolf feac864e73 Rename CACHE_DIR env var to CACHE_DIRECTORY (#3343) 2025-04-01 01:13:45 -07:00
Ozzie Isaacs d75adfe85e Improved testability 2025-03-31 19:06:53 +02:00
Ozzie Isaacs 4e67a56ed2 Merge remote-tracking branch 'ger/fix/de-translation' 2025-03-30 15:55:57 +02:00
Ozzie Isaacs dbdaa0884e Merge branch 'master' into Develop 2025-03-30 13:48:08 +02:00
Ozzie Isaacs 2b2ccb1710 Refactored epub-reader progress
Progress in epubs now visible also in dark mode(s)
2025-03-30 12:23:13 +02:00
Ozzie Isaacs 4583fc8023 Python 3.13 compatibility
Code cosmetics
2025-03-30 12:03:12 +02:00
Ozzie Isaacs 1b1b7455d2 Merge branch 'master' into Develop 2025-03-30 09:42:58 +02:00
Ozzie Isaacs daaf7337ab Update Testresults 2025-03-30 09:42:31 +02:00
Ozzie Isaacs 2c9d4d2487 Merge remote-tracking branch 'djvu_mimetype/new_djvu_mimetyp' 2025-03-30 09:17:59 +02:00
Ozzie Isaacs af09b50153 Merge remote-tracking branch 'modal/master' 2025-03-30 09:05:24 +02:00
Ozzie Isaacs b8c3674be9 Merge remote-tracking branch 'storygraph/storygraph-id' 2025-03-30 09:00:01 +02:00
Ozzie Isaacs 65a29ed4c9 Log exception for unhandled errors in background tasks 2025-03-30 08:58:56 +02:00
Ozzie Isaacs 854a7d020d Better error output for "empty" Author sort not working
Update bleach requirement
2025-03-28 17:23:45 +01:00
Ozzie Isaacs a215b73e39 Lower requirement of cryptography 2025-03-28 16:52:10 +01:00
Ozzie Isaacs 6bfe022de0 Update Teststatus 2025-03-26 06:56:53 +01:00
Ozzie Isaacs c6cde961b6 Revert Change to reenable change database function 2025-03-25 06:08:08 +01:00
Ozzie Isaacs d08acdc3cc Merge branch 'master' into Develop 2025-03-24 18:59:12 +01:00
Ozzie Isaacs 86e6161b89 Remove testing code 2025-03-23 15:29:03 +01:00
Ozzie Isaacs 646937272a Updates dependencies
Update logger ->filename is logged instead of responsible logger
2025-03-23 15:12:06 +01:00
Ozzie Isaacs 6dd7a023f3 Improved error handling for invalid recipient address 2025-03-23 14:13:02 +01:00
Ozzie Isaacs f0077e73a8 Merge remote-tracking branch 'mail_id/patch-1' 2025-03-23 09:22:14 +01:00
Ozzie Isaacs e485f10e9e List locale alphabetically 2025-03-23 09:18:48 +01:00
Ozzie Isaacs 81a0b15a3d Merge remote-tracking branch 'button/fix-setup-form' 2025-03-23 08:49:29 +01:00
Ozzie Isaacs 89577914ba Merge remote-tracking branch 'fix-js-content-type/fix-js-content-type' 2025-03-23 08:46:27 +01:00
Ozzie Isaacs c289cb5d4b Fix sync fails with error when "Synchronize Notebooks" enabled 2025-03-23 08:44:55 +01:00
Ozzie Isaacs fd88dd2383 Merge remote-tracking branch 'Kobo_pen/Develop' into Develop 2025-03-23 08:44:11 +01:00
Ozzie Isaacs 80bcfb12de Add UniDecodeError to catched errors during kobo sync check layout 2025-03-23 08:41:18 +01:00
Ozzie Isaacs 46f111cd6e Better error handling during proxying kobo requests (fix for #3334) 2025-03-23 07:56:14 +01:00
Ozzie Isaacs bcb72d780f Testupdate 2025-03-23 07:24:46 +01:00
antar37 3d9594cfaa Update mail.py
using make_msgid to create a well-formed  message-ID. The lack of brackets causes gmail to reject the message-ID
2025-03-20 12:43:56 -06:00
Jayson Rhynas bc0e218e73 Added support for storgraph: identifiers 2025-03-18 11:51:43 -04:00
Theo Psallidas f9267ba391 Fix modal for smaller devices [smartphone] 2025-03-17 19:13:25 +02:00
Louis eb02c9e5d4 Fix to use common djvu mimetype 2025-02-25 12:49:31 +01:00
Jørgen V 2f6322b0ee Fix #2849 2025-02-23 22:17:01 +01:00
Ross Williams 22a93a28e2 Refactor epub reader progress calculation
The code in epub-progress.js was causing the epub file to be loaded
twice over the network, because it created a second instance of the
epub.js library. I moved all the progress percentage display code into
epub.js. Only the locationchange polyfill code was left in the separate
file, renamed to locationchange-polyfill.js.

I rewrote the percentage progress code to use epub.js events,
giving more succinct and readable code. Also, I added localStorage
caching of the epub location calculations, required for displaying
percentage progress, which can take up to 60-90 seconds to calculate on
longer ebooks. This localStorage caching approach is recommended by
epub.js in the `locations.html` example in their repo.

Signed-off-by: Ross Williams <ross@ross-williams.net>
2025-02-21 04:15:37 +00:00
Juan Orti Alcaine 1ee49791f4 Remove duplicated 'charset' in Content-Type header for Javascript files
Javascript files are served over HTTP with an incorrect Content-Type
header because the 'charset' option is duplicated:

    $ curl -I http://127.0.0.1:8083/static/js/table.js
    HTTP/1.1 200 OK
    Content-Disposition: inline; filename=table.js
    Content-Type: text/javascript; charset=UTF-8; charset=utf-8
    Content-Length: 35967
    Last-Modified: Sat, 16 Nov 2024 06:21:28 GMT
    Cache-Control: no-cache
    ETag: "1731738088.0-35967-471731799"
    Date: Sat, 08 Feb 2025 16:30:42 GMT
    Content-Security-Policy: default-src 'self' 'unsafe-inline' 'unsafe-eval'; font-src 'self' data:; img-src 'self' data:; object-src 'none';
    X-Content-Type-Options: nosniff
    X-Frame-Options: SAMEORIGIN
    X-XSS-Protection: 1; mode=block
    Strict-Transport-Security: max-age=31536000

This header is not RFC 1521 compliant and it's breaking some reverse
proxy setups that perform compression. See this bug for reference:

https://github.com/crocodilestick/Calibre-Web-Automated/issues/217
2025-02-08 17:29:02 +01:00
Robbinsch 90bccb86ef fix: right html in config_db 2025-01-25 17:52:01 +01:00
Tobias Bayer ff6b341c36 Fix more German translation strings 2025-01-13 10:21:33 +01:00
Tobias Bayer 9d3b2b007b Fix German translation 2025-01-12 14:23:23 +01:00
cjwin2000 dbf104787c Update google.py 2025-01-10 20:31:17 -05:00
cjwin2000 bf31e675db Update config_edit.html 2025-01-10 20:28:09 -05:00
cjwin2000 7e24890991 Update admin.py 2025-01-10 20:20:08 -05:00
cjwin2000 4cf4c4dfe6 Update config_sql.py 2025-01-10 20:14:17 -05:00
Ozzie Isaacs efc7ce31d2 Fix kindle download handling 2025-01-06 17:38:25 +01:00
Ozzie Isaacs 4ccc2c0aec Handle kindle browser download filename can only contain ASCII characters (#3266) 2025-01-06 17:36:17 +01:00
Ozzie Isaacs 4512ab4524 Renamed pdf reader javascript files (#3277) 2025-01-06 14:54:09 +01:00
Ozzie Isaacs 0ef9e46133 Merge remote-tracking branch 'colorspace/fix-colorspace-transformation' 2025-01-06 07:03:23 +01:00
Ozzie Isaacs 88a06deb8c Merge remote-tracking branch 'caliblur/fix-upload-styling' 2025-01-06 07:01:50 +01:00
Wouter Koch e4f1ce9c5a Transform color space to srgb instead of rgb to prevent dark images 2025-01-05 01:49:46 +01:00
James McNee f5048ee1a8 Fix UI bug when book conversion enabled on mobile
On mobile, when book conversion is enabled and using the cabliBlur theme, the upload menu appears behind the description text area making it difficult (though not impossible with some careful guesswork around where the buttons should be).

This commit fixes the styling of this section so that it no longer appears behind the description text area.
2025-01-04 11:51:35 +00:00
Ozzie Isaacs e531bc0f0c Fixes from Test 2025-01-04 06:54:34 +01:00
Ozzie Isaacs f78a2367a2 Fix title sort, author sort setting for multi book table editing 2024-12-31 11:54:32 +01:00
Ozzie Isaacs 928ed10c2e Improved error handling on mass edit list 2024-12-29 20:12:27 +01:00
Ozzie Isaacs e7c2a85fd4 Fix for uploading azw files (#3263) 2024-12-22 13:11:59 +01:00
Ozzie Isaacs 32d120bd39 Fix for (#3261 handle permission error on generating new folders during rename of authors) 2024-12-21 11:36:18 +01:00
Ozzie Isaacs be5247a2ef Fix for (#3261 handle permission error on generating new folders during rename of authors) 2024-12-21 11:30:02 +01:00
Ozzie Isaacs ee7f393e67 enable mobi and rtf files for upload (fix for #3258) 2024-12-15 19:58:29 +01:00
Ozzie Isaacs 14bb01010d Bugfix edit books list (delete value) 2024-12-15 16:09:11 +01:00
Ozzie Isaacs 71686e4490 Merge remote-tracking branch 'it/patch-1' 2024-12-15 07:20:37 +01:00
mapi68 ea1ba54a9d Update messages.po 2024-12-15 06:40:46 +01:00
Ozzie Isaacs 0afba50953 Merge branch 'master' into Develop 2024-12-14 14:54:00 +01:00
Ozzie Isaacs 659535f5de update Galician translation 2024-12-14 14:52:06 +01:00
Ozzie Isaacs d977d1b81b Add title tag to opds feed
Enable Kepub format for epub Reader
2024-12-14 14:49:28 +01:00
Ozzie Isaacs 24fdadbeb6 Update error handling book table edit 2024-12-14 14:39:17 +01:00
Ozzie Isaacs 08527ae3ce Update mass edit
Refactored delete User function
Updated testresults
2024-12-13 18:03:14 +01:00
Aleksei Besogonov 01215aaa68 Allow the web reader to use KEPUB files and print file sizes
This commit allows the web reader to read the KEPUB (Kobo EPUB) files,
and also shows the file sizes. This is especially useful if you have
giant EPUB files with built-in audiobooks and media overlays.
2024-12-08 23:30:05 -08:00
Aleksei Besogonov ed600a9aeb Add a title to OPDS links
This allows the OPDS consumers to distinguish `epub` and `kepub` files
as they have the same MIME-type.
2024-12-08 17:29:03 -08:00
pollitor e542151652 Update Galician translation 2024-12-08 17:02:27 +01:00
Ozzie Isaacs e49402649d Order of elements on the book editing page changed 2024-12-07 19:13:28 +01:00
Ozzie Isaacs 89e9958222 Merge remote-tracking branch 'massedit/bulk-delete' into Develop 2024-12-07 10:32:17 +01:00
Ozzie Isaacs 21989c3ccf Added logging of ip address (#3237)
Refactored Response(json.dumps -> make_response(jsonify..)
Update mimetypes - Allow different mimetypes for download and file upload check (#3245, #3243)
Bugfixes from tests
Updated optional-requirements
2024-12-07 07:27:57 +01:00
Ozzie Isaacs 42924d9508 Added logging of ip address (#3237)
Refactored Response(json.dumps -> make_response(jsonify..)
Update mimetypes - Allow different mimetypes for download and file upload check (#3245, #3243)
Bugfixes from tests
Updated optional-requirements
2024-12-07 07:27:00 +01:00
Ozzie Isaacs f9390ceea5 reenable hide console window on windows 2024-12-01 16:22:08 +01:00
Ozzie Isaacs dc7a0575dd Fix typo on security settings 2024-12-01 16:19:53 +01:00
leyan a972447dbc Correct a typo on config_password_character 2024-11-30 23:21:14 +01:00
Ozzie Isaacs 87b200cc13 Connection to metadata.db is now on per request base, should solve upload issues with multiple files at once 2024-11-30 10:02:53 +01:00
Ozzie Isaacs 14e57e3714 Fix save invalid database 2024-11-30 10:01:03 +01:00
Ozzie Isaacs d45ed1c921 Fixes for parallel upload (coverfiles get individual temporary names)
Updated teststatus
2024-11-30 09:45:46 +01:00
Ozzie Isaacs 344c0c7bc3 Bugfixes after testrun 2024-11-28 14:47:52 +01:00
Ozzie Isaacs 190ee09e60 update Tests
Per request db connection
2024-11-26 06:13:18 +01:00
Ozzie Isaacs e6031844d5 Update Testresults 2024-11-24 08:42:13 +01:00
Ozzie Isaacs 7c6347442f Merge branch 'master' into Develop 2024-11-23 15:53:34 +01:00
Ozzie Isaacs 16255870a8 Merge simple view 2024-11-23 15:46:20 +01:00
Ozzie Isaacs 65bcffc129 Fix layout of identifiers on book edit page if starting with no identifiers 2024-11-23 10:49:54 +01:00
Ozzie Isaacs b28547b248 Update kobo standard resources links 2024-11-23 10:39:55 +01:00
Ozzie Isaacs 8873381290 Merge remote-tracking branch 'amazon_links/patch-2' 2024-11-23 10:19:18 +01:00
Ozzie Isaacs ebb7ddec44 Merge remote-tracking branch 'whatsapp/patch-4' 2024-11-23 10:06:22 +01:00
Ozzie Isaacs b07541a251 Merge remote-tracking branch 'whatsapp/patch-5' 2024-11-23 09:54:57 +01:00
Ozzie Isaacs 85a66a3bfe Merge remote-tracking branch 'it/patch-1' 2024-11-23 09:37:15 +01:00
Ozzie Isaacs f493d4e4e5 Merge remote-tracking branch 'bsd_paths/freebsd-binary-paths' 2024-11-23 09:34:34 +01:00
Ozzie Isaacs 5d8908db49 Update Spanish translation 2024-11-23 09:32:10 +01:00
Matthew Wener 14b044d055 Add Binary Paths for FreeBSD 2024-11-22 21:35:21 -05:00
mapi68 9b0b82ec1b Update messages.po 2024-11-22 04:42:08 +01:00
Ozzie Isaacs 881b48729c Improved handling of docker database errors 2024-11-21 17:13:20 +01:00
Ozzie Isaacs 812265324d Merge remote-tracking branch 'cn/master' 2024-11-21 16:37:52 +01:00
Ozzie Isaacs 621f8debea Update Testresults 2024-11-21 16:36:23 +01:00
qx100 43040f6162 Update Chinese Simplified Ttanslation 2024-11-21 22:06:16 +08:00
Ozzie Isaacs 0bf3bb381f Invisible books are no longer counted in archived page (Fix for #3221) 2024-11-20 18:20:33 +01:00
Ozzie Isaacs 2bfbbfd4ba Possible fix for #3230 2024-11-20 18:08:25 +01:00
Ozzie Isaacs 6cb1449ff3 Fix version detection to work with sqlalchemy version 2.0.36.dev0 2024-11-20 17:55:17 +01:00
Ozzie Fernandez Isaacs 92fbc9c792 Improved dep check for windows exe version and further fixes for windows exe 2024-11-18 19:47:33 +01:00
Ozzie Isaacs f9cfb38ad3 Updated german translation 2024-11-16 20:42:11 +01:00
Ozzie Isaacs e5dc7e2834 Update readme and version 2024-11-16 13:39:04 +01:00
Ozzie Isaacs 0af52f2053 Update Version
Update teststatus
2024-11-16 07:21:28 +01:00
Ozzie Isaacs 2fff002699 Fix for stable update version 2024-11-11 18:46:07 +01:00
Ozzie Isaacs 5a87c1c4b3 Add libmagic for windows installations 2024-11-10 14:52:55 +01:00
Webysther Sperandio 38a7454e7a Add share details metadata 2024-11-08 13:23:44 +01:00
Ozzie Isaacs f0b770224a Fix updater nightly version check 2024-11-05 18:35:21 +01:00
Ozzie Isaacs 4c3fc90830 Fix for dependency check on python versions <3.10 2024-11-05 16:48:03 +01:00
Ozzie Isaacs d6798fb286 Fix error in requirements.txt 2024-11-04 21:20:34 +01:00
Ozzie Isaacs 6315f40800 Dependency check respects now python version restrictions 2024-11-04 21:10:18 +01:00
Ozzie Isaacs 1b73d8a7e4 Specify python versions in requirements file 2024-11-04 18:50:45 +01:00
Ozzie Isaacs 54a0ddaab5 Merge remote-tracking branch 'ko/master' 2024-11-02 20:21:09 +01:00
Ozzie Isaacs a84c316e3d Merge branch 'Develop' - Improved compability for python 3.12+ 2024-11-02 16:59:19 +01:00
Ozzie Isaacs 985e59ad68 Merge branch 'master' into Develop 2024-11-02 08:00:05 +01:00
Ozzie Isaacs 5334acac37 Merge branch 'Develop' 2024-11-02 07:29:32 +01:00
limeade23 0a53719394 Fix : refine korean translation 2024-11-01 20:04:58 +09:00
limeade23 3cc89d4ca0 Fix : refine korean translation 2024-11-01 19:07:14 +09:00
limeade23 2eee5fbdd8 Fix : some fix korean (remove file) 2024-11-01 19:01:14 +09:00
limeade23 e0b2734d66 Fix : some fix korean 2024-11-01 18:59:30 +09:00
limeade23 9926e03009 Fix : some fix korean 2024-11-01 18:42:23 +09:00
limeade23 3aa0c82795 Fix : retranslate korean 2024-11-01 18:01:41 +09:00
Ozzie Isaacs 85368c89dd Merge branch 'master' into Develop 2024-11-01 09:44:10 +01:00
Ozzie Isaacs 75499b989c Merge branch 'Develop' 2024-11-01 09:43:43 +01:00
Ozzie Isaacs bf89bbc8bc Fix series_index 0 isn't correctly synced to kobo (#3204)
Update Teststatus
2024-11-01 06:59:46 +01:00
Ozzie Isaacs deb1ff37b2 Escape characters in filename for kepub conversion 2024-10-31 19:09:00 +01:00
Ozzie Isaacs 2927b5d544 Updated requirements 2024-10-28 16:25:46 +01:00
Ozzie Isaacs bf9313ddeb Update test status
Updates after test run
2024-10-28 16:16:28 +01:00
Ozzie Isaacs c2ffa940cd Add cryptography to requirements 2024-10-27 07:05:50 +01:00
Ozzie Isaacs b94e1df518 Delete custom column related values on database change 2024-10-26 16:08:50 +02:00
Ozzie Isaacs 2eb4f77a23 Display error message if visiblity resticting custom column is no available (Fix for #3190) 2024-10-26 15:34:57 +02:00
Ozzie Isaacs d5059979d5 Marked 2 strings as raw strings to suppress warnings 2024-10-25 14:18:22 +02:00
Ozzie Isaacs 4fa7520598 Final fix for #3189 (also working on windows) 2024-10-25 12:26:35 +02:00
Ozzie Isaacs e8cb84136b Fix quotes for calibre convert on windows 2024-10-25 10:29:41 +02:00
Ozzie Isaacs 8a3409e911 Fix for caliber-convert parameter recognition bug with spaces in parameter (fix for #3189) 2024-10-25 10:21:44 +02:00
Ozzie Isaacs abedb13473 Improved ldap import user routine (fix for #3186) 2024-10-25 10:20:38 +02:00
Webysther Sperandio 366a65f99f Increase sqlite calibre cache 2024-10-23 22:22:50 +02:00
Ozzie Isaacs cd01aaa69e Merge remote-tracking branch 'readme/patch-1' 2024-10-23 19:03:34 +02:00
Ozzie Isaacs d4502713ff Merge remote-tracking branch 'ios_bookmark/fix-impossible-to-press-bookmarks-button-in-safari' 2024-10-23 18:57:24 +02:00
Ozzie Isaacs c523463591 Merge remote-tracking branch 'sl/master' 2024-10-23 18:44:10 +02:00
Andrej Kralj cca8158bdf Updates Slovenian translation 2024-10-22 08:21:00 +02:00
Ozzie Isaacs b9085129a7 Merge branch 'pdf' 2024-10-19 06:47:32 +02:00
Ozzie Isaacs cb073daca3 Changed response code to opds download forbidden to 401 instead of 404 2024-10-19 06:36:03 +02:00
Ozzie Isaacs c40c8a2255 Format seriesindex everywhere to 2 digits 2024-10-18 20:24:49 +02:00
lucaparsani e42e11e2a4 fix bookmarks button for safari browser 2024-10-09 00:24:06 +02:00
contributor 07bf9047b0 pdf metadata - ignore NullObject /Keywords to fix http 500 upload error
this fixes http 500 error while uploading valid PDF document with empty /Keywords
2024-10-04 19:53:54 +03:00
Lucinda Quintal 230573dc7a Enhance README: Adds Troubleshooting section, expands Contribution section
- Adds Troubleshooting Section which has common issues, configuration errors, and user management issues to help users diagnose problems effectively.
- Expanded the Contributing Section to include guidelines for contributions, a code of conduct, bug reporting, and feature requests.
- In the Additional Resources section , provided links to documentation and community contributions for ease of reference
2024-09-29 07:32:50 -07:00
Ozzie Isaacs 94df767c28 Reupdate slovenian translation 2024-09-26 19:46:35 +02:00
Webysther Sperandio fea8a9d40d Update with all amazon site that diverge in domain style 2024-09-25 01:07:22 +02:00
James Armstrong 54d9d33e53 Revert "Add shift-click to select multiple books at once"
This reverts commit fe78222142.
2024-09-23 09:42:04 -07:00
Ozzie Isaacs 1eb9cd44dc Improve message on error cover downlaod 2024-09-21 13:12:48 +02:00
Ozzie Isaacs eb6563480f Fix #3153 (In Firefox, Github OAuth login goes into infinite redirect loops) 2024-09-21 13:01:48 +02:00
Ozzie Isaacs 2f39e51e1c Fix for #3151 (Invalid amazon link for uk) 2024-09-21 12:58:12 +02:00
Ozzie Isaacs 24252e09b4 Merge branch 'master' into Develop 2024-09-21 12:43:19 +02:00
Ozzie Isaacs 0e7eed4d3c Update generated pyproject.toml 2024-09-21 12:39:05 +02:00
Ozzie Isaacs 884f7666fa Integrate advocate and change netiface requirement 2024-09-21 12:38:41 +02:00
Ozzie Isaacs c54e9fe588 Updated slovenian language 2024-09-21 12:35:26 +02:00
Andrej Kralj d82944d08c Updated Slovenian translation
After checking the nightly build I have made some improvements.
2024-09-19 09:15:04 +02:00
Ozzie Isaacs 97764acbcd Added missing locale for datepicker in Slovenian language 2024-09-18 19:56:54 +02:00
Ozzie Isaacs 53f0647c5d New Slovenian translation 2024-09-18 19:50:57 +02:00
Ozzie Isaacs b5ee07eba8 Revert "Update Slovenian translation"
This reverts commit 5fe13f53bf.
2024-09-18 19:43:44 +02:00
Ozzie Isaacs 5fe13f53bf Update Slovenian translation 2024-09-18 19:13:24 +02:00
James Armstrong 338441f116 fix author sort not updating when bulk editing 2024-09-17 12:26:35 -07:00
James Armstrong 31380f2af9 fix typo 2024-09-17 03:19:03 -07:00
Ozzie Isaacs 13dc0b9c8e Updated requirements 2024-09-16 17:28:43 +02:00
Ozzie Isaacs 78d45f0208 Remove tzlocal warning
Updated requirements
2024-09-16 17:25:37 +02:00
Ozzie Isaacs d0e166140f Fix import pycountry on python 3.12 without warning
Fix shadowed "babel" name
2024-09-16 17:22:27 +02:00
Ozzie Isaacs 2617fa8af4 Improved Dependency check 2024-09-16 15:53:29 +02:00
Ozzie Isaacs 89a1dcfbf6 Fix for #3145 (improved contrast for epub reader headline) 2024-09-14 18:55:35 +02:00
Ozzie Isaacs 9d619ae5c7 Merge branch 'master' into Develop 2024-09-14 14:11:32 +02:00
Ozzie Isaacs 10d0542e05 Removed obsolete code 2024-09-14 11:15:04 +02:00
Ozzie Isaacs 111c93c391 Merge remote-tracking branch 'it/patch-1' 2024-09-14 10:53:30 +02:00
Ozzie Isaacs 1d9471b252 Possible fix for #3150 (Invalid cross-device link) without coping metadata 2024-09-14 10:46:02 +02:00
Ozzie Isaacs 88cb58c285 Fix for load metadata from amazon 2024-09-14 10:23:11 +02:00
James Armstrong 7e5d8978ae Merge branch 'master' into bulk-delete 2024-09-11 11:08:01 -07:00
Ozzie Isaacs eea01b0ff5 Simplified version string 2024-09-07 20:07:45 +02:00
Ozzie Isaacs d755878bd2 Migrate to pyproject.toml build 2024-09-07 19:59:02 +02:00
mapi68 2d7cf1e6d3 Update italian 2024-08-24 05:33:36 +02:00
Ozzie Isaacs b8a770a470 Merge branch 'master' into Develop 2024-08-23 11:13:48 +02:00
Ozzie Isaacs 481237dc77 Fix for #3131 (Enable/Disable "Separate Book Files from Library" issue) 2024-08-23 10:51:37 +02:00
Ozzie Isaacs 5e9dfc0724 Test update 2024-08-23 09:44:11 +02:00
Ozzie Isaacs ce720f40fe Shelf sort algorithm is now saved (#3003) 2024-08-21 19:30:33 +02:00
Ozzie Isaacs c92115faf3 Update save shelf sort algorithm 2024-08-21 19:25:50 +02:00
Ozzie Isaacs a1f9f03fc1 Fix for #3130 (only last e-mail address is saved when specifying multiple e-reader mail addresses in user settings) 2024-08-21 18:49:20 +02:00
Ozzie Isaacs 6a504673e5 Merge branch 'Develop':
Better handling of incompatible iso-639 module on python3.12
Music icon only visible once if more than one audio format available
Upload (multiple) book formats with progress and merge the corresponding metadata into the book (also via drag'n drop #2252)
2024-08-21 18:44:48 +02:00
Ozzie Isaacs 839118e4f1 Bugfixes from testrun 2024-08-21 18:21:19 +02:00
Ozzie Isaacs fd730f6609 Bugfix generate thumbnails on gdrive 2024-08-18 20:14:29 +02:00
Ozzie Isaacs 1be0ff9620 Bugfix load metadata
Bugfix xchange author and title
Better handling of incompatible iso-639 module on python3.12
2024-08-18 18:52:13 +02:00
Ozzie Isaacs 6717683ac3 Improvements merge metadata upload format
Music icon only visible once if more than one audio format available
2024-08-18 16:45:42 +02:00
Ozzie Isaacs 0f9b5d08e9 Fix cover handling on upload formats 2024-08-18 10:59:39 +02:00
Ozzie Isaacs 1eb77c9cd4 Upload (multiple) book formats with progress and merge the corresponding metadata into the book 2024-08-17 15:34:50 +02:00
Ozzie Isaacs ca92dbb168 Update german translation 2024-08-17 13:50:33 +02:00
Ozzie Isaacs 8bc1f03164 Bugfix generate thumbnails on gdrive 2024-08-17 09:30:52 +02:00
Ozzie Isaacs d8d9d405e9 First step format upload with progress 2024-08-16 21:14:41 +02:00
Ozzie Isaacs 8f2f6f5c91 Merge branch 'master' into Develop 2024-08-16 11:21:34 +02:00
Ozzie Isaacs 4c01af340f Update Testresults 2024-08-16 09:31:59 +02:00
Ozzie Isaacs 88783257b4 Update readme 2024-08-15 19:08:08 +02:00
Ozzie Isaacs c2474aa91d Fix for #2990 (Kobo browser not downloading kepub files)
Final fix for cover size during kobo sync (fix for #2523)
2024-08-15 19:02:11 +02:00
Ozzie Isaacs d2860fc374 Final fix for cover size during kobo sync (fix for #2523)
Update Teststatus
2024-08-15 18:35:48 +02:00
Ozzie Isaacs 87a1971d74 Merge remote-tracking branch 'spelling/master' 2024-08-14 19:29:40 +02:00
Ozzie Isaacs a9359bc1db Removed accidentally added translation file 2024-08-14 18:23:30 +02:00
Ozzie Isaacs c7f0293568 Implementation of sorting according to shelf added 2024-08-14 18:21:21 +02:00
Daniel M. Drucker, Ph.D. 22affedafc fix spelling of seperate to separate 2024-08-13 14:10:03 -04:00
Ozzie Isaacs 4d79c593f7 Fix for #2990 (Kobo browser not downloading kepub files) 2024-08-13 19:40:32 +02:00
Ozzie Isaacs 87b82424d5 Improved whitespace removal
Testresults
2024-08-13 07:07:54 +02:00
Ozzie Isaacs 5f81084e66 Updated testresults 2024-08-12 18:32:47 +02:00
Ozzie Isaacs 095074f977 Fix metadata search results 2024-08-12 18:32:35 +02:00
Ozzie Isaacs acd3c8d103 Merge branch 'master' into Develop 2024-08-11 19:56:20 +02:00
Ozzie Isaacs 3733fd442f Improved mp4, m4a, m4b import (coverformat png and multiple coverfiles)
Added support for metadata extraction in opus, ogv files
2024-08-11 19:45:12 +02:00
Ozzie Isaacs 4eb9845ff7 Improved asf, aac metadata import 2024-08-11 17:27:41 +02:00
Ozzie Isaacs ec6efafbed Added m4a, m4b files to parsable audio metadata 2024-08-11 12:20:16 +02:00
Ozzie Isaacs 10668571e8 Fixes for audio metadata extraction of oggvorbis and flac files (handle more than one cover and png covers as well) 2024-08-11 11:50:03 +02:00
Ozzie Isaacs 878fd85c63 Fixes for audio metadata extraction of oggvorbis and flac files (handle more than one cover and png covers as well) 2024-08-11 11:49:43 +02:00
Ozzie Isaacs 3827d46d66 Merge remote-tracking branch 'it/patch-1' 2024-08-11 08:41:46 +02:00
Ozzie Isaacs 7feff3b55c Merge branch 'Develop'
Extract metadata of audiofiles during upload
Updated pdf.js
2024-08-11 08:35:37 +02:00
Ozzie Isaacs 4523a12708 Fixes after testrun 2024-08-11 08:21:01 +02:00
Ozzie Isaacs 7a8d054b28 Make datetime utcnow compatible to older python versions 2024-08-10 21:05:29 +02:00
Ozzie Isaacs a56d1c80ae Remove deprecated utcnow method
Bugfix mp3 cover metadata extraction
2024-08-10 18:55:24 +02:00
Ozzie Isaacs 074aed6997 Fix deprecation warning datetime
Started metadata parsing for audio files
2024-08-07 17:23:41 +02:00
Ozzie Isaacs 2f8db1f7f0 Update pdf.js to 4.5.136 2024-08-07 15:16:38 +02:00
Ozzie Isaacs b3d878bae8 Fix deprecation warning datetime 2024-08-07 13:53:27 +02:00
mapi68 9b12852544 Update messages.po 2024-08-06 06:37:05 +02:00
Ozzie Isaacs a7d58386eb Get version info from importlib.metadata 2024-08-05 20:27:34 +02:00
James Armstrong fe78222142 Add shift-click to select multiple books at once 2024-08-05 10:43:51 -07:00
Ozzie Isaacs 68531a44d8 Changed formating of float values. IF value ends not with "0" tailing "0" are printed
Version update
2024-08-05 18:58:19 +02:00
Ozzie Isaacs d3233b4b9c Prepare release 2024-08-05 18:42:13 +02:00
Oskar Manhart 0e9ad0f831 Merge remote-tracking branch 'upstream/master' 2024-08-05 12:03:28 +02:00
Oskar Manhart c53a516887 feat: revert all the resizing stuff 2024-08-05 12:02:43 +02:00
Ozzie Isaacs bdac7a3257 Changed formating of float values. IF value ends not with "0" tailing "0" are printed 2024-08-04 16:39:05 +02:00
Ozzie Isaacs 0d359e9e57 Add cookie prefix environment variable to config 2024-08-04 15:52:19 +02:00
Ozzie Isaacs c4fad3cd20 Fix archiving bookm for kobo sync
Fix back function without search parameter
Updated Testresults
2024-08-04 07:12:44 +02:00
Ozzie Isaacs 9b520b1941 Fix archiving bookm for kobo sync
Fix back function without search parameter
Updated Testresults
2024-08-04 07:12:22 +02:00
James Armstong de3f883992 Add change_archived_books() description 2024-08-03 11:52:28 -07:00
James Armstong 2afce66486 Fix change_archived so state=none is a toggle. Fixes /togglearchived endpoint 2024-08-03 11:50:28 -07:00
James Armstong 2ae80d3007 Fix book_read_status marking as read even though read_status is passed as false 2024-08-03 11:40:11 -07:00
James Armstong e31763d388 Fix kobo sync status marking as archived even though state = false 2024-08-03 11:27:58 -07:00
Oskar Manhart 9955e348a0 Revert "feat: resize images directly at cover endpoint"
This reverts commit ba383643f5.
2024-08-03 16:28:13 +02:00
Ozzie Isaacs bcf4a479ac Merge branch 'master' into Develop 2024-08-03 16:03:52 +02:00
Oskar Manhart 26fb9921b2 fix: typo 2024-08-03 15:49:55 +02:00
Oskar Manhart ba383643f5 feat: resize images directly at cover endpoint 2024-08-03 15:49:15 +02:00
Oskar Manhart 6bd01c2d2b Merge branch 'master' of github.com:janeczku/calibre-web 2024-08-03 14:59:32 +02:00
Oskar Manhart 26c8e15436 feat: resize and convert images to webp using Flask-Image-Resizer 2024-08-03 14:59:16 +02:00
Oskar Manhart fd993b5063 feat: use lazy loading for images 2024-08-03 14:25:15 +02:00
Ozzie Isaacs abc923ade4 Fix for back function on simple search 2024-08-03 12:57:55 +02:00
Ozzie Isaacs 3aa72c8afb Added error message to task list 2024-08-03 11:25:07 +02:00
James Armstong bee6a3593d remove spacing 2024-08-02 23:31:04 -07:00
James Armstong a335dd75a1 Make edit metadata pass all data in a single REST call. Modularize editbooks 2024-08-02 23:29:34 -07:00
James Armstong 96fb2c1439 Auto disable author/title sort input in metadata edit form 2024-08-02 21:39:01 -07:00
James Armstong 9def910924 switch title_sort to sort in api edit request 2024-08-02 21:16:34 -07:00
James Armstong ab3d4e4f21 Fix emptying metadata form after submit 2024-08-02 20:10:43 -07:00
James Armstong ecda717bed Add bulk metadata edit button 2024-08-02 16:05:11 -07:00
James Armstrong 4ed0633edf Add bulk read/unread buttons; Fix buttons not working when moved into table 2024-08-02 14:57:20 -07:00
James Armstrong 34fec0ed97 Move buttons into table 2024-08-02 10:19:25 -07:00
Ozzie Isaacs 249017a4fa Added error message to task list 2024-08-02 18:08:18 +02:00
Ozzie Isaacs 84f432830c Fix for #3109 (search for custom int and float values within ranges) 2024-08-02 18:07:22 +02:00
James Armstrong ca9fc74541 typo fix 2024-08-02 00:40:47 -07:00
James Armstong d9a2a7a1e8 Add bulk archive/unarchive buttons 2024-08-01 21:34:55 -07:00
James Armstong d0d9985370 Add bulk delete button 2024-08-01 19:19:14 -07:00
Ozzie Isaacs e6ccd42f89 Fixed read statu search with linked column in advanced search 2024-07-31 19:25:01 +02:00
Ozzie Isaacs 12d46d33d9 Search custom integer, custom_float in range
Search custom bool like read status (unfinished)
2024-07-30 19:20:13 +02:00
Ozzie Isaacs 8d9f301aea Merge branch 'master' into Develop
# Conflicts:
#	test/Calibre-Web TestSummary_Linux.html
2024-07-30 18:52:22 +02:00
Ozzie Isaacs 0ff3f0f426 Fix for (#3111) exception on python 3.8/3.9 during storing of remember me cookie 2024-07-30 18:51:52 +02:00
Ozzie Isaacs b2f5853b12 Removed unused imports
Rearranged imports to output all missing libs
Update Testresults
Updated requirements
2024-07-29 20:08:17 +02:00
Ozzie Isaacs f8adcbb691 Make light theme default theme on epub reader
Fix csp Header for reader and google drive (#3108)
Testrun
2024-07-25 21:42:32 +02:00
Ozzie Isaacs a0728b07d0 Fix wrong quotes on calibre binary call for windows 2024-07-21 13:46:36 +02:00
Ozzie Isaacs e3b895755d Update test results 2024-07-21 13:46:36 +02:00
Ozzie Isaacs e33e4ac4ac Bugfix upload book format with language to book without language 2024-07-21 09:44:32 +02:00
Ozzie Isaacs 2f515b725b Schedules reconnect is now working even if reconnect route is not available ( #3107) 2024-07-20 18:14:54 +02:00
Ozzie Isaacs a1d7dc5c28 Merge branch 'master' into Develop 2024-07-20 14:01:36 +02:00
Ozzie Isaacs 1c5d1e24f7 Update test results 2024-07-20 13:58:53 +02:00
Ozzie Isaacs 8df45d150d Added hints for libmagic on Windows (fix #3104) 2024-07-20 13:51:45 +02:00
Ozzie Isaacs a59d20bd0f Output error message in case import of libmagic fails (#3104) 2024-07-20 11:31:31 +02:00
Ozzie Isaacs e3be7595e2 Attention flask-httpAuth is additionally needed to run calibre-web
Updated pdf.js viewer
Refactored login routine (#2623)
2024-07-18 20:42:25 +02:00
Ozzie Isaacs e33a7a3f08 Testupdate 2024-07-18 20:39:46 +02:00
Ozzie Isaacs 8c02ffb1cb Test update 2024-07-18 20:39:35 +02:00
Ozzie Isaacs 7367e96d2b Fix hiding console window on windows 2024-07-18 20:32:47 +02:00
Ozzie Isaacs 2d80187faa Clean expired sessions (also old sessions without expiry date) 2024-07-17 20:05:51 +02:00
Ozzie Isaacs 1d3a768dfe Update login routine (remember me working) 2024-07-17 19:42:12 +02:00
Ozzie Isaacs c09e1ed203 Update after testrun 2024-07-15 19:38:54 +02:00
Ozzie Isaacs 99e50bafc4 Fixes refactored user login from tests 2024-07-14 21:20:46 +02:00
Ozzie Isaacs 155cf04536 Added migration of user_session table, removed several old migration routes 2024-07-14 17:10:13 +02:00
Ozzie Isaacs ebe7cd7ba4 proxy login is now no longer saving cookies,
Cookies are saved in database for better Invalidation
Cookies expiry date is saved in database for further deletion (missing)
Database conversion is missing
2024-07-14 16:24:07 +02:00
Ozzie Isaacs 2d470e0ce1 Refactored opds login (proxy header login missing) 2024-07-13 12:17:48 +02:00
Ozzie Isaacs 87c0b15f5f Update pdf.js to version 4.4.168 2024-07-13 10:49:47 +02:00
Ozzie Isaacs 02d2c2bbf8 Better error message on failed convert because of running calibre instance (#3100) 2024-07-11 20:30:35 +02:00
Ozzie Isaacs 6996e813b5 Fixed error during debug logging on upload 2024-07-11 20:29:49 +02:00
Ozzie Isaacs 840f4d2010 Update to make upload of m4a and m4b files work (#3102) 2024-07-11 20:10:15 +02:00
Ozzie Isaacs 3cda0a0f32 Testupdate 2024-07-11 19:39:33 +02:00
Ozzie Isaacs a6931b4936 Merge branch 'master' into Develop:
Logging correct ip address behind reverse proxy,
add br to not sanitized tag for comments
code cleaning
2024-07-10 20:10:05 +02:00
Ozzie Isaacs 9536b2c322 Fix for renaming tags etc. upon upload (#3058) 2024-07-10 20:09:03 +02:00
Ozzie Isaacs 099dbf95e7 Fix error 500 on sending test email 2024-07-10 19:59:21 +02:00
Ozzie Isaacs 23d5463213 Fixes from testrun 2024-07-10 19:58:30 +02:00
Ozzie Isaacs a2ceeb678f Fix for similar names (upper case, umlauts, emphasis mark) in tags and so on 2024-07-09 19:37:24 +02:00
Ozzie Isaacs 092329c9e6 Merge remote-tracking branch 'origin/master' 2024-07-08 20:14:24 +02:00
Ozzie Isaacs de989783e8 Log Forwarded for address in accesslog instead of client address for tornado 2024-07-08 15:04:53 +02:00
Ozzie Isaacs 1d7dcce98d Log Forwarded for address in accesslog instead of client address for gevent 2024-07-08 14:42:48 +02:00
Ozzie Isaacs 551828f8cf Added "br" to not sanitized comments tag 2024-07-08 14:09:53 +02:00
Ozzie Isaacs d26964ab08 Added log message for missing python magic 2024-07-08 12:46:23 +02:00
Ozzie Isaacs 0fe12fe598 Added log message for missing python magic 2024-07-08 12:45:35 +02:00
Ozzie Isaacs b0e8024f08 Updated readme for setup calibre binaries
Added h tags to recognized tags for sanitizing comments
Avoid depreciation warning in lubimyczytac
Removed some unsed imports
2024-07-08 12:34:52 +02:00
Ozzie Isaacs bc1c097271 Updated readme for setup calibre binaries
Added h tags to recognized tags for sanitizing comments
Avoid depreciation warning in lubimyczytac
Removed some unsed imports
2024-07-08 12:34:10 +02:00
Ozzie Isaacs f98cb3d8fb Merge branch 'master' into Develop 2024-07-08 11:50:32 +02:00
Ozzie Isaacs 488005962f Update testresults 2024-07-08 11:49:53 +02:00
Ozzie Isaacs 6d6f8c1b1f Update redirect for login/logout in case of anonymous browsing enabled 2024-07-07 15:53:26 +02:00
Ozzie Isaacs c4a38087d9 Merge remote-tracking branch 'csv_kindle/master' 2024-07-07 14:55:53 +02:00
Ozzie Isaacs f468b9e6e3 Merge branch 'master' into Develop -> Epub progress indicator 2024-07-07 10:40:46 +02:00
Ozzie Isaacs 53a16c5a6f Merge remote-tracking branch 'epub_progress/progress_indicator' 2024-07-07 10:39:06 +02:00
Ozzie Isaacs 108caa0898 Merge branch 'Develop' 2024-07-07 10:32:02 +02:00
Ozzie Isaacs a0b776cbd1 Merge remote-tracking branch 'epub_reader_font/feat_font' into Develop 2024-07-07 10:31:49 +02:00
Ozzie Isaacs 4719797aff Merge branch 'Develop' epub reader themes 2024-07-07 10:22:56 +02:00
Ozzie Isaacs 60cc0c9395 Merge remote-tracking branch 'epub_theme/Develop' into Develop 2024-07-07 10:22:32 +02:00
Ozzie Isaacs ded4cb7a19 Merge remote-tracking branch 'it/patch-1' 2024-07-07 10:18:31 +02:00
Ozzie Isaacs f5f16a3dd2 Merge branch 'master' into Develop 2024-07-06 14:34:45 +02:00
Ozzie Isaacs c5f2323c8a Version bump 2024-07-06 14:21:49 +02:00
Ozzie Isaacs e9bccc83c5 Version bump 2024-07-06 13:29:17 +02:00
Ozzie Isaacs 53ba352ed9 Improved some things in caliblur theme (hide back button) 2024-07-05 20:43:50 +02:00
Ozzie Isaacs bbc3219d31 Update lubimycztac metadata provider (fixes #3090) 2024-07-05 19:16:22 +02:00
mapi68 ea89fe07d8 Update messages.po 2024-07-05 04:35:07 +02:00
Ozzie Isaacs ab2620a265 Merge branch 'Develop' (Fix for #3058, refactored rename author and improved duplicate check for tags/publishers, series, ...) 2024-07-03 15:46:19 +02:00
Ozzie Isaacs a20a4a201e Test update 2024-07-03 15:38:47 +02:00
Ozzie Isaacs ba0718f3d0 Enabled covers with gdrive 2024-07-02 20:53:08 +02:00
Ozzie Isaacs 60dd3df861 Fix after testrun for G-Drive 2024-07-02 20:02:11 +02:00
Ozzie Isaacs 762074596d Fix after testrun on Windows 2024-06-30 17:08:41 +02:00
Ozzie Isaacs 789912d0d4 Merge branch 'Develop'
Update translations
2024-06-30 12:20:42 +02:00
Ozzie Isaacs daf8dd6f90 Fix author rename on google drive
Bugfixes after testrun
2024-06-30 12:18:52 +02:00
Ozzie Isaacs e02610e2f0 Bugfixes change author 2024-06-29 20:45:56 +02:00
Ozzie Isaacs 897188ff18 Merge remote-tracking branch 'origin/Develop' into Develop 2024-06-29 09:52:05 +02:00
Ozzie Isaacs 09c0794f1a Refactored rename_authors
Bugfixes from tests
2024-06-29 09:50:00 +02:00
Ozzie Isaacs b28a3635f8 Merge branch 'master' into Develop
# Conflicts:
#	cps/editbooks.py
#	requirements.txt
#	setup.cfg
#	test/Calibre-Web TestSummary_Linux.html
2024-06-24 14:42:00 +02:00
Ozzie Isaacs 1a1f1498a5 Bugfixes from Tests 2024-06-24 14:39:28 +02:00
Ozzie Isaacs 92ffce1dc8 Rename Archived in Book Detail page 2024-06-23 13:47:54 +02:00
Ozzie Isaacs 6441f5f96b Prevent non unique authors on upload 2024-06-23 13:07:28 +02:00
Ozzie Isaacs d5a57e3b07 Merge remote-tracking branch 'mimetype/python_magic_poc' into Develop 2024-06-23 12:16:40 +02:00
Ozzie Isaacs fef20c831a Changed limiter message 2024-06-22 16:23:04 +02:00
Ozzie Isaacs e52e8c6fdf Merge branch 'master' into Develop 2024-06-22 16:07:01 +02:00
Ozzie Isaacs 89ac9ff498 Updated requirements 2024-06-22 13:35:53 +02:00
Ozzie Isaacs 059bdf1649 Bugfix from code cosmetics 2024-06-22 13:31:18 +02:00
Ozzie Isaacs 266ef11940 Bugfix for gevent as server 2024-06-22 13:30:32 +02:00
Ozzie Isaacs 64e4a1155c Code cosmetics
Bugfix missing bleach tags (#3080)
Bugfix pdfreader
2024-06-20 19:12:46 +02:00
Ozzie Isaacs f7d5480811 Make bleach mandatory 2024-06-15 08:18:38 +02:00
aptalca 7aa122e6cd Attempt pywin32 install only on Windows
Currently, doing a `pip install -r optional-requirements.txt` on a non-Windows platform results in an error due to pywin32 being a Windows only package.
2024-06-11 18:06:06 +02:00
Ozzie Isaacs cfdc07e6b2 Merge remote-tracking branch 'loglevel/handle_regions_in_locales' 2024-06-09 12:57:42 +02:00
Ozzie Isaacs 1ca1ac973a Merge remote-tracking branch 'loglevel/handle_regions_in_locales' into Develop 2024-06-09 12:57:30 +02:00
Ozzie Isaacs ba4235a39e Merge branch 'master' into Develop 2024-06-09 12:33:25 +02:00
Ozzie Isaacs 7295ebaee1 Merge remote-tracking branch 'loglevel/log_exceptions_for_own_modules_when_debug_logging_is_enabled' 2024-06-09 12:32:43 +02:00
Ozzie Isaacs d74ea7dcf2 Merge Text corrections 2024-06-09 12:30:44 +02:00
Ozzie Isaacs ee23ee97d9 Update pdf Reader to 4.3.136 2024-06-09 12:00:10 +02:00
Ozzie Isaacs c73ec52842 Update pdf Reader to 4.3.136 2024-06-09 11:59:38 +02:00
Ozzie Isaacs 0e3d3876f3 Merge branch 'master' into Develop 2024-06-09 11:10:20 +02:00
Ozzie Isaacs 76d086f536 Finish hinde_console_windows 2024-06-09 11:10:01 +02:00
Ozzie Isaacs 6022f48040 Hide console on Windows after start 2024-06-09 11:09:29 +02:00
Ozzie Isaacs e0be168779 Fix 2024-06-09 10:34:20 +02:00
Ozzie Isaacs d3118c0aa9 Merge remote-tracking branch 'it/master' 2024-06-03 20:41:52 +02:00
mapi68 04370944b9 Fix many italian strings 2024-06-01 05:55:41 +02:00
yunimoo af52748aca Update requirements to add python-magic 2024-05-31 18:08:04 -04:00
yunimoo 7eece7603b Add mime_type checks on file uploads 2024-05-31 18:08:04 -04:00
yunimoo d6aa29b095 Fix typos and text consistency 2024-05-31 14:30:58 -04:00
Purbayan Chowdhury 5d86bb0ba0 Merge branch 'janeczku:Develop' into Develop 2024-05-23 01:45:36 +05:30
Ozzie Isaacs ab11919c0b Merge remote-tracking branch 'Synctoken/fix/kobo-sync-token' 2024-05-12 17:56:49 +02:00
Ozzie Isaacs 014a247847 Merge remote-tracking branch 'Synctoken/fix/kobo-sync-token' into Develop 2024-05-12 17:56:19 +02:00
Ozzie Isaacs 58c269881f Merge remote-tracking branch 'barnesnnoble/db-barnesnoble' 2024-05-12 09:03:40 +02:00
Ozzie Isaacs e91dd5729a Finish OPDS-access 2024-05-12 09:01:00 +02:00
Ozzie Isaacs 6760d6971c Fix for #2983 (visible OPDS categories reflect settings in web UI)
Merge branch 'feature/OPDS-access'
2024-05-12 08:57:55 +02:00
Kreeblah ad05534ed2 Add support for barnesnoble identifier 2024-05-11 23:56:37 -07:00
Ozzie Isaacs ee451fb236 Testrun 2024-05-12 08:56:20 +02:00
Ozzie Isaacs ab13fcf60c Merge remote-tracking branch 'origin/feature/OPDS-access' into feature/OPDS-access 2024-05-11 18:37:10 +02:00
Ozzie Isaacs c7fa2ac71a Merge branch 'master' into Develop 2024-05-11 18:27:51 +02:00
Ozzie Isaacs 6f60ec7b99 Change order of imports for goodreads to make import error message clear agan 2024-05-11 18:27:35 +02:00
Ozzie Isaacs 93f1ccbea9 Merge branch 'master' into Develop 2024-05-11 18:21:29 +02:00
Ozzie Isaacs 894fd9d30a get rid of apscheduler timezone warning 2024-05-11 18:21:03 +02:00
Ozzie Isaacs 2b1efdb50e Bugfixes opds feed 2024-05-11 14:26:43 +02:00
Ozzie Isaacs fc9a9cb9ac Fix for #3016 (Parsing lubimyczytac: Tags instead of categories are taken, translator is appended to description) 2024-05-11 09:03:22 +02:00
Ozzie Isaacs e99be72ff7 Merge branch 'Develop' into feature/OPDS-access
# Conflicts:
#	test/Calibre-Web TestSummary_Linux.html
2024-05-11 07:12:46 +02:00
Ozzie Isaacs f1ceff2b52 Merge branch 'master' into Develop (goodreads) 2024-05-11 07:11:22 +02:00
Ozzie Isaacs 7e85894b3a Bugfix for goodreads (html formated info for authors now visible) 2024-05-11 07:10:41 +02:00
Ozzie Isaacs 5c49c8cdd7 Fix for Flask-SimpleLDAP 2.0.0 2024-05-10 20:23:41 +02:00
Ozzie Isaacs c8c3b3cba3 Fix for goodreads not working anymore (due to blocked requests calls by goodreads.com) 2024-05-10 15:24:24 +02:00
Ozzie Isaacs 4911843146 Bugfix for flask-ldap 2.0.0 2024-05-10 11:30:47 +02:00
Ozzie Isaacs 2c37546598 Code cosmetics 2024-05-10 10:41:04 +02:00
Ozzie Isaacs 25a875b628 Fix for goodreads blocking "requests" 2024-05-10 09:42:44 +02:00
Ozzie Isaacs 506f0a33cf Merge branch 'master' into Develop (apply fix for #3050) 2024-05-10 09:06:11 +02:00
Ozzie Isaacs 921caf6716 Fix for #3050 (metadata extraction for cb7 files not working) 2024-05-10 09:05:31 +02:00
Ozzie Isaacs 60ed1904f5 testrun 2024-05-10 09:04:50 +02:00
Ozzie Isaacs cb62d36e44 Bugfix for visibility opds feed 2024-05-07 08:27:55 +02:00
Ozzie Isaacs 737d758362 Return 404 if current element is not visible 2024-05-07 07:30:57 +02:00
Ozzie Isaacs 8e27912ff5 Merge branch 'master' into Develop
Bugfix for too new lxml
2024-05-07 07:16:54 +02:00
Ozzie Isaacs 3a603cec22 Handle error on uploading a book with lxml too new and no bleach, nh3 installation 2024-05-05 11:18:31 +02:00
eggy b1d7badef4 fix: change b64-encoded token to unicode string 2024-05-02 03:06:53 -04:00
Ozzie Isaacs e591211b57 Fix for #3037 (catch OError on detect epub layout) 2024-04-27 07:22:58 +02:00
Ozzie Isaacs a305c35de4 Merge remote-tracking branch 'it/patch-1' 2024-04-27 07:22:23 +02:00
growfrow 51d306b11d chore: fix some typos in comments
Signed-off-by: growfrow <growfrow@outlook.com>
2024-04-20 20:49:56 +02:00
mapi68 abb418fe86 Update messages.po 2024-04-17 07:45:40 +02:00
Ozzie Isaacs 0925f34557 Merge remote-tracking branch 'caliblur/issue/caliBlur-3002' 2024-04-07 18:51:00 +02:00
Ozzie Isaacs 15952a764c Fix for #3021 (speed of calculating number of pages) 2024-04-07 18:49:18 +02:00
Daniel Edwards 28c810b514 feat: base is_debug on effective level vs root log level 2024-03-19 11:05:04 +11:00
Daniel Edwards cfe61a26d0 Refactor get_language_name function to handle missing language names 2024-03-19 10:54:48 +11:00
Ozzie Isaacs fcc95bd895 Improvements for password verify (addresses: https://github.com/iiab/calibre-web/pull/138) 2024-03-10 16:39:51 +01:00
Ghighi Eftimie 964e7de920 fixes 3002 2024-03-06 15:42:10 +02:00
Ozzie Isaacs 14b578dd3a Implement correct password verification of Umlaunts, kyrillic, greek.. charactersets, CJK-Characters, and special characters (#2964) 2024-02-29 12:08:58 +01:00
Ozzie Isaacs becb84a73d Finish Fix_Umlauts 2024-02-29 12:06:48 +01:00
Ozzie Isaacs c901ccbb01 Improved js password strength check
Improved check of CJK-Characters
2024-02-29 11:48:07 +01:00
Ozzie Isaacs f987fb0aba Fixed recognition of capital umlauts 2024-02-27 19:48:33 +01:00
Ozzie Isaacs c30460d76b Merge branch 'Develop'
- Back function for delete and edit books
- configure ratelimiter backend possible
- embed metadata during send to ereader
- bugfixes split library
- updated requirements
2024-02-27 06:03:54 +01:00
Ozzie Isaacs 97380b4b3f Updated teststatus 2024-02-27 06:01:11 +01:00
Ozzie Isaacs 4fbd064b85 Merge remote-tracking branch 'origin/back' into Develop 2024-02-26 18:42:48 +01:00
Ozzie Isaacs abbd9a5888 Revert logging line termination feature 2024-02-26 18:07:24 +01:00
Ozzie Isaacs e860b4e097 Back function implemented for delete book and edit book 2024-02-26 15:07:59 +01:00
Ozzie Isaacs 23a8a4657d Merge branch 'master' into Develop
(Fix for #3005 and #2993)
2024-02-25 20:07:40 +01:00
Ozzie Isaacs b38a1b2298 Admin can now force full sync for users (fix for #2993 2024-02-25 20:03:38 +01:00
Ozzie Isaacs 0ebfba8d05 Added blobs to csp for reader page (fix for #3005) 2024-02-25 19:32:04 +01:00
Ozzie Isaacs 990ad8d72d Update Requirements 2024-02-25 16:11:57 +01:00
Ozzie Isaacs c3fc125501 Added command line option or overwriting limiter backend
Added logger functions to remove newlines in messages
CalibreTask has now a default name
2024-02-25 16:02:01 +01:00
Ozzie Isaacs 3c4ed0de1a Added ratelimiterbackends 2024-02-25 09:00:49 +01:00
Ozzie Isaacs 117c92233d Added sending email to embed metadata text
Updated test result
2024-02-25 06:54:35 +01:00
Ozzie Isaacs 2ba14acf4f Merge branch 'master' into Develop
# Conflicts:
#	cps/helper.py
2024-02-24 14:51:53 +01:00
Ozzie Isaacs 80a2d07009 fix embed metadata, split library and download file / convert files 2024-02-24 14:48:56 +01:00
Ozzie Isaacs ff9e1ed7c8 Implemented embed metadata on send to ereader 2024-02-24 13:59:49 +01:00
Ozzie Isaacs 8e5bee5352 Merge remote-tracking branch 'embed_metadata/embed_metadata_on_send' into Develop 2024-02-18 14:48:04 +01:00
Ozzie Isaacs d659430116 Bugfix view None ratings caused error 500 in certain cases 2024-02-18 14:17:43 +01:00
Ozzie Isaacs 859dac462b Update Teststatus 2024-02-18 13:29:03 +01:00
Ozzie Isaacs 2bea4dbd06 Show List with no file formats available
Bugfix save order of format list view
2024-02-17 11:13:49 +01:00
Ozzie Isaacs 0180b4b6b5 Better error handling on next parameter 2024-02-12 20:58:26 +01:00
Ozzie Isaacs 2bfb02c448 Updated requirements
Updated testresults
2024-02-11 07:31:57 +01:00
Ozzie Isaacs 4864254e37 Merge branch 'Develop'
# Conflicts:
#	cps/config_sql.py
2024-02-10 10:55:02 +01:00
Ozzie Isaacs 09dce28a0e Merge remote-tracking branch 'embed_metadata/embed_metadata_on_convert' into Develop 2024-02-10 10:54:29 +01:00
Ozzie Isaacs e55d09d8bb Merge branch 'Develop' into embed_metadata_on_convert 2024-02-10 10:52:16 +01:00
Ozzie Isaacs 92c162b2fd Merge remote-tracking branch 'embed_metadata/embed_metadata_on_download'
# Conflicts:
#	cps/helper.py
#	cps/tasks/convert.py
#	cps/templates/config_edit.html
2024-02-10 10:49:09 +01:00
Ozzie Isaacs 57fb5001e2 Merge branch 'Develop' 2024-02-10 10:43:58 +01:00
Ozzie Isaacs 64e5314148 Merge remote-tracking branch 'identifier/master' into Develop 2024-02-10 10:31:57 +01:00
Ozzie Isaacs 873602a5c9 Deleted unused code 2024-02-10 10:30:41 +01:00
Ozzie Isaacs 09e966e18a Merge remote-tracking branch 'optimize_details_html/only-render-cc-with-data' into Develop 2024-02-10 10:28:36 +01:00
Ozzie Isaacs f7718cae0c Fix typo in send password message 2024-02-10 10:07:10 +01:00
Ozzie Isaacs 90e728516c Merge remote-tracking branch 'it/master' 2024-02-10 10:04:01 +01:00
Ozzie Isaacs 7c04b68c88 Merge remote-tracking branch 'icon/master' 2024-02-10 10:01:16 +01:00
Ozzie Isaacs 8549689a0f Merge branch 'Develop'
Separate library from metadata file
embed metadata on download
2024-02-10 09:57:28 +01:00
Ozzie Isaacs d8f5c17518 Mark separate library as highly experimental 2024-02-10 09:56:32 +01:00
mapi68 05367d2df5 Update messages.po 2024-01-25 07:46:31 +01:00
Webysther Sperandio eb6fbfc90c HiDPI icons 2024-01-23 04:24:21 +01:00
Ozzie Isaacs c2267b6902 Bugfix add to shelf 2024-01-22 13:17:27 +01:00
Ozzie Isaacs 0e5520a261 Bugfix add to shelf 2024-01-22 13:16:58 +01:00
Ozzie Isaacs 6f5e9f167e Fix typo 2024-01-21 14:42:39 +01:00
Ozzie Isaacs ce83fb6816 Update bug_report.md 2024-01-21 14:37:12 +01:00
Ozzie Isaacs fbfb7adef6 Update issue templates 2024-01-21 14:33:50 +01:00
Ozzie Isaacs cc52ad5d27 Added Notice 2024-01-21 14:27:38 +01:00
Ozzie Isaacs 706b9c4013 Improved errorhandling for adding invalid book_id to shelf 2024-01-21 08:12:49 +01:00
Ozzie Isaacs 6972c1b841 Improved errorhandling for adding invalid book_id to shelf 2024-01-21 08:12:28 +01:00
Ozzie Isaacs b9c329535d Fix for #2980 (invalid seriesindex causes no longer a crash) 2024-01-18 19:41:46 +01:00
Ozzie Isaacs 8fdf7a94ab Updated testresult 2024-01-18 19:37:33 +01:00
Ozzie Isaacs 31a344b410 Bugfix from testrun 2024-01-17 20:29:47 +01:00
Ozzie Isaacs 3814fbf08f Bugfixes from testrun 2024-01-14 14:28:08 +01:00
Ozzie Isaacs ffc13a5565 Merge branch 'master' into Develop 2024-01-13 14:48:09 +01:00
Ozzie Isaacs 74c61d9685 Merge branch 'metadata' into Develop 2024-01-13 14:47:48 +01:00
Ozzie Isaacs b8031cd53f Add possibility to replace kepub metadata on download 2024-01-13 14:31:42 +01:00
Ozzie Isaacs 898e76fc37 re enable gevent 2024-01-13 12:32:54 +01:00
Ozzie Isaacs af71a1a2ed Fix for #2973 (No unix sockets on windows available) 2024-01-13 12:26:53 +01:00
Ozzie Isaacs e0327db08f Enable embedd metadata of kepub file during conversion 2024-01-08 20:51:38 +01:00
Purbayan Chowdhury 05032aed3c Updating theme logic and persisting theme change 2024-01-08 16:56:13 +05:30
Ozzie Isaacs bf2ac97c47 Update setup.cfg 2024-01-07 13:28:31 +01:00
Ozzie Isaacs 902fa254b0 Merge branch 'master' into Develop 2024-01-07 08:03:40 +01:00
Ozzie Isaacs f0cc93abd3 Sanitze username for logging 2024-01-06 16:08:14 +01:00
Ozzie Isaacs 977f07364b Fix for #2961 (empty comment with newline causes error 500 on upload)
Language of error message for kobo sync improved
2024-01-06 16:08:14 +01:00
Ozzie Isaacs 00acd745f4 Fix tornado deprecation warning 2024-01-06 16:08:14 +01:00
Ozzie Isaacs d272f43424 Show error message if user is missing download permission for kobo sync 2024-01-06 16:08:14 +01:00
Whatever Cloud 7a8d8375d0 Refactor detail.html to optimize custom_column rendering
The div with class "real_custom_columns" is now only rendered if the custom_column data exists, removing blank space in details view.
2024-01-01 20:38:05 +01:00
Johannes H 3aa75ef4a7 fix: link to Linux Mind installation in README.md
the link the wiki page had an typo (missing '-') https://github.com/janeczku/calibre-web/wiki/How-To:-Install-Calibre-Web-in-Linux-Mint-19-or-20
2023-12-30 14:19:39 +01:00
Ozzie Isaacs 25fb8d934f Merge remote-tracking branch 'nl/master' 2023-12-21 13:47:02 +01:00
GONCALVES Nelson (T0025615) f08c8faaff Generate identifiers in opf metadata file 2023-12-21 11:02:45 +01:00
Michiel Cornelissen bc0ebdb78d Updated Dutch translation. 2023-12-20 21:52:09 +01:00
Ozzie Isaacs 2a4b3cb7af Update Teststatus
Add hint for calibre binary
2023-12-17 08:04:16 +01:00
Ozzie Isaacs 4401cf66d1 Remove remains of ie8 support 2023-12-16 17:23:20 +01:00
Ozzie Isaacs d353c9b6d3 Fix #2945 (handle illegal multibyte sequence) 2023-12-16 10:48:49 +01:00
Ozzie Isaacs 0aba96c032 Update Teststatus 2023-12-16 10:31:36 +01:00
Ozzie Isaacs c60b7e9192 Update teststatus 2023-12-14 07:09:50 +01:00
Ozzie Isaacs 23033255b8 Bugfix updater 2023-12-12 18:15:48 +01:00
Ozzie Isaacs 31c8909dea Merge branch 'Develop' into metadata -> Now all tests should run "pass" now
# Conflicts:
#	cps/constants.py
#	cps/helper.py
#	cps/tasks/convert.py
#	test/Calibre-Web TestSummary_Linux.html
2023-12-11 14:23:12 +01:00
Ozzie Isaacs 9ef89dbcc3 Bugfix convert file from gdrive without cover
Update Teststatus
2023-12-10 15:23:26 +01:00
Ozzie Isaacs 1086296d1d Make embed metadata configurable 2023-12-09 11:29:11 +01:00
Ozzie Isaacs d341faf204 Make Version setuptools compatible and still have the "Beta" in the User interface 2023-12-09 09:36:28 +01:00
Ozzie Isaacs 2334e8f9c9 Refactored calibre executable detection for better error messages 2023-12-07 16:47:10 +01:00
Ozzie Isaacs 90ad570578 Show only folders for selecting converter binaries 2023-12-07 16:22:34 +01:00
Ozzie Isaacs fd90d6e375 Delete temp dir not shown in tasks overview
Handle case no cover during convert ebook
2023-12-06 19:33:22 +01:00
Ozzie Isaacs 7fbbb85f47 Temp folder is deleted on regular base 2023-12-04 19:26:43 +01:00
Ozzie Isaacs 52c7557878 Merge remote-tracking branch 'caliblur/issue/caliBlur2931'
Updated optional requirements
2023-12-04 19:05:39 +01:00
Ozzie Isaacs 794cd354ca Added ToDo's 2023-12-04 18:57:50 +01:00
Ghighi Eftimie 389e3f09f5 small fix for mobile resolution - add to shelf button 2023-12-04 16:40:56 +02:00
Ghighi Eftimie 285979b68d fix for 2931 2023-12-04 16:00:00 +02:00
Ozzie Isaacs 3a012c900e Merge branch 'master' into Develop 2023-11-28 18:00:26 +01:00
Ozzie Isaacs ec45de3212 Merge remote-tracking branch 'douban/master' 2023-11-28 17:59:48 +01:00
Ozzie Isaacs f644a2a136 Merge remote-tracking branch 'kobo_cover/patch-1' 2023-11-28 17:56:36 +01:00
Russell 01108aac42 Remove trailing slash
Signed-off-by: Russell <russell@troxel.io>
2023-11-26 22:01:26 -08:00
Russell Troxel 400c745692 Update KOBO_IMAGEHOST_URL to new CDN endpoint
Kobo has introduced a vanity URL to their Akamai CDN config - "https://https://cdn.kobo.com". As a result, requests sent to the old raw Akamai endpoint now through 404s. This is a simple PR that updates to the new URL.

This is visible in the config of a newly bought Kobo Sage (mine):
```
image_host=https://cdn.kobo.com/book-images/
image_url_quality_template=https://cdn.kobo.com/book-images/{ImageId}/{Width}/{Height}/{Quality}/{IsGreyscale}/image.jpg
image_url_template=https://cdn.kobo.com/book-images/{ImageId}/{Width}/{Height}/false/image.jpg
```

Example:

OLD:
https://kbimages1-a.akamaihd.net/1abfb307-457b-4597-b2ea-74beb2eb1478/149/223/false/image.jpg
(Throws 404)

New:
https://cdn.kobo.com/book-images/1abfb307-457b-4597-b2ea-74beb2eb1478/149/223/false/image.jpg
(Renders Properly)

fixes #2371 
ref #2731
2023-11-26 14:31:24 -08:00
ye 9841a4d068 fix the the problem that metadata_provider/douban.py can't get tags info 2023-11-26 09:06:25 +08:00
Ozzie Isaacs 7fd1d10fca Implement gdrive metadata on download 2023-11-11 15:26:05 +01:00
Ozzie Isaacs 4f6bbfa8b8 Little refactoring do_download 2023-11-11 15:00:12 +01:00
Ozzie Isaacs cf6810db87 Refactored get_temp_dir
bugfixes export_metadata
2023-11-11 14:48:59 +01:00
Ozzie Isaacs 5afff2231e Fix for #2743 (read status is no longer implicitly added to advanced search query) 2023-11-11 10:43:50 +01:00
Ozzie Isaacs d611582b78 Fix for #2743 (read status is no longer implicitly added to advanced search query) 2023-11-11 10:43:23 +01:00
Ozzie Isaacs 3bbd8ee27e Use belach or nh3 for cleaning html (fix for #2874) 2023-11-09 17:59:20 +01:00
Ozzie Isaacs f78e0ff938 Use belach or nh3 for cleaning html (fix for #2874) 2023-11-09 17:59:06 +01:00
Ozzie Isaacs bd71391bfb Possible fix for #2849 (404 error during sync request) 2023-11-09 17:43:02 +01:00
Ozzie Isaacs 20b2936cc1 Merge branch 'master' into Develop 2023-11-09 17:41:39 +01:00
Ozzie Isaacs 19825a635a Possible fix for 2849 (404 error during sync request) 2023-11-09 17:41:20 +01:00
Ozzie Isaacs 0d611d35de Updated Testresult
Updated requirements
2023-11-09 06:39:25 +01:00
Ozzie Isaacs effd026fe2 Merge branch 'master' into Develop 2023-11-08 20:36:49 +01:00
Ozzie Isaacs d68e57c4fc Implement split library and books
Bugfix arrows in comic reader
Fix kobo download link
Updated requirement
2023-11-08 20:11:03 +01:00
Ozzie Isaacs 184ce23351 Catch error with tornado on restart 2023-11-06 18:05:36 +01:00
Ozzie Isaacs 2fbc3da451 Added Slovak translation 2023-11-06 16:51:08 +01:00
Ozzie Isaacs fad6550ff1 Show "all" opds feed entries only if there is at least one entry 2023-11-06 16:35:39 +01:00
Ozzie Isaacs b7aaa0f24d Add metadata change code 2023-11-02 17:05:02 +01:00
Ozzie Isaacs 5040bb762c Merge remote-tracking branch 'vi/master' 2023-11-02 16:35:54 +01:00
Ozzie Isaacs 55deca1ec8 Catch additional errors on logfile
Fix error on exception in session management
2023-11-02 16:34:04 +01:00
Ozzie Isaacs 40a16f4717 Reenabled gevent as server 2023-11-01 07:47:29 +01:00
Ozzie Isaacs d26e60724a Socket listening and socket activation enabled on tornado
Refactoring of server code
Updates requirements
Improved requirements parsing for versions containing letters
2023-10-30 14:39:22 +01:00
Ozzie Isaacs d877fa1c68 Merge remote-tracking branch 'socket-activation/socket-activated' 2023-10-29 08:20:03 +01:00
Ozzie Isaacs d55bafdfa9 Added hint for beta release format 2023-10-28 19:10:44 +02:00
Ozzie Isaacs a2a431802a Added prc to supported convert from formats (#2801)
Improved error message for not able to listen to ipv6 address with gevent
2023-10-28 13:49:16 +02:00
Ozzie Isaacs b2e4907165 Merge branch 'master' into Develop 2023-10-28 09:06:51 +02:00
Ozzie Isaacs 6c2e40f544 Added favicon in opds feed
Merge remote-tracking branch 'favicon/master'
2023-10-28 09:05:24 +02:00
Ozzie Isaacs 5e3d0ec2ad Fix location of config files for executable files (#2917) 2023-10-28 08:48:13 +02:00
Ozzie Isaacs c550d6c90d Fix comic reader arrow visiblilty for one paged comic files
Changed logging during kobo sync
2023-10-28 08:48:13 +02:00
bacpd 3b1d0b4013 Update messages.po 2023-10-25 15:08:10 +07:00
Ozzie Isaacs 3d07efbb4f Update Italian and German translation 2023-10-21 15:47:35 +02:00
mapi68 c0ae5bb381 Update messages.po 2023-10-21 15:34:09 +02:00
Ozzie Isaacs 6e755a26f9 Version update
Updated security file
2023-10-21 14:37:21 +02:00
Ozzie Isaacs c45188beb2 Version update 2023-10-21 12:40:32 +02:00
Ozzie Isaacs 0736c53d7b Update teststatus 2023-10-18 18:14:00 +02:00
Ozzie Isaacs f0f8011d24 Modified build script to avoid warnings 2023-10-16 18:17:54 +02:00
Ozzie Isaacs 65f3ecb924 Updated test results 2023-10-15 15:43:50 +02:00
Ozzie Isaacs 87b3999ec8 Merge remote-tracking branch 'ko/master' 2023-10-14 15:55:27 +02:00
Ozzie Isaacs e32312b54a Merge branch 'master' into Develop 2023-10-14 15:53:10 +02:00
Ozzie Isaacs d7ea569e5d Merge remote-tracking branch 'upload_text/patch-1' into Develop 2023-10-14 15:52:37 +02:00
Ozzie Isaacs 96958e7266 Merge remote-tracking branch 'upload_text/patch-1' 2023-10-14 15:48:06 +02:00
Ozzie Isaacs 2c339ed10c Merge branch 'Develop':
- Fix for new tornado version
- bookmark for comic viewer
- Bugfix for showing series containing only one book in list view containing having this book no series_index value set
- updated requirements
2023-10-14 15:30:44 +02:00
Ozzie Isaacs dc2c30f508 Added additional debug output for download links during kobo sync 2023-10-14 09:51:54 +02:00
Ozzie Isaacs 0c43d80163 Added additional debug output for download links
Removed unused code
2023-10-14 09:51:19 +02:00
Ozzie Isaacs df71a86f94 New testrun 2023-10-14 09:34:34 +02:00
Ozzie Isaacs 7ed56b4397 Better fix for new tornado version 2023-10-08 15:46:51 +02:00
Ozzie Isaacs 5ceb2b6d83 Merge branch 'master' into Develop 2023-10-04 20:11:34 +02:00
Ozzie Isaacs 8abea1ddd0 Fix for #2904, werkzeug breaks master branch 2023-10-04 19:46:14 +02:00
Ozzie Isaacs 11816d3405 Fix for tornado 6.3 no response in restart moment
Update test results (many tests fail due to above problem)
2023-10-03 08:12:33 +02:00
Ozzie Isaacs 198bff928f Merge remote-tracking branch 'cn/master' 2023-10-02 20:03:27 +02:00
lawsssscat cac200ba61 Fix messages.po in zh_Hans_CN 2023-09-25 10:48:41 +08:00
David K 8cc36ab081 Clarify Enable Uploads text.
This change updates the help text next to the `Enable Uploads` setting.

- Current: `Please ensure users having also upload rights`
- Update: `Please ensure that users also have upload permissions`

---

The current help text is a little odd in terms of sentence structure for an English speaker.
The updated version clarifies the meaning.
2023-09-11 10:35:01 +01:00
databoy2k b3d1558df8 Add Favicon to OPDS Feed
<icon> is a standard of the OPDS spec, and this commit adds the favicon to the feed. Certain OPDS readers, e.g. FBReader on Windows, respect this tag and will show the same icon as the main page.
2023-09-08 13:09:40 -06:00
byword77 a045b6f467 Update messages.po
It is final commit. 
I made a mistake in the previous update. 
So, Please disregard the previous file.
2023-09-05 17:01:38 +09:00
Ozzie Isaacs 7a961c9011 Fix for click on scrollbar in long strip view
Fix for tornado version
2023-09-01 07:35:48 +02:00
Ozzie Isaacs 444ac181f8 more bookmark feature
tornado fix for tornado <6.2
2023-08-31 17:03:56 +02:00
Ozzie Isaacs 4bbcec21e4 Update test results 2023-08-31 11:42:55 +02:00
Ozzie Isaacs 5509d4598b Bugfix for showing series coatining only one book in list view containing having this book no series_index value set 2023-08-30 20:23:40 +02:00
Ozzie Isaacs fab35e69ec Update Teststatus
Little code refactoring
2023-08-29 20:05:57 +02:00
Ozzie Isaacs 4f0f5b1495 Merge remote-tracking branch 'origin/Develop' into Develop
# Conflicts:
#	optional-requirements.txt
2023-08-28 19:38:51 +02:00
Ozzie Isaacs cfa309f0d1 Merge branch 'master' into Develop
# Conflicts:
#	cps/services/SyncToken.py
#	cps/static/js/kthoom.js
#	cps/templates/readcbr.html
2023-08-28 18:08:19 +02:00
Ozzie Isaacs 885d914f18 Update tornado to 6.2
Remove unneeded imports from jsonschema for synctoken
Update optional requirements
Remove invalid direction arrows in comic reader
2023-08-28 18:06:32 +02:00
Ozzie Isaacs b580f418f7 Merge branch 'master' into Develop 2023-08-27 15:12:26 +02:00
Ozzie Isaacs 6a14e2cf68 Next try showing last book of series in grid view 2023-08-27 12:00:34 +02:00
Ozzie Isaacs 8535bb5821 Fix "got an unexpected keyword argument 'rarExecutable'" during format upload 2023-08-27 11:20:53 +02:00
Ozzie Isaacs b2a26a421c Removed deprecation warning for sqlalchemy2.0 2023-08-26 20:26:01 +02:00
Ozzie Isaacs 7aea7fc0bb Merge remote-tracking branch 'comic-bookmark/comics-save-position'
# Conflicts:
#	cps/static/js/kthoom.js
#	cps/templates/readcbr.html
#	cps/web.py
2023-08-26 20:13:42 +02:00
Ozzie Isaacs 52172044e6 Fix deprecation warnings 2023-08-26 20:12:52 +02:00
Ozzie Isaacs 9b99427c84 Merged comic save position 2023-08-26 20:12:34 +02:00
Ozzie Isaacs 0499e578cd Added /opds/stats route 2023-08-24 13:49:22 +02:00
Ozzie Isaacs b3a85ffcbb Added CB7 to supported upload formats 2023-08-24 10:51:16 +02:00
PhracturedBlue 074e611705 Add support for systemd socket-activation 2023-08-23 20:52:05 -07:00
Ozzie Isaacs a1899bf582 Fix for #2603 (Kobo UserKey in request missing due to no kobo account) 2023-08-23 21:13:17 +02:00
Ozzie Isaacs f7ff3e7cba Added py7zr to setup.cfg 2023-08-23 20:50:39 +02:00
Ozzie Isaacs 3a08b91ffa Added cb7 to supported comic files for upload and metadata extraction 2023-08-16 18:44:15 +02:00
Ozzie Isaacs d253804a50 fix for #2865 (Kobo sync fails during cover request) 2023-08-16 18:04:45 +02:00
Ozzie Isaacs ba0e5399d6 Fixes Uploading pdf file fails with whitespace title (#2824)
Merge remote-tracking branch 'pdf_title/fix/title-parsing-of-pdf-metadata'
2023-08-12 14:09:14 +02:00
lucas 7e46f9c0b1 Add font/spread customize for epub reader 2023-08-09 17:10:09 +08:00
Ozzie Isaacs 7818c4a7b0 Adapt cover size to kobo sync requested sze 2023-08-08 19:21:47 +02:00
Ozzie Isaacs 3f6a12898b Merge branch 'Develop' 2023-07-31 19:02:41 +02:00
Ozzie Isaacs caf69669cb Removed encode utf-8 in dodownload 2023-07-31 19:01:15 +02:00
Ozzie Isaacs de59181be7 Merge remote-tracking branch 'home/link_fixes' into Develop 2023-07-31 18:49:53 +02:00
Ozzie Isaacs 966c9236b9 Merge remote-tracking branch 'home/link_fixes' 2023-07-30 20:00:18 +02:00
Ozzie Isaacs 34c6010ad0 Catch additional error during kobo detect layout 2023-07-30 19:57:42 +02:00
Ozzie Isaacs 60e904967b Fix deprecated text parameter 2023-07-30 19:47:29 +02:00
Ozzie Isaacs 3efcbcc679 Fix deprecated text parameter 2023-07-30 07:44:41 +02:00
Ozzie Isaacs 7bb4bc934c Merge remote-tracking branch 'caliblur/issues/caliblur2838' 2023-07-29 15:36:44 +02:00
Ozzie Isaacs dcb8a0f77b Merge remote-tracking branch 'lubimyczytac/fix-lubimyczytac-metadata' 2023-07-29 15:35:53 +02:00
Ozzie Isaacs 2f12b2e315 Handle invalid or missing container.xml during kobo sync (Fix for #2840) 2023-07-29 15:32:35 +02:00
Ozzie Isaacs 279f0569e4 Fix visibility for sending to reader without download permissions (fix for #2847) 2023-07-29 15:15:38 +02:00
Ozzie Isaacs 6723369d65 Merge branch 'master' into Develop
# Conflicts:
#	cps/admin.py
2023-07-29 12:12:03 +02:00
Ozzie Isaacs 4b93ac034f Do not show password in smtp settings 2023-07-29 12:11:04 +02:00
Ozzie Isaacs fda62dde1d Fix for not changing password in email settings
Improved ssl certificate check on sending emails
2023-07-29 12:03:45 +02:00
Ozzie Isaacs df74fdb4d1 Update edit identifiers 2023-07-29 11:10:54 +02:00
Ozzie Isaacs cce538d5a7 Update Testresult 2023-07-28 13:44:56 +02:00
Ozzie Isaacs e8b0051b31 Merge development into master 2023-07-26 21:43:18 +02:00
Ozzie Isaacs fe55958ecc Update Teststatus 2023-07-26 21:42:19 +02:00
Ozzie Isaacs 7b321d63c1 update testresults 2023-07-26 21:42:19 +02:00
Ozzie Isaacs 986eaf9f02 Merge remote-tracking branch 'br/horus68-pt-translation' 2023-07-26 20:49:13 +02:00
Ozzie Isaacs caf8ed77d7 Merge remote-tracking branch 'br/horus68-ptbr-fix' 2023-07-26 20:30:19 +02:00
Ghighi Eftimie ee5cfa1f36 fix for #2838 2023-07-26 15:11:04 +03:00
Horus68 5eef476135 Update messages.po 2023-07-25 13:48:57 +01:00
Horus68 b5e4a88357 Update messages.po 2023-07-25 13:11:08 +01:00
Horus68 256f4bb428 Update messages.po
fix typo
2023-07-25 11:43:03 +01:00
Horus68 a4d45512ee pt-BR Update messages.po
fixing pt-BR major errors
2023-07-25 11:40:26 +01:00
Horus68 074687c330 Create pt-PT translation
Translation to european portuguese - pt-PT portuguese (Portugal)
Note: messages.mo not created as file was translated directly in browser
2023-07-25 11:29:20 +01:00
archont 2f7b175dda Fix tags xpath 2023-07-16 18:50:54 +02:00
Ozzie Isaacs a256bd5260 Password is not returned in smtp settings 2023-07-09 10:23:56 +02:00
Ozzie Isaacs fdd1410b06 Improved pathchooser 2023-07-09 10:01:48 +02:00
Ozzie Isaacs 3f5583017f Improved pathchooser 2023-07-09 10:00:54 +02:00
Ozzie Isaacs 63b7d70f33 Update optional requirements
Update to be compatible with comicapi 3.2
2023-06-25 14:39:45 +02:00
Ozzie Isaacs 500758050c Fixed typo in German translation 2023-06-25 11:32:23 +02:00
Ozzie Isaacs 4b4c0daab0 Update testresults 2023-06-18 18:30:01 +02:00
Ozzie Isaacs 709a4e51ba Testrun 2023-06-18 11:17:06 +02:00
Ozzie Isaacs eff0750d77 Fix for renaming uppercase/lowercase author, tag, series, publisher entries (fix for #2787)
Update epub.js
2023-06-18 10:17:55 +02:00
Ozzie Isaacs e63a04093c Bugfix rename author in book list 2023-06-18 10:14:53 +02:00
Ozzie Isaacs 07d97d18d0 Merge remote-tracking branch 'epubreader/update_epub.min.js' into Develop 2023-06-17 15:50:51 +02:00
Ozzie Isaacs d8f30983d5 Merge remote-tracking branch 'readme/patch-1' 2023-06-17 15:48:18 +02:00
Ozzie Isaacs 062efc4e78 Bugfix change uppercase/lowercase on edit authors
Remove autocomplete on several elements to make typeahead work without problems
2023-06-17 10:47:23 +02:00
boosh 4e6c9c2703 Update README.md
Link to the raw download URL of the metadata.db file
2023-06-13 06:23:53 +00:00
Ozzie Isaacs 4dc5885723 Bugfix for upper/lowercase rename if not before part of book 2023-06-10 10:37:22 +02:00
quarz12 5e15cac598 deleted empty lines 2023-06-09 18:32:32 +02:00
quarz12 d0551274dc switched to using epub.min.js, deleted now unnecessary dependencies 2023-06-09 18:32:30 +02:00
quarz12 99c05650a1 -added pako and epub-cfi-resolver as dependencies
-cfi resolving is now done by that module, therefore removed validateChildNodes and adjusted cfiToXmlNode
2023-06-09 18:32:28 +02:00
quarz12 617ee3d781 now shows correct numbers, still needs bugfixes 2023-06-09 18:32:26 +02:00
quarz12 47aa3254c7 better css positioning 2023-06-09 18:32:24 +02:00
quarz12 0717b9493c added progress display, better rounding
TODO: getPrev gives wrong values,
design, testing
2023-06-09 18:32:22 +02:00
quarz12 824ebc4d76 added event on change position 2023-06-09 18:32:22 +02:00
quarz12 cbaa61bbb7 EpubParser now gets automatically loaded
TODO:detect page change, display number
2023-06-09 18:32:15 +02:00
quarz12 dbac685985 implemented current file process, needs testing but looks good 2023-06-09 18:32:11 +02:00
quarz12 b25c024b66 added getCurrentFileProgress,
TODO: resolve CFI to xml node
2023-06-09 18:32:10 +02:00
quarz12 bc65180c32 restructured and fixed a bug in getprevfilesize 2023-06-09 18:32:06 +02:00
quarz12 10c66b6e63 wrote a class to handle epub parsing, implemented bytesize of all previous files, total bytesize. still needs implementation of bytesize of current file until CFI point. 2023-06-09 18:32:05 +02:00
quarz12 c29b1696f7 added function to get bytelength of book text 2023-06-09 18:31:55 +02:00
quarz12 39638d3c9c updated epub.min.js to version 0.3.93 2023-06-09 16:11:53 +02:00
Ozzie Isaacs 3ef34c8f15 Bugfixes rename upper-lowercase after testrun 2023-06-08 10:28:42 +02:00
Ozzie Isaacs 932abbf090 Merge remote-tracking branch 'error_scroll/error_page' 2023-06-05 14:54:10 +02:00
Ozzie Isaacs 860443079d Fix for (#2802) search request fails with error after browser session closed and currently returns all results 2023-06-05 14:41:03 +02:00
Ozzie Isaacs bd4b7ffaba Fix for upper lower change of non ascii values in series, tags, ... 2023-05-30 20:02:52 +02:00
Ozzie Isaacs 33e35eeb52 Added option -o to define logfile via command line (fixes #2792) 2023-05-29 11:29:14 +02:00
Ozzie Isaacs ed09814460 Prevent log_message on startup
logfile Parameter
2023-05-28 20:42:18 +02:00
Ozzie Isaacs e52eb74121 Merge branch 'Develop' 2023-05-28 19:58:33 +02:00
Daniel dc7fbce4f7 changed style property of container 2023-05-28 13:21:26 +02:00
Ozzie Isaacs dad0fd5a1c Update test results 2023-05-28 10:24:40 +02:00
Ozzie Isaacs 8a87c152b4 Bugfix opds search 2023-05-27 16:25:06 +02:00
Ozzie Isaacs 16baa306c5 Update test results 2023-05-27 15:32:48 +02:00
Daniel 2eb334fb3d fixed a typo in http_error.html which broke the github link
changed the behavior of the home button so it directs to the application root, not the server root .
2023-05-08 21:48:04 +02:00
Ozzie Isaacs cb7356a04d Fixes to word with new version of comicapi 2023-05-04 20:23:02 +03:00
Ozzie Isaacs 63a561bf9b Merge remote-tracking branch 'chinese/translation/Simplified_Chinese' 2023-05-04 19:54:06 +03:00
Ozzie Isaacs cc733454b2 Merge remote-tracking branch 'chinese/translation/Simplified_Chinese' 2023-04-30 19:38:59 +03:00
whilenot 940544577a don't mutate meta into a str, keep it a namedtuple 2023-04-30 13:37:08 +02:00
xlivevil 9e0fc320cb Update Simplified Chinese translation 2023-04-25 16:03:28 +08:00
xlivevil bf3ca20fb2 Update Simplified Chinese translation 2023-04-25 15:38:40 +08:00
Ozzie Isaacs c7e1736ade Merge branch 'master' into Develop 2023-04-23 11:05:19 +02:00
Ozzie Isaacs bc6a50550e Merge branch 'master' into Develop 2023-04-23 11:03:12 +02:00
Ozzie Isaacs fe4dc1bb8f Fix #2757 (Sqlalchemy >1.30 <1.4.24 wasn't supported anymore) 2023-04-22 09:25:54 +02:00
Ozzie Isaacs f2369609e8 Bugfix for non existent rating, language, and user downloaded books 2023-04-18 20:53:55 +02:00
Ozzie Isaacs de4d6ec7df Merge remote-tracking branch 'it/patch-1' 2023-04-18 20:06:46 +02:00
mapi68 7754f4aa5d Update messages.po 2023-04-18 09:05:19 +02:00
Ozzie Isaacs 524751ea51 Removed superfluous space 2023-04-17 18:52:52 +02:00
Ozzie Isaacs 8111d0dd51 Update translation status 2023-04-16 15:06:34 +02:00
Ozzie Isaacs fad5929253 Bugfix getPath for logfile viewer 2023-04-16 13:08:50 +02:00
Ozzie Isaacs 9f28144779 Fix for #2756 (Home button in caliblur is leading to "/" instead of calibre-web home) 2023-04-16 09:43:13 +02:00
Ozzie Isaacs 42fd6973a0 Merge remote-tracking branch 'readme/patch-1' 2023-04-15 19:15:21 +02:00
driz b2e20ff50c update readme due to my mistake on link
i fubarred the optional calibre layer somehow, my apologies

thanks for all you guys do, myself and my entire family love calibre-web :)
2023-04-15 13:02:55 -04:00
Ozzie Isaacs 6075b3dd1d Merge remote-tracking branch 'readme/patch-2' 2023-04-15 18:46:45 +02:00
driz 37871ea8cb Update README.md
this is built against the formatting changes of https://github.com/janeczku/calibre-web/pull/2742
it corrects the docker-mods section which is incorrect, fixes a dead link, and removes armhf from the listed of supported arches.
2023-04-15 11:38:04 -04:00
Ozzie Isaacs e2785c3985 Added djv file format to djvu reader 2023-04-15 15:25:46 +02:00
Ozzie Isaacs dba83a2900 Fixes for sqlalachemy2 2023-04-15 13:22:17 +02:00
Ozzie Isaacs 33c19b20f4 Merge remote-tracking branch 'readme/update-readme' 2023-04-15 11:20:52 +02:00
Ozzie Isaacs d2f39d3dce Update Teststatus 2023-04-15 11:00:38 +02:00
Ozzie Isaacs 1c8bc78b48 Improvements for sqlalchemy 2 2023-04-13 19:01:53 +02:00
Ozzie Isaacs 6c6841f8b0 Further fixes for sqlalchemy 2.0 2023-04-12 18:56:21 +02:00
Ozzie Isaacs 592216588c Revert "post" as search request. Search request is now get again (fix for #2741)
Revert "Auxiliary commit to revert individual files from 275675b48add79d2bbce06426cc1224c5e2c1bfb"

This reverts commit 6c920bc49f133d5c7451230448121f1f8b3cd9f2.
2023-04-12 18:29:15 +02:00
Wladimir Kirianov f4db0f04d2 add table of contents and contributor recognition section 2023-04-09 13:07:33 +02:00
Wladimir Kirianov b16e3a6e2c Update README.md for clarity, formatting, and improved readability 2023-04-09 12:36:19 +02:00
Ozzie Isaacs 13c0d30a8f Update login
Removed not needed parameters for task status
2023-04-03 20:00:40 +02:00
Ozzie Isaacs b9c942befc Fix for 'NoneType' object has no attribute 'author_sort' while trying to read a book (#2733) 2023-03-31 07:48:18 +02:00
Ozzie Isaacs a68a0dd037 Fixed typo 2023-03-30 11:25:34 +02:00
Thomas de Ruiter a952c36ab7 Remove unused fallback cover handling 2023-03-28 16:13:10 +02:00
Thomas de Ruiter 5f0c7737fe Fix proxy cover images to Kobo store 2023-03-28 15:56:02 +02:00
Ozzie Isaacs 38484624e9 Version update 2023-03-27 20:20:18 +02:00
Olivier b45d69ef2d set currentImage to the start if no bookmark 2022-10-11 23:43:54 +09:00
Olivier a80735d7d3 Save the position of the last read page for comics 2022-10-11 23:37:12 +09:00
gjutras c974cd048e minor formatting 2022-08-02 19:51:31 -04:00
gjutras 24e9bf2728 Merge branch 'janeczku:master' into master 2022-08-01 16:38:46 -04:00
Thore Schillmann 9bcbe523d7 (draft) metadata embedding when sending to device 2022-07-22 08:58:28 +00:00
Thore Schillmann e176d63ca6 Merge branch 'embed_metadata_on_convert' into embed_metadata_on_download 2022-07-14 13:39:58 +00:00
Thore Schillmann 80b0e88650 fix for GDrive integration 2022-07-14 13:34:42 +00:00
Thore Schillmann 0b4731913e created do_calibre_export function 2022-07-14 09:25:37 +00:00
Thore Schillmann fc7ce8da2d cleanup 2022-07-13 15:39:01 +00:00
gjutras ff46af9c49 fix indentation and spaces 2022-07-10 17:23:20 -04:00
gjutras 0a7345186d Merge branch 'janeczku-master'
# Conflicts:
#	cps/helper.py
#	cps/tasks/convert.py
#	cps/templates/user_edit.html
2022-07-08 16:42:14 -04:00
Thore Schillmann c89bc12c9b Merge branch 'embed_metadata_on_convert' into embed_metadata_on_download 2022-07-07 14:09:15 +00:00
Thore Schillmann 4913673e8f added subprocess.wait() when getting metadata 2022-07-07 11:47:10 +00:00
Thore Schillmann fc004f4f0c moved get_calibre_binarypath() to helper.py 2022-07-07 11:41:51 +00:00
Thore Schillmann c5c3874243 first implementation 2022-07-01 16:04:25 +00:00
Thore Schillmann 0d34f41a48 cleanup of autodetect_converter_binary 2022-07-01 12:06:33 +00:00
Thore Schillmann a77aef83c6 automatically set config_converterpath 2022-06-30 13:05:36 +00:00
Thore Schillmann e39c6130c3 cleanup and better error handling 2022-06-29 19:54:53 +00:00
Thore Schillmann 03359599ed input validation for calibre binary directory 2022-06-23 20:02:54 +00:00
Thore Schillmann 3c4330ba51 refactoring of calibre binary detection 2022-06-21 17:04:44 +00:00
Thore Schillmann 8c781ad4a4 code cleanup and implements cover change 2022-06-19 23:20:59 +00:00
Thore Schillmann 5e9ec706c5 first draft of embedding metadata on conversion 2022-06-19 22:59:54 +00:00
gjutras cb0d9ec95c Allow kindle_email to be CSV to allow sending to multiple kindles 2022-03-28 19:59:59 -04:00
509 changed files with 170624 additions and 139727 deletions
+18 -2
View File
@@ -6,12 +6,23 @@ labels: ''
assignees: ''
---
<!-- Please have a look at our [Contributing Guidelines](https://github.com/janeczku/calibre-web/blob/master/CONTRIBUTING.md) -->
**Describe the bug/problem**
## Short Notice from the maintainer
After 6 years of more or less intensive programming on Calibre-Web, I need a break.
The last few months, maintaining Calibre-Web has felt more like work than a hobby. I felt pressured and teased by people to solve "their" problems and merge PRs for "their" Calibre-Web.
I have turned off all notifications from GitHub/Discord and will now concentrate undisturbed on the development of “my” Calibre-Web over the next few weeks/months.
I will look into the issues and maybe also the PRs from time to time, but don't expect a quick response from me.
Please also have a look at our [Contributing Guidelines](https://github.com/janeczku/calibre-web/blob/master/CONTRIBUTING.md)
**Describe the bug/problem**
A clear and concise description of what the bug is. If you are asking for support, please check our [Wiki](https://github.com/janeczku/calibre-web/wiki) if your question is already answered there.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
@@ -19,15 +30,19 @@ Steps to reproduce the behavior:
4. See error
**Logfile**
Add content of calibre-web.log file or the relevant error, try to reproduce your problem with "debug" log-level to get more output.
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Environment (please complete the following information):**
- OS: [e.g. Windows 10/Raspberry Pi OS]
- Python version: [e.g. python2.7]
- Calibre-Web version: [e.g. 0.6.8 or 087c4c59 (git rev-parse --short HEAD)]:
@@ -37,3 +52,4 @@ If applicable, add screenshots to help explain your problem.
**Additional context**
Add any other context about the problem here. [e.g. access via reverse proxy, database background sync, special database location]
+8 -1
View File
@@ -7,7 +7,14 @@ assignees: ''
---
<!-- Please have a look at our [Contributing Guidelines](https://github.com/janeczku/calibre-web/blob/master/CONTRIBUTING.md) -->
# Short Notice from the maintainer
After 6 years of more or less intensive programming on Calibre-Web, I need a break.
The last few months, maintaining Calibre-Web has felt more like work than a hobby. I felt pressured and teased by people to solve "their" problems and merge PRs for "their" Calibre-Web.
I have turned off all notifications from GitHub/Discord and will now concentrate undisturbed on the development of “my” Calibre-Web over the next few weeks/months.
I will look into the issues and maybe also the PRs from time to time, but don't expect a quick response from me.
Please have a look at our [Contributing Guidelines](https://github.com/janeczku/calibre-web/blob/master/CONTRIBUTING.md)
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
+4 -4
View File
@@ -20,7 +20,7 @@ Some of the user languages in Calibre-Web having missing translations. We are ha
### **Documentation**
The Calibre-Web documentation is hosted in the Github [Wiki](https://github.com/janeczku/calibre-web/wiki). The Wiki is open to everybody, if you find a problem, feel free to correct it. If information is missing, you are welcome to add it. The content will be reviewed time by time. Please try to be consistent with the form with the other Wiki pages (e.g. the project name is Calibre-Web with 2 capital letters and a dash in between).
The Calibre-Web documentation is hosted in the GitHub [Wiki](https://github.com/janeczku/calibre-web/wiki). The Wiki is open to everybody, if you find a problem, feel free to correct it. If information is missing, you are welcome to add it. The content will be reviewed time by time. Please try to be consistent with the form with the other Wiki pages (e.g. the project name is Calibre-Web with 2 capital letters and a dash in between).
### **Reporting a bug**
@@ -28,12 +28,12 @@ Do not open up a GitHub issue if the bug is a **security vulnerability** in Cali
Ensure the **bug was not already reported** by searching on GitHub under [Issues](https://github.com/janeczku/calibre-web/issues). Please also check if a solution for your problem can be found in the [wiki](https://github.com/janeczku/calibre-web/wiki).
If you're unable to find an **open issue** addressing the problem, open a [new one](https://github.com/janeczku/calibre-web/issues/new/choose). Be sure to include a **title** and **clear description**, as much relevant information as possible, the **issue form** helps you providing the right information. Deleting the form and just pasting the stack trace doesn't speed up fixing the problem. If your issue could be resolved, consider closing the issue.
If you're unable to find an **open issue** addressing the problem, open a [new one](https://github.com/janeczku/calibre-web/issues/new/choose). Be sure to include a **title** and **clear description**, as much relevant information as possible, the **issue form** helps you provide the right information. Deleting the form and just pasting the stack trace doesn't speed up fixing the problem. If your issue could be resolved, consider closing the issue.
### **Feature Request**
If there is a feature missing in Calibre-Web and you can't find a feature request in the [Issues](https://github.com/janeczku/calibre-web/issues) section, you could create a [feature request](https://github.com/janeczku/calibre-web/issues/new?assignees=&labels=&template=feature_request.md&title=).
We will not extend Calibre-Web with any more login abilities or add further files storages, or file syncing ability. Furthermore Calibre-Web is made for home usage for company in-house usage, so requests regarding any sorts of social interaction capability, payment routines, search engine or web site analytics integration will not be implemented.
We will not extend Calibre-Web with any more login abilities or add further files storages, or file syncing ability. Calibre-Web is made for home usage for company in-house usage, so requests regarding any sorts of social interaction capability, payment routines, search engine or website analytics integration will not be implemented.
### **Contributing code to Calibre-Web**
@@ -42,5 +42,5 @@ Open a new GitHub pull request with the patch. Ensure the PR description clearly
In case your code enhances features of Calibre-Web: Create your pull request for the development branch if your enhancement consists of more than some lines of code in a local section of Calibre-Webs code. This makes it easier to test it and check all implication before it's made public.
Please check if your code runs with python 3, python 2 is no longer supported. If possible and the feature is related to operating system functions, try to check it on Windows and Linux.
Calibre-Web is automatically tested on Linux in combination with python 3.8. The code for testing is in a [separate repo](https://github.com/OzzieIsaacs/calibre-web-test) on Github. It uses unit tests and performs real system tests with selenium; it would be great if you could consider also writing some tests.
Calibre-Web is automatically tested on Linux in combination with python 3.8. The code for testing is in a [separate repo](https://github.com/OzzieIsaacs/calibre-web-test) on GitHub. It uses unit tests and performs real system tests with selenium; it would be great if you could consider also writing some tests.
A static code analysis is done by Codacy, but it's partly broken and doesn't run automatically. You could check your code with ESLint before contributing, a configuration file can be found in the projects root folder.
+2
View File
@@ -1 +1,3 @@
graft src/calibreweb
global-exclude __pycache__
global-exclude *.pyc
+152 -74
View File
@@ -1,109 +1,187 @@
# About
# Calibre-Web
Calibre-Web is a web app providing a clean interface for browsing, reading and downloading eBooks using a valid [Calibre](https://calibre-ebook.com) database.
Calibre-Web is a web app that offers a clean and intuitive interface for browsing, reading, and downloading eBooks using a valid [Calibre](https://calibre-ebook.com) database.
[![GitHub License](https://img.shields.io/github/license/janeczku/calibre-web?style=flat-square)](https://github.com/janeczku/calibre-web/blob/master/LICENSE)
[![GitHub commit activity](https://img.shields.io/github/commit-activity/w/janeczku/calibre-web?logo=github&style=flat-square&label=commits)]()
[![GitHub all releases](https://img.shields.io/github/downloads/janeczku/calibre-web/total?logo=github&style=flat-square)](https://github.com/janeczku/calibre-web/releases)
[![License](https://img.shields.io/github/license/janeczku/calibre-web?style=flat-square)](https://github.com/janeczku/calibre-web/blob/master/LICENSE)
![Commit Activity](https://img.shields.io/github/commit-activity/w/janeczku/calibre-web?logo=github&style=flat-square&label=commits)
[![All Releases](https://img.shields.io/github/downloads/janeczku/calibre-web/total?logo=github&style=flat-square)](https://github.com/janeczku/calibre-web/releases)
[![PyPI](https://img.shields.io/pypi/v/calibreweb?logo=pypi&logoColor=fff&style=flat-square)](https://pypi.org/project/calibreweb/)
[![PyPI - Downloads](https://img.shields.io/pypi/dm/calibreweb?logo=pypi&logoColor=fff&style=flat-square)](https://pypi.org/project/calibreweb/)
[![Discord](https://img.shields.io/discord/838810113564344381?label=Discord&logo=discord&style=flat-square)](https://discord.gg/h2VsJ2NEfB)
<details>
<summary><strong>Table of Contents</strong> (click to expand)</summary>
1. [About](#calibre-web)
2. [Features](#features)
3. [Installation](#installation)
- [Installation via pip (recommended)](#installation-via-pip-recommended)
- [Quick start](#quick-start)
- [Requirements](#requirements)
4. [Docker Images](#docker-images)
5. [Troubleshooting](#troubleshooting)
6. [Contributor Recognition](#contributor-recognition)
7. [Contact](#contact)
8. [Contributing to Calibre-Web](#contributing-to-calibre-web)
</details>
*This software is a fork of [library](https://github.com/mutschler/calibreserver) and licensed under the GPL v3 License.*
![Main screen](https://github.com/janeczku/calibre-web/wiki/images/main_screen.png)
## Features
- Bootstrap 3 HTML5 interface
- full graphical setup
- User management with fine-grained per-user permissions
- Modern and responsive Bootstrap 3 HTML5 interface
- Full graphical setup
- Comprehensive user management with fine-grained per-user permissions
- Admin interface
- User Interface in brazilian, czech, dutch, english, finnish, french, galician, german, greek, hungarian, indonesian, italian, japanese, khmer, korean, norwegian, polish, russian, simplified and traditional chinese, spanish, swedish, turkish, ukrainian, vietnamese
- OPDS feed for eBook reader apps
- Filter and search by titles, authors, tags, series, book format and language
- Create a custom book collection (shelves)
- Support for editing eBook metadata and deleting eBooks from Calibre library
- Support for downloading eBook metadata from various sources, sources can be extended via external plugins
- Support for converting eBooks through Calibre binaries
- Restrict eBook download to logged-in users
- Support for public user registration
- Send eBooks to E-Readers with the click of a button
- Sync your Kobo devices through Calibre-Web with your Calibre library
- Support for reading eBooks directly in the browser (.txt, .epub, .pdf, .cbr, .cbt, .cbz, .djvu)
- Upload new books in many formats, including audio formats (.mp3, .m4a, .m4b)
- Support for Calibre Custom Columns
- Ability to hide content based on categories and Custom Column content per user
- Multilingual user interface supporting 20+ languages ([supported languages](https://github.com/janeczku/calibre-web/wiki/Translation-Status))
- OPDS feed for eBook reader apps
- Advanced search and filtering options
- Custom book collection (shelves) creation
- eBook metadata editing and deletion support
- Metadata download from various sources (extensible via plugins)
- eBook conversion through Calibre binaries
- eBook download restriction to logged-in users
- Public user registration support
- Send eBooks to E-Readers with a single click
- Sync Kobo devices with your Calibre library
- In-browser eBook reading support for multiple formats
- Upload new books in various formats, including audio formats
- Calibre Custom Columns support
- Content hiding based on categories and Custom Column content per user
- Self-update capability
- "Magic Link" login to make it easy to log on eReaders
- Login via LDAP, google/github oauth and via proxy authentication
- "Magic Link" login for easy access on eReaders
- LDAP, Google/GitHub OAuth, and proxy authentication support
## Installation
#### Installation via pip (recommended)
1. To avoid problems with already installed python dependencies, it's recommended to create a virtual environment for Calibre-Web
2. Install Calibre-Web via pip with the command `pip install calibreweb` (Depending on your OS and or distro the command could also be `pip3`).
3. Optional features can also be installed via pip, please refer to [this page](https://github.com/janeczku/calibre-web/wiki/Dependencies-in-Calibre-Web-Linux-and-Windows) for details
4. Calibre-Web can be started afterwards by typing `cps`
### Installation via pip (recommended)
Issues with Raspberry Pi - Raspberry Pi OS:
Depending on your version of pip it's possible that the installation fails with `Failed to build cryptography
ERROR: Could not build wheels for cryptography, which is required to install pyproject.toml-based projects`.
In this case please try to update pip with `./venv/bin/python3 -m pip install --upgrade pip` first, and then try installing Calibre-Web again.
If this isn't working please also install cargo via `sudo apt install cargo`, and try installing Calibre-Web again.
1. **Create a virtual environment**: It’s essential to isolate your Calibre-Web installation to avoid dependency conflicts. You can create a virtual environment by running:
```
python3 -m venv calibre-web-env
```
2. **Activate the virtual environment**:
```
source calibre-web-env/bin/activate
```
3. **Install Calibre-Web**: Use pip to install the application:
```
pip install calibreweb
```
4. **Install optional features**: For additional functionality, you may need to install optional features. Refer to [this page](https://github.com/janeczku/calibre-web/wiki/Dependencies-in-Calibre-Web-Linux-and-Windows) for details on what can be installed.
5. **Start Calibre-Web**: After installation, you can start the application with:
```
cps
```
In the Wiki there are also examples for: a [manual installation](https://github.com/janeczku/calibre-web/wiki/Manual-installation), [installation on Linux Mint](https://github.com/janeczku/calibre-web/wiki/How-To:Install-Calibre-Web-in-Linux-Mint-19-or-20), [installation on a Cloud Provider](https://github.com/janeczku/calibre-web/wiki/How-To:-Install-Calibre-Web-on-a-Cloud-Provider).
*Note: Users of Raspberry Pi OS may encounter installation issues. If you do, try upgrading pip and/or installing cargo as follows:*
```
./venv/bin/python3 -m pip install --upgrade pip
sudo apt install cargo
```
## Quick start
### Important Links
- For additional installation examples, check the following:
- [Manual installation](https://github.com/janeczku/calibre-web/wiki/Manual-installation)
- [Linux Mint installation](https://github.com/janeczku/calibre-web/wiki/How-To:-Install-Calibre-Web-in-Linux-Mint-19-or-20)
- [Cloud Provider setup](https://github.com/janeczku/calibre-web/wiki/How-To:-Install-Calibre-Web-on-a-Cloud-Provider)
Point your browser to `http://localhost:8083` or `http://localhost:8083/opds` for the OPDS catalog \
Login with default admin login \
If you don't have a Calibre database already, this [database](https://github.com/janeczku/calibre-web/blob/master/library/metadata.db) can be used. **IMPORTATNT** Please move the database out of the calibre-web folder structure, as it will be overwritten during update. \
Set `Location of Calibre database` to the path of the folder where your Calibre library (metadata.db) lives, push "submit" button. \
Optionally a Google Drive can be used to host the calibre library [-> Using Google Drive integration](https://github.com/janeczku/calibre-web/wiki/G-Drive-Setup#using-google-drive-integration) \
Afterwards you can configure your Calibre-Web instance ([Basic Configuration](https://github.com/janeczku/calibre-web/wiki/Configuration#basic-configuration) and [UI Configuration](https://github.com/janeczku/calibre-web/wiki/Configuration#ui-configuration) on admin page)
#### Default admin login:
*Username:* admin\
*Password:* admin123
## Quick Start
1. **Access Calibre-Web**: Open your browser and navigate to:
```
http://localhost:8083
```
or for the OPDS catalog:
```
http://localhost:8083/opds
```
2. **Log in**: Use the default admin credentials:
- **Username:** admin
- **Password:** admin123
3. **Database Setup**: If you do not have a Calibre database, download a sample from:
```
https://github.com/janeczku/calibre-web/raw/master/library/metadata.db
```
Move it out of the Calibre-Web folder to avoid overwriting during updates.
4. **Configure Calibre Database**: In the admin interface, set the `Location of Calibre database` to the path of the folder containing your Calibre library (where `metadata.db` is located) and click "Save".
5. **Google Drive Integration**: For hosting your Calibre library on Google Drive, refer to the [Google Drive integration guide](https://github.com/janeczku/calibre-web/wiki/G-Drive-Setup#using-google-drive-integration).
6. **Admin Configuration**: Configure your instance via the admin page, referring to the [Basic Configuration](https://github.com/janeczku/calibre-web/wiki/Configuration#basic-configuration) and [UI Configuration](https://github.com/janeczku/calibre-web/wiki/Configuration#ui-configuration) guides.
## Requirements
python 3.5+
[Download](https://imagemagick.org/script/download.php) Imagemagick to extract covers from epubs. On Windows the additional installation of [ghostscript](https://ghostscript.com/releases/gsdnld.html) might be necessary to extract covers from pdf files. On Linux Imagemagick and Ghostscript can often be installed using the system package manager.
Optionally, to enable on-the-fly conversion from one ebook format to another when using the send-to-ereader feature, or during editing of ebooks metadata:
[Download and install](https://calibre-ebook.com/download) the Calibre desktop program for your platform and enter the folder including program name (normally /opt/calibre/ebook-convert, or C:\Program Files\calibre\ebook-convert.exe) in the field "calibre's converter tool" on the setup page.
[Download](https://github.com/pgaskin/kepubify/releases/latest) Kepubify tool for your platform and place the binary starting with `kepubify` in Linux: `/opt/kepubify` Windows: `C:\Program Files\kepubify`.
- **Python Version**: Ensure you have Python 3.7 or newer.
- **Imagemagick**: Required for cover extraction from EPUBs. Windows users may also need to install [Ghostscript](https://ghostscript.com/releases/gsdnld.html) for PDF cover extraction.
- **Optional Tools**:
- **Calibre desktop program**: Recommended for on-the-fly conversion and metadata editing. Set the path to Calibre’s converter tool on the setup page.
- **Kepubify tool**: Needed for Kobo device support. Download the tool and place the binary in `/opt/kepubify` on Linux or `C:\Program Files\kepubify` on Windows.
## Docker Images
A pre-built Docker image is available in these Docker Hub repository (maintained by the LinuxServer team):
Pre-built Docker images are available:
#### **LinuxServer - x64, armhf, aarch64**
+ Docker Hub - [https://hub.docker.com/r/linuxserver/calibre-web](https://hub.docker.com/r/linuxserver/calibre-web)
+ Github - [https://github.com/linuxserver/docker-calibre-web](https://github.com/linuxserver/docker-calibre-web)
+ Github - (Optional Calibre layer) - [https://github.com/linuxserver/docker-calibre-web/tree/calibre](https://github.com/linuxserver/docker-calibre-web/tree/calibre)
### **LinuxServer - x64, aarch64**
- **Docker Hub**: [linuxserver/calibre-web](https://hub.docker.com/r/linuxserver/calibre-web)
- **GitHub**: [linuxserver/docker-calibre-web](https://github.com/linuxserver/docker-calibre-web)
- **Optional Calibre layer**: [linuxserver/docker-mods](https://github.com/linuxserver/docker-mods/tree/universal-calibre)
This image has the option to pull in an extra docker manifest layer to include the Calibre `ebook-convert` binary. Just include the environmental variable `DOCKER_MODS=linuxserver/calibre-web:calibre` in your docker run/docker compose file. **(x64 only)**
If you do not need this functionality then this can be omitted, keeping the image as lightweight as possible.
Both the Calibre-Web and Calibre-Mod images are rebuilt automatically on new releases of Calibre-Web and Calibre respectively, and on updates to any included base image packages on a weekly basis if required.
+ The "path to convertertool" should be set to `/usr/bin/ebook-convert`
+ The "path to unrar" should be set to `/usr/bin/unrar`
To include the Calibre `ebook-convert` binary (x64 only), add the environment variable:
```
DOCKER_MODS=linuxserver/mods:universal-calibre
```
in your Docker run/compose file. Omit this variable for a lightweight image.
# Contact
- **Paths Configuration**:
- Set **Path to Calibre Binaries** to `/usr/bin`.
- Set **Path to Unrar** to `/usr/bin/unrar`.
Just reach us out on [Discord](https://discord.gg/h2VsJ2NEfB)
## Troubleshooting
For further information, How To's and FAQ please check the [Wiki](https://github.com/janeczku/calibre-web/wiki)
- **Common Issues**:
- If you experience issues starting the application, check the log files located in the `logs` directory for error messages.
- If eBooks fail to load, verify that the `Location of Calibre database` is correctly set and that the database file is accessible.
- You need to enable uploads under `Basic settings` for this option to appear
# Contributing to Calibre-Web
- **Configuration Errors**: Ensure that your Calibre database is compatible and properly formatted. Refer to the Calibre documentation for guidance on maintaining the database.
Please have a look at our [Contributing Guidelines](https://github.com/janeczku/calibre-web/blob/master/CONTRIBUTING.md)
- **Performance Problems**:
- If the application is slow, consider increasing the allocated resources (CPU/RAM) to your server or optimizing the Calibre database by removing duplicates and unnecessary entries.
- Regularly clear the cache in your web browser to improve loading times.
- **User Management Issues**: If users are unable to log in or register, check the user permission settings in the admin interface. Ensure that registration is enabled and that users are being assigned appropriate roles.
- **Support Resources**: For additional help, consider visiting the [FAQ section](https://github.com/janeczku/calibre-web/wiki/FAQ) of the wiki or posting your questions in the [Discord community](https://discord.gg/h2VsJ2NEfB).
## Contributor Recognition
We would like to thank all the [contributors](https://github.com/janeczku/calibre-web/graphs/contributors) and maintainers of Calibre-Web for their valuable input and dedication to the project. Your contributions are greatly appreciated.
## Contact
Join us on [Discord](https://discord.gg/h2VsJ2NEfB)
For more information, How To's, and FAQs, please visit the [Wiki](https://github.com/janeczku/calibre-web/wiki)
## Contributing to Calibre-Web
To contribute, please check our [Contributing Guidelines](https://github.com/janeczku/calibre-web/blob/master/CONTRIBUTING.md). We welcome issues, feature requests, and pull requests from the community.
### Reporting Bugs
If you encounter bugs or issues, please report them in the [issues section](https://github.com/janeczku/calibre-web/issues) of the repository. Be sure to include detailed information about your setup and the problem encountered.
### Feature Requests
We welcome suggestions for new features. Please create a new issue in the repository to discuss your ideas.
## Additional Resources
- **Documentation**: Comprehensive documentation is available on the [Calibre-Web wiki](https://github.com/janeczku/calibre-web/wiki).
- **Community Contributions**: Explore the [community contributions](https://github.com/janeczku/calibre-web/pulls) to see ongoing work and how you can get involved.
---
Thank you for using Calibre-Web! We hope you enjoy managing your eBook library with our tool.
+40 -28
View File
@@ -10,34 +10,46 @@ To receive fixes for security vulnerabilities it is required to always upgrade t
## History
| Fixed in | Description |CVE number |
|---------------|--------------------------------------------------------------------------------------------------------------------|---------|
| 3rd July 2018 | Guest access acts as a backdoor ||
| V 0.6.7 | Hardcoded secret key for sessions |CVE-2020-12627 |
| V 0.6.13 | Calibre-Web Metadata cross site scripting |CVE-2021-25964|
| V 0.6.13 | Name of Shelves are only visible to users who can access the corresponding shelf Thanks to @ibarrionuevo ||
| V 0.6.13 | JavaScript could get executed in the description field. Thanks to @ranjit-git and Hagai Wechsler (WhiteSource) ||
| V 0.6.13 | JavaScript could get executed in a custom column of type "comment" field ||
| V 0.6.13 | JavaScript could get executed after converting a book to another format with a title containing javascript code ||
| V 0.6.13 | JavaScript could get executed after converting a book to another format with a username containing javascript code ||
| V 0.6.13 | JavaScript could get executed in the description series, categories or publishers title ||
| V 0.6.13 | JavaScript could get executed in the shelf title ||
| V 0.6.13 | Login with the old session cookie after logout. Thanks to @ibarrionuevo ||
| V 0.6.14 | CSRF was possible. Thanks to @mik317 and Hagai Wechsler (WhiteSource) |CVE-2021-25965|
| V 0.6.14 | Migrated some routes to POST-requests (CSRF protection). Thanks to @scara31 |CVE-2021-4164|
| V 0.6.15 | Fix for "javascript:" script links in identifier. Thanks to @scara31 |CVE-2021-4170|
| V 0.6.15 | Cross-Site Scripting vulnerability on uploaded cover file names. Thanks to @ibarrionuevo ||
| V 0.6.15 | Creating public shelfs is now denied if user is missing the edit public shelf right. Thanks to @ibarrionuevo ||
| V 0.6.15 | Changed error message in case of trying to delete a shelf unauthorized. Thanks to @ibarrionuevo ||
| V 0.6.16 | JavaScript could get executed on authors page. Thanks to @alicaz |CVE-2022-0352|
| V 0.6.16 | Localhost can no longer be used to upload covers. Thanks to @scara31 |CVE-2022-0339|
| V 0.6.16 | Another case where public shelfs could be created without permission is prevented. Thanks to @nhiephon |CVE-2022-0273|
| V 0.6.16 | It's prevented to get the name of a private shelfs. Thanks to @nhiephon |CVE-2022-0405|
| V 0.6.17 | The SSRF Protection can no longer be bypassed via an HTTP redirect. Thanks to @416e6e61 |CVE-2022-0767|
| V 0.6.17 | The SSRF Protection can no longer be bypassed via 0.0.0.0 and it's ipv6 equivalent. Thanks to @r0hanSH |CVE-2022-0766|
| V 0.6.18 | Possible SQL Injection is prevented in user table Thanks to Iman Sharafaldin (Forward Security) |CVE-2022-30765|
| V 0.6.18 | The SSRF protection no longer can be bypassed by IPV6/IPV4 embedding. Thanks to @416e6e61 |CVE-2022-0939|
| V 0.6.18 | The SSRF protection no longer can be bypassed to connect to other servers in the local network. Thanks to @michaellrowley |CVE-2022-0990|
| Fixed in | Description | CVE number |
|---------------|----------------------------------------------------------------------------------------------------------------------------------|----------------|
| 3rd July 2018 | Guest access acts as a backdoor | |
| V 0.6.7 | Hardcoded secret key for sessions | CVE-2020-12627 |
| V 0.6.13 | Calibre-Web Metadata cross site scripting | CVE-2021-25964 |
| V 0.6.13 | Name of Shelves are only visible to users who can access the corresponding shelf Thanks to @ibarrionuevo | |
| V 0.6.13 | JavaScript could get executed in the description field. Thanks to @ranjit-git and Hagai Wechsler (WhiteSource) | |
| V 0.6.13 | JavaScript could get executed in a custom column of type "comment" field | |
| V 0.6.13 | JavaScript could get executed after converting a book to another format with a title containing javascript code | |
| V 0.6.13 | JavaScript could get executed after converting a book to another format with a username containing javascript code | |
| V 0.6.13 | JavaScript could get executed in the description series, categories or publishers title | |
| V 0.6.13 | JavaScript could get executed in the shelf title | |
| V 0.6.13 | Login with the old session cookie after logout. Thanks to @ibarrionuevo | |
| V 0.6.14 | CSRF was possible. Thanks to @mik317 and Hagai Wechsler (WhiteSource) | CVE-2021-25965 |
| V 0.6.14 | Migrated some routes to POST-requests (CSRF protection). Thanks to @scara31 | CVE-2021-4164 |
| V 0.6.15 | Fix for "javascript:" script links in identifier. Thanks to @scara31 | CVE-2021-4170 |
| V 0.6.15 | Cross-Site Scripting vulnerability on uploaded cover file names. Thanks to @ibarrionuevo | |
| V 0.6.15 | Creating public shelfs is now denied if user is missing the edit public shelf right. Thanks to @ibarrionuevo | |
| V 0.6.15 | Changed error message in case of trying to delete a shelf unauthorized. Thanks to @ibarrionuevo | |
| V 0.6.16 | JavaScript could get executed on authors page. Thanks to @alicaz | CVE-2022-0352 |
| V 0.6.16 | Localhost can no longer be used to upload covers. Thanks to @scara31 | CVE-2022-0339 |
| V 0.6.16 | Another case where public shelfs could be created without permission is prevented. Thanks to @nhiephon | CVE-2022-0273 |
| V 0.6.16 | It's prevented to get the name of a private shelfs. Thanks to @nhiephon | CVE-2022-0405 |
| V 0.6.17 | The SSRF Protection can no longer be bypassed via an HTTP redirect. Thanks to @416e6e61 | CVE-2022-0767 |
| V 0.6.17 | The SSRF Protection can no longer be bypassed via 0.0.0.0 and it's ipv6 equivalent. Thanks to @r0hanSH | CVE-2022-0766 |
| V 0.6.18 | Possible SQL Injection is prevented in user table Thanks to Iman Sharafaldin (Forward Security) | CVE-2022-30765 |
| V 0.6.18 | The SSRF protection no longer can be bypassed by IPV6/IPV4 embedding. Thanks to @416e6e61 | CVE-2022-0939 |
| V 0.6.18 | The SSRF protection no longer can be bypassed to connect to other servers in the local network. Thanks to @michaellrowley | CVE-2022-0990 |
| V 0.6.20 | Credentials for emails are now stored encrypted | |
| V 0.6.20 | Login is rate limited | |
| V 0.6.20 | Passwordstrength can be forced | |
| V 0.6.21 | SMTP server credentials are no longer returned to client | |
| V 0.6.21 | Cross-site scripting (XSS) stored in href bypasses filter using data wrapper no longer possible | |
| V 0.6.21 | Cross-site scripting (XSS) is no longer possible via pathchooser | |
| V 0.6.21 | Error Handling at non existent rating, language, and user downloaded books was fixed | |
| V 0.6.22 | Upload mimetype is checked to prevent malicious file content in the books library | |
| V 0.6.22 | Cross-site scripting (XSS) stored in comments section is prevented better (switching from lxml to bleach for sanitizing strings) | |
| V 0.6.23 | Cookies are no longer stored for opds basic authentication and proxy authentication | |
## Statement regarding Log4j (CVE-2021-44228 and related)
+34 -1
View File
@@ -27,8 +27,41 @@ sys.path.insert(0, path)
from cps.main import main
def hide_console_windows():
import ctypes
kernel32 = ctypes.WinDLL('kernel32')
user32 = ctypes.WinDLL('user32')
SW_HIDE = 0
hWnd = kernel32.GetConsoleWindow()
if hWnd:
user32.ShowWindow(hWnd, SW_HIDE)
if __name__ == '__main__':
main()
# Only hide the console window on Windows when there is no interactive
# console attached. This preserves the ability to use Ctrl+C from a
# terminal (stdin is a tty) to stop the server.
if os.name == "nt" and not sys.stdin.isatty():
hide_console_windows()
try:
main()
except KeyboardInterrupt:
# Allow stopping the server with Ctrl+C from an interactive console, after reboot of calibre-web
# (initally the SIGINT signal CTRL+C is catched in server.py via the signal callback).
try:
# Try to perform a graceful stop if web_server is available.
# Import here to avoid import-time side-effects when not needed.
from cps import web_server
web_server.stop()
except Exception:
pass
print('\nCalibre-Web: received interrupt, shutting down')
sys.exit(0)
+7 -22
View File
@@ -20,33 +20,18 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from .cw_login import LoginManager
from flask import session
from flask_login import LoginManager, confirm_login
from flask import session, current_app
from flask_login.utils import decode_cookie
from flask_login.signals import user_loaded_from_cookie
class MyLoginManager(LoginManager):
def _session_protection_failed(self):
_session = session._get_current_object()
sess = session._get_current_object()
ident = self._session_identifier_generator()
if(_session and not (len(_session) == 1
and _session.get('csrf_token', None))) and ident != _session.get('_id', None):
if(sess and not (len(sess) == 1
and sess.get('csrf_token', None))) and ident != sess.get('_id', None):
return super(). _session_protection_failed()
return False
def _load_user_from_remember_cookie(self, cookie):
user_id = decode_cookie(cookie)
if user_id is not None:
session["_user_id"] = user_id
session["_fresh"] = False
user = None
if self._user_callback:
user = self._user_callback(user_id)
if user is not None:
app = current_app._get_current_object()
user_loaded_from_cookie.send(app, user=user)
# if session was restored from remember me cookie make login valid
confirm_login()
return user
return None
+58 -39
View File
@@ -26,17 +26,16 @@ import os
import mimetypes
from flask import Flask
from flask.sessions import SecureCookieSessionInterface
from .MyLoginManager import MyLoginManager
from flask_principal import Principal
from . import logger
from .cli import CliParameter
from .constants import CONFIG_DIR
from .reverseproxy import ReverseProxied
from .server import WebServer
from .dep_check import dependency_check
from .updater import Updater
from .babel import babel, get_locale
from . import config_sql
from . import cache_buster
from . import ub, db
@@ -56,23 +55,31 @@ except ImportError:
mimetypes.init()
mimetypes.add_type('application/xhtml+xml', '.xhtml')
mimetypes.add_type('application/epub+zip', '.epub')
mimetypes.add_type('application/epub+zip', '.kepub')
mimetypes.add_type('application/fb2+zip', '.fb2')
mimetypes.add_type('application/x-mobipocket-ebook', '.mobi')
mimetypes.add_type('application/x-mobipocket-ebook', '.prc')
mimetypes.add_type('application/vnd.amazon.ebook', '.azw')
mimetypes.add_type('application/x-mobi8-ebook', '.azw3')
mimetypes.add_type('application/octet-stream', '.prc')
mimetypes.add_type('application/x-mobipocket-ebook', '.azw')
mimetypes.add_type('application/x-mobipocket-ebook', '.azw3')
mimetypes.add_type('application/x-cbr', '.cbr')
mimetypes.add_type('application/x-cbz', '.cbz')
mimetypes.add_type('application/x-cbt', '.cbt')
mimetypes.add_type('application/x-tar', '.cbt')
mimetypes.add_type('application/x-7z-compressed', '.cb7')
mimetypes.add_type('image/vnd.djvu', '.djv')
mimetypes.add_type('image/vnd.djvu', '.djvu')
mimetypes.add_type('application/mpeg', '.mpeg')
mimetypes.add_type('application/mpeg', '.mp3')
mimetypes.add_type('application/mp4', '.m4a')
mimetypes.add_type('application/mp4', '.m4b')
mimetypes.add_type('application/ogg', '.ogg')
mimetypes.add_type('audio/mpeg', '.mp3')
mimetypes.add_type('audio/x-m4a', '.m4a')
mimetypes.add_type('audio/x-m4a', '.m4b')
mimetypes.add_type('audio/x-hx-aac-adts', '.aac')
mimetypes.add_type('audio/vnd.dolby.dd-raw', '.ac3')
mimetypes.add_type('video/x-ms-asf', '.asf')
mimetypes.add_type('audio/ogg', '.ogg')
mimetypes.add_type('application/ogg', '.oga')
mimetypes.add_type('text/css', '.css')
mimetypes.add_type('text/javascript; charset=UTF-8', '.js')
mimetypes.add_type('application/x-ms-reader', '.lit')
mimetypes.add_type('text/javascript', '.js')
mimetypes.add_type('text/rtf', '.rtf')
log = logger.create()
@@ -80,33 +87,43 @@ app = Flask(__name__)
app.config.update(
SESSION_COOKIE_HTTPONLY=True,
SESSION_COOKIE_SAMESITE='Lax',
REMEMBER_COOKIE_SAMESITE='Lax', # will be available in flask-login 0.5.1 earliest
WTF_CSRF_SSL_STRICT=False
REMEMBER_COOKIE_SAMESITE='Strict',
WTF_CSRF_SSL_STRICT=False,
SESSION_COOKIE_NAME=os.environ.get('COOKIE_PREFIX', "") + "session",
REMEMBER_COOKIE_NAME=os.environ.get('COOKIE_PREFIX', "") + "remember_token"
)
lm = MyLoginManager()
config = config_sql.ConfigSQL()
cli_param = CliParameter()
config = config_sql.ConfigSQL()
if wtf_present:
csrf = CSRFProtect()
else:
csrf = None
calibre_db = db.CalibreDB()
calibre_db = db.CalibreDB(app)
web_server = WebServer()
updater_thread = Updater()
if limiter_present:
limiter = Limiter(key_func=True, headers_enabled=True, auto_check=False, swallow_errors=True)
limiter = Limiter(key_func=True, headers_enabled=True, in_memory_fallback_enabled=True, default_limits=[],
swallow_errors=True)
else:
limiter = None
class ScriptNameSessionInterface(SecureCookieSessionInterface):
def get_cookie_path(self, app):
# Called once per response, after request context exists
return app.wsgi_app.script_name.rstrip("/") or "/"
def create_app():
app.session_interface = ScriptNameSessionInterface()
if csrf:
csrf.init_app(app)
@@ -124,13 +141,6 @@ def create_app():
ub.password_change(cli_param.user_credentials)
if not limiter:
log.info('*** "flask-limiter" is needed for calibre-web to run. '
'Please install it using pip: "pip install flask-limiter" ***')
print('*** "flask-limiter" is needed for calibre-web to run. '
'Please install it using pip: "pip install flask-limiter" ***')
web_server.stop(True)
sys.exit(8)
if sys.version_info < (3, 0):
log.info(
'*** Python2 is EOL since end of 2019, this version of Calibre-Web is no longer supporting Python2, '
@@ -140,30 +150,29 @@ def create_app():
'please update your installation to Python3 ***')
web_server.stop(True)
sys.exit(5)
if not wtf_present:
log.info('*** "flask-WTF" is needed for calibre-web to run. '
'Please install it using pip: "pip install flask-WTF" ***')
print('*** "flask-WTF" is needed for calibre-web to run. '
'Please install it using pip: "pip install flask-WTF" ***')
web_server.stop(True)
sys.exit(7)
lm.login_view = 'web.login'
lm.anonymous_user = ub.Anonymous
lm.session_protection = 'strong' if config.config_session == 1 else "basic"
db.CalibreDB.update_config(config)
db.CalibreDB.setup_db(config.config_calibre_dir, cli_param.settings_path)
calibre_db.init_db()
db.CalibreDB.update_config(config, config.config_calibre_dir, cli_param.settings_path)
updater_thread.init_updater(config, web_server)
# Perform dry run of updater and exit afterwards
# Perform dry run of updater and exit afterward
if cli_param.dry_run:
updater_thread.dry_run()
sys.exit(0)
updater_thread.start()
for res in dependency_check() + dependency_check(True):
requirements = dependency_check()
for res in requirements:
if res['found'] == "not installed":
message = ('Cannot import {name} module, it is needed to run calibre-web, '
'please install it using "pip install {name}"').format(name=res["name"])
log.info(message)
print("*** " + message + " ***")
web_server.stop(True)
sys.exit(8)
for res in requirements + dependency_check(True):
log.info('*** "{}" version does not meet the requirements. '
'Should: {}, Found: {}, please consider installing required version ***'
.format(res['name'],
@@ -179,6 +188,7 @@ def create_app():
app.secret_key = os.getenv('SECRET_KEY', config_sql.get_flask_session_key(ub.session))
web_server.init_app(app, config)
from .cw_babel import babel, get_locale
if hasattr(babel, "localeselector"):
babel.init_app(app)
babel.localeselector(get_locale)
@@ -191,12 +201,21 @@ def create_app():
services.ldap.init_app(app, config)
if services.goodreads_support:
services.goodreads_support.connect(config.config_goodreads_api_key,
config.config_goodreads_api_secret_e,
config.config_use_goodreads)
config.store_calibre_uuid(calibre_db, db.Library_Id)
# Configure rate limiter
# https://limits.readthedocs.io/en/stable/storage.html
app.config.update(RATELIMIT_ENABLED=config.config_ratelimiter)
limiter.init_app(app)
if config.config_limiter_uri != "" and not cli_param.memory_backend:
app.config.update(RATELIMIT_STORAGE_URI=config.config_limiter_uri)
if config.config_limiter_options != "":
app.config.update(RATELIMIT_STORAGE_OPTIONS=config.config_limiter_options)
try:
limiter.init_app(app)
except Exception as e:
log.error('Wrong Flask Limiter configuration, falling back to default: {}'.format(e))
app.config.update(RATELIMIT_STORAGE_URI=None)
limiter.init_app(app)
# Register scheduled tasks
from .schedule import register_scheduled_tasks, register_startup_tasks
+8 -7
View File
@@ -23,15 +23,15 @@
import sys
import platform
import sqlite3
from importlib.metadata import metadata
from collections import OrderedDict
import flask
import flask_login
import jinja2
from flask_babel import gettext as _
from . import db, calibre_db, converter, uploader, constants, dep_check
from .render_template import render_title_template
from .usermanagement import user_login_required
about = flask.Blueprint('about', __name__)
@@ -41,17 +41,18 @@ req = dep_check.load_dependencies(False)
opt = dep_check.load_dependencies(True)
for i in (req + opt):
modules[i[1]] = i[0]
modules['Jinja2'] = jinja2.__version__
modules['pySqlite'] = sqlite3.version
modules['Jinja2'] = metadata("jinja2")["Version"]
if sys.version_info < (3, 12):
modules['pySqlite'] = sqlite3.version
modules['SQLite'] = sqlite3.sqlite_version
sorted_modules = OrderedDict((sorted(modules.items(), key=lambda x: x[0].casefold())))
def collect_stats():
if constants.NIGHTLY_VERSION[0] == "$Format:%H$":
calibre_web_version = constants.STABLE_VERSION['version']
calibre_web_version = constants.STABLE_VERSION.replace("b", " Beta")
else:
calibre_web_version = (constants.STABLE_VERSION['version'] + ' - '
calibre_web_version = (constants.STABLE_VERSION.replace("b", " Beta") + ' - '
+ constants.NIGHTLY_VERSION[0].replace('%', '%%') + ' - '
+ constants.NIGHTLY_VERSION[1].replace('%', '%%'))
@@ -74,7 +75,7 @@ def collect_stats():
@about.route("/stats")
@flask_login.login_required
@user_login_required
def stats():
counter = calibre_db.session.query(db.Books).count()
authors = calibre_db.session.query(db.Authors).count()
+195 -131
View File
@@ -32,14 +32,15 @@ from datetime import time as datetime_time
from functools import wraps
from urllib.parse import urlparse
from flask import Blueprint, flash, redirect, url_for, abort, request, make_response, send_from_directory, g, Response
from flask_login import login_required, current_user, logout_user
from flask import Blueprint, flash, redirect, url_for, abort, request, make_response, \
send_from_directory, g, jsonify
from markupsafe import Markup
from .cw_login import current_user
from flask_babel import gettext as _
from flask_babel import get_locale, format_time, format_datetime, format_timedelta
from flask import session as flask_session
from sqlalchemy import and_
from sqlalchemy.orm.attributes import flag_modified
from sqlalchemy.exc import IntegrityError, OperationalError, InvalidRequestError
from sqlalchemy.exc import IntegrityError, OperationalError, InvalidRequestError, ArgumentError
from sqlalchemy.sql.expression import func, or_, text
from . import constants, logger, helper, services, cli_param
@@ -47,11 +48,14 @@ from . import db, calibre_db, ub, web_server, config, updater_thread, gdriveutil
kobo_sync_status, schedule
from .helper import check_valid_domain, send_test_mail, reset_password, generate_password_hash, check_email, \
valid_email, check_username
from .embed_helper import get_calibre_binarypath
from .gdriveutils import is_gdrive_ready, gdrive_support
from .render_template import render_title_template, get_sidebar_config
from .services.worker import WorkerThread
from .babel import get_available_translations, get_available_locale, get_user_locale_language
from .usermanagement import user_login_required
from .cw_babel import get_available_translations, get_available_locale, get_user_locale_language
from . import debug_info
from .string_helper import strip_whitespaces
log = logger.create()
@@ -101,16 +105,21 @@ def admin_required(f):
@admi.before_app_request
def before_request():
if not ub.check_user_session(current_user.id, flask_session.get('_id')) and 'opds' not in request.path:
logout_user()
#try:
#if not ub.check_user_session(current_user.id,
# flask_session.get('_id')) and 'opds' not in request.path \
# and config.config_session == 1:
# logout_user()
#except AttributeError:
# pass # ? fails on requesting /ajax/emailstat during restart ?
g.constants = constants
g.google_site_verification = os.getenv('GOOGLE_SITE_VERIFICATION','')
g.google_site_verification = os.getenv('GOOGLE_SITE_VERIFICATION', '')
g.allow_registration = config.config_public_reg
g.allow_anonymous = config.config_anonbrowse
g.allow_upload = config.config_uploading
g.current_theme = config.config_theme
g.config_authors_max = config.config_authors_max
if '/static/' not in request.path and not config.db_configured and \
if ('/static/' not in request.path and not config.db_configured and
request.endpoint not in ('admin.ajax_db_config',
'admin.simulatedbchange',
'admin.db_configuration',
@@ -118,25 +127,24 @@ def before_request():
'web.login_post',
'web.logout',
'admin.load_dialogtexts',
'admin.ajax_pathchooser'):
'admin.ajax_pathchooser')):
return redirect(url_for('admin.db_configuration'))
@admi.route("/admin")
@login_required
def admin_forbidden():
abort(403)
#@admi.route("/admin")
#@user_login_required
#def admin_forbidden():
# abort(403)
@admi.route("/shutdown", methods=["POST"])
@login_required
@user_login_required
@admin_required
def shutdown():
task = request.get_json().get('parameter', -1)
show_text = {}
if task in (0, 1): # valid commandos received
# close all database connections
calibre_db.dispose()
ub.dispose()
if task == 0:
@@ -158,7 +166,7 @@ def shutdown():
@admi.route("/metadata_backup", methods=["POST"])
@login_required
@user_login_required
@admin_required
def queue_metadata_backup():
show_text = {}
@@ -181,8 +189,8 @@ def reconnect():
@admi.route("/ajax/updateThumbnails", methods=['POST'])
@user_login_required
@admin_required
@login_required
def update_thumbnails():
content = config.get_scheduled_task_settings()
if content['schedule_generate_book_covers']:
@@ -192,7 +200,7 @@ def update_thumbnails():
@admi.route("/admin/view")
@login_required
@user_login_required
@admin_required
def admin():
version = updater_thread.get_current_version_info()
@@ -211,7 +219,7 @@ def admin():
form_date += timedelta(hours=int(commit[20:22]), minutes=int(commit[23:]))
commit = format_datetime(form_date - tz, format='short')
else:
commit = version['version']
commit = version['version'].replace("b", " Beta")
all_user = ub.session.query(ub.User).all()
# email_settings = mail_config.get_mail_settings()
@@ -226,7 +234,7 @@ def admin():
@admi.route("/admin/dbconfig", methods=["GET", "POST"])
@login_required
@user_login_required
@admin_required
def db_configuration():
if request.method == "POST":
@@ -235,7 +243,7 @@ def db_configuration():
@admi.route("/admin/config", methods=["GET"])
@login_required
@user_login_required
@admin_required
def configuration():
return render_title_template("config_edit.html",
@@ -246,28 +254,28 @@ def configuration():
@admi.route("/admin/ajaxconfig", methods=["POST"])
@login_required
@user_login_required
@admin_required
def ajax_config():
return _configuration_update_helper()
@admi.route("/admin/ajaxdbconfig", methods=["POST"])
@login_required
@user_login_required
@admin_required
def ajax_db_config():
return _db_configuration_update_helper()
@admi.route("/admin/alive", methods=["GET"])
@login_required
@user_login_required
@admin_required
def calibreweb_alive():
return "", 200
@admi.route("/admin/viewconfig")
@login_required
@user_login_required
@admin_required
def view_configuration():
read_column = calibre_db.session.query(db.CustomColumns) \
@@ -284,7 +292,7 @@ def view_configuration():
@admi.route("/admin/usertable")
@login_required
@user_login_required
@admin_required
def edit_user_table():
visibility = current_user.view_settings.get('useredit', {})
@@ -298,7 +306,15 @@ def edit_user_table():
.group_by(text('books_tags_link.tag')) \
.order_by(db.Tags.name).all()
if config.config_restricted_column:
custom_values = calibre_db.session.query(db.cc_classes[config.config_restricted_column]).all()
try:
custom_values = calibre_db.session.query(db.cc_classes[config.config_restricted_column]).all()
except (KeyError, AttributeError, IndexError):
custom_values = []
log.error("Custom Column No.{} does not exist in calibre database".format(
config.config_restricted_column))
flash(_("Custom Column No.%(column)d does not exist in calibre database",
column=config.config_restricted_column),
category="error")
else:
custom_values = []
if not config.config_anonbrowse:
@@ -319,7 +335,7 @@ def edit_user_table():
@admi.route("/ajax/listusers")
@login_required
@user_login_required
@admin_required
def list_users():
off = int(request.args.get("offset") or 0)
@@ -333,8 +349,9 @@ def list_users():
if sort not in ub.User.__table__.columns.keys():
sort = "id"
order = request.args.get("order", "").lower()
if sort != "state" and order:
if not order in ["asc", "desc"]:
order = "asc"
order = text(sort + " " + order)
elif not state:
order = ub.User.id.asc()
@@ -363,29 +380,25 @@ def list_users():
user.default = get_user_locale_language(user.default_language)
table_entries = {'totalNotFiltered': total_count, 'total': filtered_count, "rows": users}
js_list = json.dumps(table_entries, cls=db.AlchemyEncoder)
response = make_response(js_list)
response.headers["Content-Type"] = "application/json; charset=utf-8"
return response
return make_response(json.dumps(table_entries, cls=db.AlchemyEncoder))
@admi.route("/ajax/deleteuser", methods=['POST'])
@login_required
@user_login_required
@admin_required
def delete_user():
user_ids = request.form.to_dict(flat=False)
users = None
user_ids = request.get_json().get("userid")
message = ""
if "userid[]" in user_ids:
users = ub.session.query(ub.User).filter(ub.User.id.in_(user_ids['userid[]'])).all()
elif "userid" in user_ids:
users = ub.session.query(ub.User).filter(ub.User.id == user_ids['userid'][0]).all()
try:
users = ub.session.query(ub.User).filter(ub.User.id.in_(user_ids)).all()
except (ArgumentError):
users = None
count = 0
errors = list()
success = list()
if not users:
log.error("User not found")
return Response(json.dumps({'type': "danger", 'message': _("User not found")}), mimetype='application/json')
return make_response(jsonify(type="danger", message=_("User not found")))
for user in users:
try:
message = _delete_user(user)
@@ -395,17 +408,17 @@ def delete_user():
errors.append({'type': "danger", 'message': str(ex)})
if count == 1:
log.info("User {} deleted".format(user_ids))
log.info("User {} deleted".format(user_ids[0]))
success = [{'type': "success", 'message': message}]
elif count > 1:
log.info("Users {} deleted".format(user_ids))
log.info("Users {} deleted".format(", ".join([str(user_id) for user_id in user_ids])))
success = [{'type': "success", 'message': _("{} users deleted successfully").format(count)}]
success.extend(errors)
return Response(json.dumps(success), mimetype='application/json')
return make_response(jsonify(success))
@admi.route("/ajax/getlocale")
@login_required
@user_login_required
@admin_required
def table_get_locale():
locale = get_available_locale()
@@ -413,11 +426,11 @@ def table_get_locale():
current_locale = get_locale()
for loc in locale:
ret.append({'value': str(loc), 'text': loc.get_language_name(current_locale)})
return json.dumps(ret)
return json.dumps(sorted(ret, key=lambda x: x['text']))
@admi.route("/ajax/getdefaultlanguage")
@login_required
@user_login_required
@admin_required
def table_get_default_lang():
languages = calibre_db.speaking_language()
@@ -425,11 +438,11 @@ def table_get_default_lang():
ret.append({'value': 'all', 'text': _('Show All')})
for lang in languages:
ret.append({'value': lang.lang_code, 'text': lang.name})
return json.dumps(ret)
return json.dumps(sorted(ret, key=lambda x: x['text']))
@admi.route("/ajax/editlistusers/<param>", methods=['POST'])
@login_required
@user_login_required
@admin_required
def edit_list_user(param):
vals = request.form.to_dict(flat=False)
@@ -456,9 +469,9 @@ def edit_list_user(param):
if 'value[]' in vals:
setattr(user, param, prepare_tags(user, vals['action'][0], param, vals['value[]']))
else:
setattr(user, param, vals['value'].strip())
setattr(user, param, strip_whitespaces(vals['value']))
else:
vals['value'] = vals['value'].strip()
vals['value'] = strip_whitespaces(vals['value'])
if param == 'name':
if user.name == "Guest":
raise Exception(_("Guest Name can't be changed"))
@@ -472,7 +485,7 @@ def edit_list_user(param):
elif param.endswith('role'):
value = int(vals['field_index'])
if user.name == "Guest" and value in \
[constants.ROLE_ADMIN, constants.ROLE_PASSWD, constants.ROLE_EDIT_SHELFS]:
[constants.ROLE_ADMIN, constants.ROLE_PASSWD, constants.ROLE_EDIT_SHELFS]:
raise Exception(_("Guest can't have this role"))
# check for valid value, last on checks for power of 2 value
if value > 0 and value <= constants.ROLE_VIEWER and (value & value - 1 == 0 or value == 1):
@@ -483,10 +496,10 @@ def edit_list_user(param):
if not ub.session.query(ub.User). \
filter(ub.User.role.op('&')(constants.ROLE_ADMIN) == constants.ROLE_ADMIN,
ub.User.id != user.id).count():
return Response(
json.dumps([{'type': "danger",
return make_response(
jsonify([{'type': "danger",
'message': _("No admin user remaining, can't remove admin role",
nick=user.name)}]), mimetype='application/json')
nick=user.name)}]))
user.role &= ~value
else:
raise Exception(_("Value has to be true or false"))
@@ -534,7 +547,7 @@ def edit_list_user(param):
@admi.route("/ajax/user_table_settings", methods=['POST'])
@login_required
@user_login_required
@admin_required
def update_table_settings():
current_user.view_settings['useredit'] = json.loads(request.data)
@@ -551,7 +564,7 @@ def update_table_settings():
@admi.route("/admin/viewconfig", methods=["POST"])
@login_required
@user_login_required
@admin_required
def update_view_configuration():
to_save = request.form.to_dict()
@@ -559,7 +572,7 @@ def update_view_configuration():
_config_string(to_save, "config_calibre_web_title")
_config_string(to_save, "config_columns_to_ignore")
if _config_string(to_save, "config_title_regex"):
calibre_db.update_title_sort(config)
calibre_db.create_functions(config)
if not check_valid_read_column(to_save.get("config_read_column", "0")):
flash(_("Invalid Read Column"), category="error")
@@ -596,7 +609,7 @@ def update_view_configuration():
@admi.route("/ajax/loaddialogtexts/<element_id>", methods=['POST'])
@login_required
@user_login_required
def load_dialogtexts(element_id):
texts = {"header": "", "main": "", "valid": 1}
if element_id == "config_delete_kobo_token":
@@ -605,6 +618,8 @@ def load_dialogtexts(element_id):
texts["main"] = _('Do you really want to delete this domain?')
elif element_id == "btndeluser":
texts["main"] = _('Do you really want to delete this user?')
elif element_id == "btndelbook":
texts["main"] = _('Do you really want to delete this book?')
elif element_id == "delete_shelf":
texts["main"] = _('Are you sure you want to delete this shelf?')
elif element_id == "select_locale":
@@ -613,6 +628,10 @@ def load_dialogtexts(element_id):
texts["main"] = _('Are you sure you want to change visible book languages for selected user(s)?')
elif element_id == "role":
texts["main"] = _('Are you sure you want to change the selected role for the selected user(s)?')
elif element_id == "archive_books":
texts["main"] = _('Are you sure you want to change the archive status for the selected book(s)?')
elif element_id == "read_books":
texts["main"] = _('Are you sure you want to change the read status for the selected book(s)?')
elif element_id == "restrictions":
texts["main"] = _('Are you sure you want to change the selected restrictions for the selected user(s)?')
elif element_id == "sidebar_view":
@@ -632,7 +651,7 @@ def load_dialogtexts(element_id):
@admi.route("/ajax/editdomain/<int:allow>", methods=['POST'])
@login_required
@user_login_required
@admin_required
def edit_domain(allow):
# POST /post
@@ -646,7 +665,7 @@ def edit_domain(allow):
@admi.route("/ajax/adddomain/<int:allow>", methods=['POST'])
@login_required
@user_login_required
@admin_required
def add_domain(allow):
domain_name = request.form.to_dict()['domainname'].replace('*', '%').replace('?', '_').lower()
@@ -660,7 +679,7 @@ def add_domain(allow):
@admi.route("/ajax/deletedomain", methods=['POST'])
@login_required
@user_login_required
@admin_required
def delete_domain():
try:
@@ -678,12 +697,12 @@ def delete_domain():
@admi.route("/ajax/domainlist/<int:allow>")
@login_required
@user_login_required
@admin_required
def list_domain(allow):
answer = ub.session.query(ub.Registration).filter(ub.Registration.allow == allow).all()
json_dumps = json.dumps([{"domain": r.domain.replace('%', '*').replace('_', '?'), "id": r.id} for r in answer])
js = json.dumps(json_dumps.replace('"', "'")).lstrip('"').strip('"')
js = json.dumps(json_dumps.replace('"', "'")).strip('"')
response = make_response(js.replace("'", '"'))
response.headers["Content-Type"] = "application/json; charset=utf-8"
return response
@@ -691,7 +710,7 @@ def list_domain(allow):
@admi.route("/ajax/editrestriction/<int:res_type>", defaults={"user_id": 0}, methods=['POST'])
@admi.route("/ajax/editrestriction/<int:res_type>/<int:user_id>", methods=['POST'])
@login_required
@user_login_required
@admin_required
def edit_restriction(res_type, user_id):
element = request.form.to_dict()
@@ -757,14 +776,14 @@ def edit_restriction(res_type, user_id):
@admi.route("/ajax/addrestriction/<int:res_type>", methods=['POST'])
@login_required
@user_login_required
@admin_required
def add_user_0_restriction(res_type):
return add_restriction(res_type, 0)
@admi.route("/ajax/addrestriction/<int:res_type>/<int:user_id>", methods=['POST'])
@login_required
@user_login_required
@admin_required
def add_restriction(res_type, user_id):
element = request.form.to_dict()
@@ -810,14 +829,14 @@ def add_restriction(res_type, user_id):
@admi.route("/ajax/deleterestriction/<int:res_type>", methods=['POST'])
@login_required
@user_login_required
@admin_required
def delete_user_0_restriction(res_type):
return delete_restriction(res_type, 0)
@admi.route("/ajax/deleterestriction/<int:res_type>/<int:user_id>", methods=['POST'])
@login_required
@user_login_required
@admin_required
def delete_restriction(res_type, user_id):
element = request.form.to_dict()
@@ -865,7 +884,7 @@ def delete_restriction(res_type, user_id):
@admi.route("/ajax/listrestriction/<int:res_type>", defaults={"user_id": 0})
@admi.route("/ajax/listrestriction/<int:res_type>/<int:user_id>")
@login_required
@user_login_required
@admin_required
def list_restriction(res_type, user_id):
if res_type == 0: # Tags as template
@@ -909,25 +928,36 @@ def list_restriction(res_type, user_id):
@admi.route("/ajax/fullsync", methods=["POST"])
@login_required
def ajax_fullsync():
count = ub.session.query(ub.KoboSyncedBooks).filter(current_user.id == ub.KoboSyncedBooks.user_id).delete()
message = _("{} sync entries deleted").format(count)
ub.session_commit(message)
return Response(json.dumps([{"type": "success", "message": message}]), mimetype='application/json')
@user_login_required
def ajax_self_fullsync():
return do_full_kobo_sync(current_user.id)
@admi.route("/ajax/fullsync/<int:userid>", methods=["POST"])
@user_login_required
@admin_required
def ajax_fullsync(userid):
return do_full_kobo_sync(userid)
@admi.route("/ajax/pathchooser/")
@login_required
@user_login_required
@admin_required
def ajax_pathchooser():
return pathchooser()
def do_full_kobo_sync(userid):
count = ub.session.query(ub.KoboSyncedBooks).filter(userid == ub.KoboSyncedBooks.user_id).delete()
message = _("{} sync entries deleted").format(count)
ub.session_commit(message)
return make_response(jsonify(type="success", message=message))
def check_valid_read_column(column):
if column != "0":
if not calibre_db.session.query(db.CustomColumns).filter(db.CustomColumns.id == column) \
.filter(and_(db.CustomColumns.datatype == 'bool', db.CustomColumns.mark_for_delete == 0)).all():
.filter(and_(db.CustomColumns.datatype == 'bool', db.CustomColumns.mark_for_delete == 0)).all():
return False
return True
@@ -935,7 +965,7 @@ def check_valid_read_column(column):
def check_valid_restricted_column(column):
if column != "0":
if not calibre_db.session.query(db.CustomColumns).filter(db.CustomColumns.id == column) \
.filter(and_(db.CustomColumns.datatype == 'text', db.CustomColumns.mark_for_delete == 0)).all():
.filter(and_(db.CustomColumns.datatype == 'text', db.CustomColumns.mark_for_delete == 0)).all():
return False
return True
@@ -963,8 +993,14 @@ def prepare_tags(user, action, tags_name, id_list):
raise Exception(_("Tag not found"))
new_tags_list = [x.name for x in tags]
else:
tags = calibre_db.session.query(db.cc_classes[config.config_restricted_column]) \
.filter(db.cc_classes[config.config_restricted_column].id.in_(id_list)).all()
try:
tags = calibre_db.session.query(db.cc_classes[config.config_restricted_column]) \
.filter(db.cc_classes[config.config_restricted_column].id.in_(id_list)).all()
except (KeyError, AttributeError, IndexError):
log.error("Custom Column No.{} does not exist in calibre database".format(
config.config_restricted_column))
raise Exception(_("Custom Column No.%(column)d does not exist in calibre database",
column=config.config_restricted_column))
new_tags_list = [x.value for x in tags]
saved_tags_list = user.__dict__[tags_name].split(",") if len(user.__dict__[tags_name]) else []
if action == "remove":
@@ -981,10 +1017,7 @@ def get_drives(current):
for d in string.ascii_uppercase:
if os.path.exists('{}:'.format(d)) and current[0].lower() != d.lower():
drive = "{}:\\".format(d)
data = {"name": drive, "fullpath": drive}
data["sort"] = "_" + data["fullpath"].lower()
data["type"] = "dir"
data["size"] = ""
data = {"name": drive, "fullpath": drive, "type": "dir", "size": "", "sort": "_" + drive.lower()}
drive_letters.append(data)
return drive_letters
@@ -1033,7 +1066,8 @@ def pathchooser():
for f in folders:
try:
data = {"name": f, "fullpath": os.path.join(cwd, f)}
sanitized_f = str(Markup.escape(f))
data = {"name": sanitized_f, "fullpath": os.path.join(cwd, sanitized_f)}
data["sort"] = data["fullpath"].lower()
except Exception:
continue
@@ -1084,7 +1118,7 @@ def _config_checkbox_int(to_save, x):
def _config_string(to_save, x):
return config.set_from_dictionary(to_save, x, lambda y: y.strip().strip(u'\u200B\u200C\u200D\ufeff') if y else y)
return config.set_from_dictionary(to_save, x, lambda y: strip_whitespaces(y) if y else y)
def _configuration_gdrive_helper(to_save):
@@ -1123,12 +1157,12 @@ def _configuration_oauth_helper(to_save):
reboot_required = False
for element in oauthblueprints:
if to_save["config_" + str(element['id']) + "_oauth_client_id"] != element['oauth_client_id'] \
or to_save["config_" + str(element['id']) + "_oauth_client_secret"] != element['oauth_client_secret']:
or to_save["config_" + str(element['id']) + "_oauth_client_secret"] != element['oauth_client_secret']:
reboot_required = True
element['oauth_client_id'] = to_save["config_" + str(element['id']) + "_oauth_client_id"]
element['oauth_client_secret'] = to_save["config_" + str(element['id']) + "_oauth_client_secret"]
if to_save["config_" + str(element['id']) + "_oauth_client_id"] \
and to_save["config_" + str(element['id']) + "_oauth_client_secret"]:
and to_save["config_" + str(element['id']) + "_oauth_client_secret"]:
active_oauths += 1
element["active"] = 1
else:
@@ -1183,9 +1217,9 @@ def _configuration_ldap_helper(to_save):
config.save()
if not config.config_ldap_provider_url \
or not config.config_ldap_port \
or not config.config_ldap_dn \
or not config.config_ldap_user_object:
or not config.config_ldap_port \
or not config.config_ldap_dn \
or not config.config_ldap_user_object:
return reboot_required, _configuration_result(_('Please Enter a LDAP Provider, '
'Port, DN and User Object Identifier'))
@@ -1230,15 +1264,15 @@ def _configuration_ldap_helper(to_save):
@admi.route("/ajax/simulatedbchange", methods=['POST'])
@login_required
@user_login_required
@admin_required
def simulatedbchange():
db_change, db_valid = _db_simulate_change()
return Response(json.dumps({"change": db_change, "valid": db_valid}), mimetype='application/json')
return make_response(jsonify(change=db_change, valid=db_valid))
@admi.route("/admin/user/new", methods=["GET", "POST"])
@login_required
@user_login_required
@admin_required
def new_user():
content = ub.User()
@@ -1260,7 +1294,7 @@ def new_user():
@admi.route("/admin/mailsettings", methods=["GET"])
@login_required
@user_login_required
@admin_required
def edit_mailsettings():
content = config.get_mail_settings()
@@ -1269,7 +1303,7 @@ def edit_mailsettings():
@admi.route("/admin/mailsettings", methods=["POST"])
@login_required
@user_login_required
@admin_required
def update_mailsettings():
to_save = request.form.to_dict()
@@ -1292,11 +1326,12 @@ def update_mailsettings():
else:
_config_int(to_save, "mail_port")
_config_int(to_save, "mail_use_ssl")
_config_string(to_save, "mail_password_e")
if to_save.get("mail_password_e", ""):
_config_string(to_save, "mail_password_e")
_config_int(to_save, "mail_size", lambda y: int(y) * 1024 * 1024)
config.mail_server = to_save.get('mail_server', "").strip()
config.mail_from = to_save.get('mail_from', "").strip()
config.mail_login = to_save.get('mail_login', "").strip()
config.mail_server = strip_whitespaces(to_save.get('mail_server', ""))
config.mail_from = strip_whitespaces(to_save.get('mail_from', ""))
config.mail_login = strip_whitespaces(to_save.get('mail_login', ""))
try:
config.save()
except (OperationalError, InvalidRequestError) as e:
@@ -1325,7 +1360,7 @@ def update_mailsettings():
@admi.route("/admin/scheduledtasks")
@login_required
@user_login_required
@admin_required
def edit_scheduledtasks():
content = config.get_scheduled_task_settings()
@@ -1346,13 +1381,13 @@ def edit_scheduledtasks():
@admi.route("/admin/scheduledtasks", methods=["POST"])
@login_required
@user_login_required
@admin_required
def update_scheduledtasks():
error = False
to_save = request.form.to_dict()
if 0 <= int(to_save.get("schedule_start_time")) <= 23:
_config_int( to_save, "schedule_start_time")
_config_int(to_save, "schedule_start_time")
else:
flash(_("Invalid start time for task specified"), category="error")
error = True
@@ -1389,7 +1424,7 @@ def update_scheduledtasks():
@admi.route("/admin/user/<int:user_id>", methods=["GET", "POST"])
@login_required
@user_login_required
@admin_required
def edit_user(user_id):
content = ub.session.query(ub.User).filter(ub.User.id == int(user_id)).first() # type: ub.User
@@ -1418,7 +1453,7 @@ def edit_user(user_id):
@admi.route("/admin/resetpassword/<int:user_id>", methods=["POST"])
@login_required
@user_login_required
@admin_required
def reset_user_password(user_id):
if current_user is not None and current_user.is_authenticated:
@@ -1436,7 +1471,7 @@ def reset_user_password(user_id):
@admi.route("/admin/logfile")
@login_required
@user_login_required
@admin_required
def view_logfile():
logfiles = {0: logger.get_logfile(config.config_logfile),
@@ -1450,7 +1485,7 @@ def view_logfile():
@admi.route("/ajax/log/<int:logtype>")
@login_required
@user_login_required
@admin_required
def send_logfile(logtype):
if logtype == 1:
@@ -1466,7 +1501,7 @@ def send_logfile(logtype):
@admi.route("/admin/logdownload/<int:logtype>")
@login_required
@user_login_required
@admin_required
def download_log(logtype):
if logtype == 0:
@@ -1481,14 +1516,14 @@ def download_log(logtype):
@admi.route("/admin/debug")
@login_required
@user_login_required
@admin_required
def download_debug():
return debug_info.send_debug()
@admi.route("/get_update_status", methods=['GET'])
@login_required
@user_login_required
@admin_required
def get_update_status():
if feature_support['updater']:
@@ -1499,7 +1534,7 @@ def get_update_status():
@admi.route("/get_updater_status", methods=['GET', 'POST'])
@login_required
@user_login_required
@admin_required
def get_updater_status():
status = {}
@@ -1594,7 +1629,7 @@ def ldap_import_create_user(user, user_data):
@admi.route('/import_ldap_users', methods=["POST"])
@login_required
@user_login_required
@admin_required
def import_ldap_users():
showtext = {}
@@ -1611,7 +1646,10 @@ def import_ldap_users():
imported = 0
for username in new_users:
user = username.decode('utf-8')
if isinstance(username, bytes):
user = username.decode('utf-8')
else:
user = username
if '=' in user:
# if member object field is empty take user object as filter
if config.config_ldap_member_user_object:
@@ -1646,7 +1684,7 @@ def import_ldap_users():
@admi.route("/ajax/canceltask", methods=['POST'])
@login_required
@user_login_required
@admin_required
def cancel_task():
task_id = request.get_json().get('task_id', None)
@@ -1658,10 +1696,10 @@ def cancel_task():
def _db_simulate_change():
param = request.form.to_dict()
to_save = dict()
to_save['config_calibre_dir'] = re.sub(r'[\\/]metadata\.db$',
to_save['config_calibre_dir'] = strip_whitespaces(re.sub(r'[\\/]metadata\.db$',
'',
param['config_calibre_dir'],
flags=re.IGNORECASE).strip()
flags=re.IGNORECASE))
db_valid, db_change = calibre_db.check_valid_db(to_save["config_calibre_dir"],
ub.app_DB_path,
config.config_calibre_uuid)
@@ -1695,14 +1733,19 @@ def _db_configuration_update_helper():
db_change = True
except Exception as ex:
return _db_configuration_result('{}'.format(ex), gdrive_error)
if db_change or not db_valid or not config.db_configured \
or config.config_calibre_dir != to_save["config_calibre_dir"]:
config.config_calibre_split = to_save.get('config_calibre_split', 0) == "on"
if config.config_calibre_split:
split_dir = to_save.get("config_calibre_split_dir")
if not os.path.exists(split_dir):
return _db_configuration_result(_("Books path not valid"), gdrive_error)
else:
_config_string(to_save, "config_calibre_split_dir")
if (db_change or not db_valid or not config.db_configured
or config.config_calibre_dir != to_save["config_calibre_dir"]):
if not os.path.exists(metadata_db) or not to_save['config_calibre_dir']:
return _db_configuration_result(_('DB Location is not Valid, Please Enter Correct Path'), gdrive_error)
else:
calibre_db.setup_db(to_save['config_calibre_dir'], ub.app_DB_path)
config.store_calibre_uuid(calibre_db, db.Library_Id)
# if db changed -> delete shelfs, delete download books, delete read books, kobo sync...
if db_change:
log.info("Calibre Database changed, all Calibre-Web info related to old Database gets deleted")
@@ -1716,10 +1759,20 @@ def _db_configuration_update_helper():
ub.session.query(ub.KoboSyncedBooks).delete()
helper.delete_thumbnail_cache()
ub.session_commit()
# deleted visibilities based on custom column and tags
config.config_restricted_column = 0
config.config_denied_tags = ""
config.config_allowed_tags = ""
config.config_columns_to_ignore = ""
config.config_denied_column_value = ""
config.config_allowed_column_value = ""
config.config_read_column = 0
_config_string(to_save, "config_calibre_dir")
calibre_db.update_config(config)
calibre_db.update_config(config, config.config_calibre_dir, ub.app_DB_path)
config.store_calibre_uuid(calibre_db, db.Library_Id)
if not os.access(os.path.join(config.config_calibre_dir, "metadata.db"), os.W_OK):
flash(_("DB is not Writeable"), category="warning")
calibre_db.update_config(config, config.config_calibre_dir, ub.app_DB_path)
config.save()
return _db_configuration_result(None, gdrive_error)
@@ -1740,6 +1793,7 @@ def _configuration_update_helper():
_config_checkbox_int(to_save, "config_uploading")
_config_checkbox_int(to_save, "config_unicode_filename")
_config_checkbox_int(to_save, "config_embed_metadata")
# Reboot on config_anonbrowse with enabled ldap, as decoraters are changed in this case
reboot_required |= (_config_checkbox_int(to_save, "config_anonbrowse")
and config.config_login_type == constants.LOGIN_LDAP)
@@ -1751,13 +1805,18 @@ def _configuration_update_helper():
if "config_upload_formats" in to_save:
to_save["config_upload_formats"] = ','.join(
helper.uniq([x.lstrip().rstrip().lower() for x in to_save["config_upload_formats"].split(',')]))
helper.uniq([x.strip().lower() for x in to_save["config_upload_formats"].split(',')]))
_config_string(to_save, "config_upload_formats")
constants.EXTENSIONS_UPLOAD = config.config_upload_formats.split(',')
_config_string(to_save, "config_calibre")
_config_string(to_save, "config_converterpath")
_config_string(to_save, "config_binariesdir")
_config_string(to_save, "config_kepubifypath")
if "config_binariesdir" in to_save:
calibre_status = helper.check_calibre(config.config_binariesdir)
if calibre_status:
return _configuration_result(calibre_status)
to_save["config_converterpath"] = get_calibre_binarypath("ebook-convert")
_config_string(to_save, "config_converterpath")
reboot_required |= _config_int(to_save, "config_login_type")
@@ -1776,12 +1835,13 @@ def _configuration_update_helper():
# Goodreads configuration
_config_checkbox(to_save, "config_use_goodreads")
_config_string(to_save, "config_goodreads_api_key")
_config_string(to_save, "config_goodreads_api_secret_e")
if services.goodreads_support:
services.goodreads_support.connect(config.config_goodreads_api_key,
config.config_goodreads_api_secret_e,
config.config_use_goodreads)
# Google Books API configuration
reboot_required |=_config_string(to_save, "config_googlebooks_api_key")
_config_int(to_save, "config_updatechannel")
# Reverse proxy login configuration
@@ -1799,10 +1859,12 @@ def _configuration_update_helper():
reboot_required |= reboot
# security configuration
_config_checkbox(to_save, "config_check_extensions")
_config_checkbox(to_save, "config_password_policy")
_config_checkbox(to_save, "config_password_number")
_config_checkbox(to_save, "config_password_lower")
_config_checkbox(to_save, "config_password_upper")
_config_checkbox(to_save, "config_password_character")
_config_checkbox(to_save, "config_password_special")
if 0 < int(to_save.get("config_password_min_length", "0")) < 41:
_config_int(to_save, "config_password_min_length")
@@ -1810,6 +1872,8 @@ def _configuration_update_helper():
return _configuration_result(_('Password length has to be between 1 and 40'))
reboot_required |= _config_int(to_save, "config_session")
reboot_required |= _config_checkbox(to_save, "config_ratelimiter")
reboot_required |= _config_string(to_save, "config_limiter_uri")
reboot_required |= _config_string(to_save, "config_limiter_options")
# Rarfile Content configuration
_config_string(to_save, "config_rarfile_location")
@@ -1839,7 +1903,7 @@ def _configuration_result(error_flash=None, reboot=False):
resp['result'] = [{'type': "success", 'message': _("Calibre-Web configuration updated")}]
resp['reboot'] = reboot
resp['config_upload'] = config.config_upload_formats
return Response(json.dumps(resp), mimetype='application/json')
return make_response(jsonify(resp))
def _db_configuration_result(error_flash=None, gdrive_error=None):
@@ -2044,7 +2108,7 @@ def _handle_edit_user(to_save, content, languages, translations, kobo_support):
def extract_user_data_from_field(user, field):
match = re.search(field + r"=([@\.\d\s\w-]+)", user, re.IGNORECASE | re.UNICODE)
match = re.search(field + r"=(.*?)($|(?<!\\),)", user, re.IGNORECASE | re.UNICODE)
if match:
return match.group(1)
else:
@@ -2052,7 +2116,7 @@ def extract_user_data_from_field(user, field):
def extract_dynamic_field_from_filter(user, filtr):
match = re.search("([a-zA-Z0-9-]+)=%s", filtr, re.IGNORECASE | re.UNICODE)
match = re.search(r"([a-zA-Z0-9-]+)=%s", filtr, re.IGNORECASE | re.UNICODE)
if match:
return match.group(1)
else:
+147
View File
@@ -0,0 +1,147 @@
# -*- coding: utf-8 -*-
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
# Copyright (C) 2024 Ozzieisaacs
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import mutagen
import base64
from . import cover, logger
from cps.constants import BookMeta
log = logger.create()
def get_audio_file_info(tmp_file_path, original_file_extension, original_file_name, no_cover_processing):
tmp_cover_name = None
audio_file = mutagen.File(tmp_file_path)
comments = None
if original_file_extension in [".mp3", ".wav", ".aiff"]:
cover_data = list()
for key, val in audio_file.tags.items():
if key.startswith("APIC:"):
cover_data.append(val)
if key.startswith("COMM:"):
comments = val.text[0]
title = audio_file.tags.get('TIT2').text[0] if "TIT2" in audio_file.tags else None
author = audio_file.tags.get('TPE1').text[0] if "TPE1" in audio_file.tags else None
if author is None:
author = audio_file.tags.get('TPE2').text[0] if "TPE2" in audio_file.tags else None
tags = audio_file.tags.get('TCON').text[0] if "TCON" in audio_file.tags else None # Genre
series = audio_file.tags.get('TALB').text[0] if "TALB" in audio_file.tags else None# Album
series_id = audio_file.tags.get('TRCK').text[0] if "TRCK" in audio_file.tags else None # track no.
publisher = audio_file.tags.get('TPUB').text[0] if "TPUB" in audio_file.tags else None
pubdate = str(audio_file.tags.get('TDRL').text[0]) if "TDRL" in audio_file.tags else None
if not pubdate:
pubdate = str(audio_file.tags.get('TDRC').text[0]) if "TDRC" in audio_file.tags else None
if not pubdate:
pubdate = str(audio_file.tags.get('TDOR').text[0]) if "TDOR" in audio_file.tags else None
if cover_data and not no_cover_processing:
cover_info = cover_data[0]
for dat in cover_data:
if dat.type == mutagen.id3.PictureType.COVER_FRONT:
cover_info = dat
break
tmp_cover_name = cover.cover_processing(tmp_file_path, cover_info.data, "." + cover_info.mime[-3:])
elif original_file_extension in [".ogg", ".flac", ".opus", ".ogv"]:
title = audio_file.tags.get('TITLE')[0] if "TITLE" in audio_file else None
author = audio_file.tags.get('ARTIST')[0] if "ARTIST" in audio_file else None
comments = audio_file.tags.get('COMMENTS')[0] if "COMMENTS" in audio_file else None
tags = audio_file.tags.get('GENRE')[0] if "GENRE" in audio_file else None # Genre
series = audio_file.tags.get('ALBUM')[0] if "ALBUM" in audio_file else None
series_id = audio_file.tags.get('TRACKNUMBER')[0] if "TRACKNUMBER" in audio_file else None
publisher = audio_file.tags.get('LABEL')[0] if "LABEL" in audio_file else None
pubdate = audio_file.tags.get('DATE')[0] if "DATE" in audio_file else None
cover_data = audio_file.tags.get('METADATA_BLOCK_PICTURE')
if not no_cover_processing:
if cover_data:
cover_info = mutagen.flac.Picture(base64.b64decode(cover_data[0]))
tmp_cover_name = cover.cover_processing(tmp_file_path, cover_info.data, "." + cover_info.mime[-3:])
if hasattr(audio_file, "pictures"):
cover_info = audio_file.pictures[0]
for dat in audio_file.pictures:
if dat.type == mutagen.id3.PictureType.COVER_FRONT:
cover_info = dat
break
tmp_cover_name = cover.cover_processing(tmp_file_path, cover_info.data, "." + cover_info.mime[-3:])
elif original_file_extension in [".aac"]:
title = audio_file.tags.get('Title').value if "Title" in audio_file else None
author = audio_file.tags.get('Artist').value if "Artist" in audio_file else None
comments = audio_file.tags.get('Comment').value if "Comment" in audio_file else None
tags = audio_file.tags.get('Genre').value if "Genre" in audio_file else None
series = audio_file.tags.get('Album').value if "Album" in audio_file else None
series_id = audio_file.tags.get('Track').value if "Track" in audio_file else None
publisher = audio_file.tags.get('Label').value if "Label" in audio_file else None
pubdate = audio_file.tags.get('Year').value if "Year" in audio_file else None
cover_data = audio_file.tags['Cover Art (Front)']
if cover_data and not no_cover_processing:
tmp_cover_name = tmp_file_path + '.jpg'
with open(tmp_cover_name, "wb") as cover_file:
cover_file.write(cover_data.value.split(b"\x00",1)[1])
elif original_file_extension in [".asf"]:
title = audio_file.tags.get('Title')[0].value if "Title" in audio_file else None
author = audio_file.tags.get('Artist')[0].value if "Artist" in audio_file else None
comments = audio_file.tags.get('Comments')[0].value if "Comments" in audio_file else None
tags = audio_file.tags.get('Genre')[0].value if "Genre" in audio_file else None
series = audio_file.tags.get('Album')[0].value if "Album" in audio_file else None
series_id = audio_file.tags.get('Track')[0].value if "Track" in audio_file else None
publisher = audio_file.tags.get('Label')[0].value if "Label" in audio_file else None
pubdate = audio_file.tags.get('Year')[0].value if "Year" in audio_file else None
cover_data = audio_file.tags.get('WM/Picture', None)
if cover_data and not no_cover_processing:
tmp_cover_name = tmp_file_path + '.jpg'
with open(tmp_cover_name, "wb") as cover_file:
cover_file.write(cover_data[0].value)
elif original_file_extension in [".mp4", ".m4a", ".m4b"]:
title = audio_file.tags.get('©nam')[0] if "©nam" in audio_file.tags else None
author = audio_file.tags.get('©ART')[0] if "©ART" in audio_file.tags else None
comments = audio_file.tags.get('©cmt')[0] if "©cmt" in audio_file.tags else None
tags = audio_file.tags.get('©gen')[0] if "©gen" in audio_file.tags else None
series = audio_file.tags.get('©alb')[0] if "©alb" in audio_file.tags else None
series_id = str(audio_file.tags.get('trkn')[0][0]) if "trkn" in audio_file.tags else None
publisher = ""
pubdate = audio_file.tags.get('©day')[0] if "©day" in audio_file.tags else None
cover_data = audio_file.tags.get('covr', None)
if cover_data and not no_cover_processing:
cover_type = None
for c in cover_data:
if c.imageformat == mutagen.mp4.AtomDataType.JPEG:
cover_type =".jpg"
cover_bin = c
break
elif c.imageformat == mutagen.mp4.AtomDataType.PNG:
cover_type = ".png"
cover_bin = c
break
if cover_type:
tmp_cover_name = cover.cover_processing(tmp_file_path, cover_bin, cover_type)
else:
logger.error("Unknown covertype in file {} ".format(original_file_name))
return BookMeta(
file_path=tmp_file_path,
extension=original_file_extension,
title=title or original_file_name ,
author="Unknown" if author is None else author,
cover=tmp_cover_name,
description="" if comments is None else comments,
tags="" if tags is None else tags,
series="" if series is None else series,
series_id="1" if series_id is None else series_id.split("/")[0],
languages="",
publisher= "" if publisher is None else publisher,
pubdate="" if pubdate is None else pubdate,
identifiers=[],
)
+89
View File
@@ -0,0 +1,89 @@
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
# Copyright (C) 2018-2019 OzzieIsaacs, cervinko, jkrehm, bodybybuddha, ok11,
# andy29485, idalin, Kyosfonica, wuqi, Kennyl, lemmsh,
# falgh1, grunjol, csitko, ytils, xybydy, trasba, vrabe,
# ruben-herold, marblepebble, JackED42, SiphonSquirrel,
# apetresc, nanu-c, mutschler, carderne
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from flask import Blueprint
from flask_babel import gettext as _
from flask_babel import get_locale
from flask import request, redirect, url_for
from . import logger, isoLanguages
from . import db, config
from . import calibre_db
from .usermanagement import login_required_if_no_ano
from .render_template import render_title_template
from .web import get_sort_function
try:
from natsort import natsorted as sort
except ImportError:
sort = sorted # Just use regular sort then, may cause issues with badly named pages in cbz/cbr files
basic = Blueprint('basic', __name__)
log = logger.create()
@basic.route("/basic", methods=["GET"])
@login_required_if_no_ano
def index():
term = request.args.get("query", "") # default to showing all books
limit = 15
page = int(request.args.get("page") or 1)
off = (page - 1) * limit
order = get_sort_function("stored", "search")
join = db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series
entries, result_count, pagination = calibre_db.get_search_results(term,
config,
off,
order,
limit,
*join)
return render_title_template('basic_index.html',
searchterm=term,
pagination=pagination,
query=term,
adv_searchterm=term,
entries=entries,
result_count=result_count,
title=_("Search"),
page="search",
order=order[1])
@basic.route("/basic_book/<int:book_id>")
@login_required_if_no_ano
def show_book(book_id):
entries = calibre_db.get_book_read_archived(book_id, config.config_read_column, allow_show_archived=True)
if entries:
entry = entries[0]
for lang_index in range(0, len(entry.languages)):
entry.languages[lang_index].language_name = isoLanguages.get_language_name(get_locale(), entry.languages[
lang_index].lang_code)
entry.ordered_authors = calibre_db.order_authors([entry])
return render_title_template('basic_detail.html',
entry=entry,
is_xhr=request.headers.get('X-Requested-With') == 'XMLHttpRequest',
title=entry.title,
page="book")
else:
log.debug("Selected book is unavailable. File does not exist or is not accessible")
return redirect(url_for("basic.index"))
+53
View File
@@ -0,0 +1,53 @@
# -*- coding: utf-8 -*-
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
# Copyright (C) 2018-2019 OzzieIsaacs
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from . import logger
from lxml.etree import ParserError
log = logger.create()
try:
# at least bleach 6.0 is needed -> incomplatible change from list arguments to set arguments
from bleach import clean as clean_html
from bleach.sanitizer import ALLOWED_TAGS
bleach = True
except ImportError:
from nh3 import clean as clean_html
bleach = False
def clean_string(unsafe_text, book_id=0):
try:
if bleach:
allowed_tags = list(ALLOWED_TAGS)
allowed_tags.extend(["p", "span", "div", "pre", "br", "h1", "h2", "h3", "h4", "h5", "h6", "img"])
allowed_attributes = {
"*": ["class", "style"],
"a": ["href", "title", "rel"],
"img": ["src", "alt", "title", "width", "height"],
}
safe_text = clean_html(unsafe_text, tags=set(allowed_tags), attributes=allowed_attributes)
else:
safe_text = clean_html(unsafe_text)
except ParserError as e:
log.error("Comments of book {} are corrupted: {}".format(book_id, e))
safe_text = ""
except TypeError as e:
log.error("Comments can't be parsed, maybe 'lxml' is too new, try installing 'bleach': {}".format(e))
safe_text = ""
return safe_text
+30 -12
View File
@@ -29,12 +29,25 @@ from .constants import DEFAULT_SETTINGS_FILE, DEFAULT_GDRIVE_FILE
def version_info():
if _NIGHTLY_VERSION[1].startswith('$Format'):
return "Calibre-Web version: %s - unknown git-clone" % _STABLE_VERSION['version']
return "Calibre-Web version: %s -%s" % (_STABLE_VERSION['version'], _NIGHTLY_VERSION[1])
return "Calibre-Web version: %s - unknown git-clone" % _STABLE_VERSION.replace("b", " Beta")
return "Calibre-Web version: %s -%s" % (_STABLE_VERSION.replace("b", " Beta"), _NIGHTLY_VERSION[1])
class CliParameter(object):
def __init__(self):
self.user_credentials = None
self.ip_address = None
self.allow_localhost = None
self.reconnect_enable = None
self.memory_backend = None
self.dry_run = None
self.certfilepath = None
self.keyfilepath = None
self.gd_path = None
self.settings_path = None
self.logpath = None
def init(self):
self.arg_parser()
@@ -44,22 +57,28 @@ class CliParameter(object):
prog='cps.py')
parser.add_argument('-p', metavar='path', help='path and name to settings db, e.g. /opt/cw.db')
parser.add_argument('-g', metavar='path', help='path and name to gdrive db, e.g. /opt/gd.db')
parser.add_argument('-c', metavar='path', help='path and name to SSL certfile, e.g. /opt/test.cert, '
'works only in combination with keyfile')
parser.add_argument('-c', metavar='path', help='path and name to SSL certfile, '
'e.g. /opt/test.cert, works only in combination with keyfile')
parser.add_argument('-k', metavar='path', help='path and name to SSL keyfile, e.g. /opt/test.key, '
'works only in combination with certfile')
parser.add_argument('-v', '--version', action='version', help='Shows version number and exits Calibre-Web',
parser.add_argument('-o', metavar='path', help='path and name Calibre-Web logfile')
parser.add_argument('-v', '--version', action='version', help='Shows version number '
'and exits Calibre-Web',
version=version_info())
parser.add_argument('-i', metavar='ip-address', help='Server IP-Address to listen')
parser.add_argument('-m', action='store_true',
help='Use Memory-backend as limiter backend, use this parameter '
'in case of miss configured backend')
parser.add_argument('-s', metavar='user:pass',
help='Sets specific username to new password and exits Calibre-Web')
parser.add_argument('-f', action='store_true', help='Flag is depreciated and will be removed in next version')
parser.add_argument('-l', action='store_true', help='Allow loading covers from localhost')
parser.add_argument('-d', action='store_true', help='Dry run of updater to check file permissions in advance '
'and exits Calibre-Web')
parser.add_argument('-r', action='store_true', help='Enable public database reconnect route under /reconnect')
parser.add_argument('-d', action='store_true', help='Dry run of updater to check file permissions '
'in advance and exits Calibre-Web')
parser.add_argument('-r', action='store_true', help='Enable public database reconnect '
'route under /reconnect')
args = parser.parse_args()
self.logpath = args.o or ""
self.settings_path = args.p or os.path.join(_CONFIG_DIR, DEFAULT_SETTINGS_FILE)
self.gd_path = args.g or os.path.join(_CONFIG_DIR, DEFAULT_GDRIVE_FILE)
@@ -96,6 +115,8 @@ class CliParameter(object):
if args.k == "":
self.keyfilepath = ""
# overwrite limiter backend
self.memory_backend = args.m or None
# dry run updater
self.dry_run = args.d or None
# enable reconnect endpoint for docker database reconnect
@@ -125,6 +146,3 @@ class CliParameter(object):
if self.user_credentials and ":" not in self.user_credentials:
print("No valid 'username:password' format")
sys.exit(3)
if args.f:
print("Warning: -f flag is depreciated and will be removed in next version")
+70 -25
View File
@@ -36,6 +36,12 @@ try:
from comicapi import __version__ as comic_version
except ImportError:
comic_version = ''
try:
from comicapi.comicarchive import load_archive_plugins
import comicapi.utils
comicapi.utils.add_rar_paths()
except ImportError:
load_archive_plugins = None
except (ImportError, LookupError) as e:
log.debug('Cannot import comicapi, extracting comic metadata will not work: %s', e)
import zipfile
@@ -46,6 +52,12 @@ except (ImportError, LookupError) as e:
except (ImportError, SyntaxError) as e:
log.debug('Cannot import rarfile, extracting cover files from rar files will not work: %s', e)
use_rarfile = False
try:
import py7zr
use_7zip = True
except (ImportError, SyntaxError) as e:
log.debug('Cannot import py7zr, extracting cover files from CB7 files will not work: %s', e)
use_7zip = False
use_comic_meta = False
@@ -53,7 +65,7 @@ def _extract_cover_from_archive(original_file_extension, tmp_file_name, rar_exec
cover_data = extension = None
if original_file_extension.upper() == '.CBZ':
cf = zipfile.ZipFile(tmp_file_name)
for name in cf.namelist():
for name in sorted(cf.namelist()):
ext = os.path.splitext(name)
if len(ext) > 1:
extension = ext[1].lower()
@@ -62,7 +74,7 @@ def _extract_cover_from_archive(original_file_extension, tmp_file_name, rar_exec
break
elif original_file_extension.upper() == '.CBT':
cf = tarfile.TarFile(tmp_file_name)
for name in cf.getnames():
for name in sorted(cf.getnames()):
ext = os.path.splitext(name)
if len(ext) > 1:
extension = ext[1].lower()
@@ -73,7 +85,7 @@ def _extract_cover_from_archive(original_file_extension, tmp_file_name, rar_exec
try:
rarfile.UNRAR_TOOL = rar_executable
cf = rarfile.RarFile(tmp_file_name)
for name in cf.namelist():
for name in sorted(cf.namelist()):
ext = os.path.splitext(name)
if len(ext) > 1:
extension = ext[1].lower()
@@ -81,50 +93,79 @@ def _extract_cover_from_archive(original_file_extension, tmp_file_name, rar_exec
cover_data = cf.read(name)
break
except Exception as ex:
log.debug('Rarfile failed with error: {}'.format(ex))
return cover_data, extension
def _extract_cover(tmp_file_name, original_file_extension, rar_executable):
cover_data = extension = None
if use_comic_meta:
archive = ComicArchive(tmp_file_name, rar_exe_path=rar_executable)
for index, name in enumerate(archive.getPageNameList()):
log.error('Rarfile failed with error: {}'.format(ex))
elif original_file_extension.upper() == '.CB7' and use_7zip:
cf = py7zr.SevenZipFile(tmp_file_name)
for name in sorted(cf.getnames()):
ext = os.path.splitext(name)
if len(ext) > 1:
extension = ext[1].lower()
if extension in cover.COVER_EXTENSIONS:
cover_data = archive.getPage(index)
try:
cover_data = cf.read([name])[name].read()
except (py7zr.Bad7zFile, OSError) as ex:
log.error('7Zip file failed with error: {}'.format(ex))
break
return cover_data, extension
def _extract_cover(tmp_file_path, original_file_extension, rar_executable):
cover_data = extension = None
if use_comic_meta:
try:
archive = ComicArchive(tmp_file_path, rar_exe_path=rar_executable)
except TypeError:
archive = ComicArchive(tmp_file_path)
name_list = archive.getPageNameList if hasattr(archive, "getPageNameList") else archive.get_page_name_list
for index, name in enumerate(name_list()):
ext = os.path.splitext(name)
if len(ext) > 1:
extension = ext[1].lower()
if extension in cover.COVER_EXTENSIONS:
get_page = archive.getPage if hasattr(archive, "getPageNameList") else archive.get_page
cover_data = get_page(index)
break
else:
cover_data, extension = _extract_cover_from_archive(original_file_extension, tmp_file_name, rar_executable)
return cover.cover_processing(tmp_file_name, cover_data, extension)
cover_data, extension = _extract_cover_from_archive(original_file_extension, tmp_file_path, rar_executable)
return cover.cover_processing(tmp_file_path, cover_data, extension)
def get_comic_info(tmp_file_path, original_file_name, original_file_extension, rar_executable):
def get_comic_info(tmp_file_path, original_file_name, original_file_extension, rar_executable, no_cover_processing):
if use_comic_meta:
archive = ComicArchive(tmp_file_path, rar_exe_path=rar_executable)
if archive.seemsToBeAComicArchive():
if archive.hasMetadata(MetaDataStyle.CIX):
try:
archive = ComicArchive(tmp_file_path, rar_exe_path=rar_executable)
except TypeError:
load_archive_plugins(force=True, rar=rar_executable)
archive = ComicArchive(tmp_file_path)
if hasattr(archive, "seemsToBeAComicArchive"):
seems_archive = archive.seemsToBeAComicArchive
else:
seems_archive = archive.seems_to_be_a_comic_archive
if seems_archive():
has_metadata = archive.hasMetadata if hasattr(archive, "hasMetadata") else archive.has_metadata
if has_metadata(MetaDataStyle.CIX):
style = MetaDataStyle.CIX
elif archive.hasMetadata(MetaDataStyle.CBI):
elif has_metadata(MetaDataStyle.CBI):
style = MetaDataStyle.CBI
else:
style = None
# if style is not None:
loaded_metadata = archive.readMetadata(style)
read_metadata = archive.readMetadata if hasattr(archive, "readMetadata") else archive.read_metadata
loaded_metadata = read_metadata(style)
lang = loaded_metadata.language or ""
loaded_metadata.language = isoLanguages.get_lang3(lang)
if not no_cover_processing:
cover_file = _extract_cover(tmp_file_path, original_file_extension, rar_executable)
else:
cover_file = None
return BookMeta(
file_path=tmp_file_path,
extension=original_file_extension,
title=loaded_metadata.title or original_file_name,
author=" & ".join([credit["person"]
for credit in loaded_metadata.credits if credit["role"] == "Writer"]) or 'Unknown',
cover=_extract_cover(tmp_file_path, original_file_extension, rar_executable),
cover=cover_file,
description=loaded_metadata.comments or "",
tags="",
series=loaded_metadata.series or "",
@@ -133,13 +174,17 @@ def get_comic_info(tmp_file_path, original_file_name, original_file_extension, r
publisher="",
pubdate="",
identifiers=[])
if not no_cover_processing:
cover_file = _extract_cover(tmp_file_path, original_file_extension, rar_executable)
else:
cover_file = None
return BookMeta(
file_path=tmp_file_path,
extension=original_file_extension,
title=original_file_name,
author='Unknown',
cover=_extract_cover(tmp_file_path, original_file_extension, rar_executable),
cover=cover_file,
description="",
tags="",
series="",
+87 -45
View File
@@ -34,7 +34,8 @@ except ImportError:
from sqlalchemy.ext.declarative import declarative_base
from . import constants, logger
from .subproc_wrapper import process_wait
from .string_helper import strip_whitespaces
log = logger.create()
_Base = declarative_base()
@@ -47,6 +48,7 @@ class _Flask_Settings(_Base):
flask_session_key = Column(BLOB, default=b"")
def __init__(self, key):
super().__init__()
self.flask_session_key = key
@@ -69,6 +71,8 @@ class _Settings(_Base):
config_calibre_dir = Column(String)
config_calibre_uuid = Column(String)
config_calibre_split = Column(Boolean, default=False)
config_calibre_split_dir = Column(String)
config_port = Column(Integer, default=constants.DEFAULT_PORT)
config_external_port = Column(Integer, default=constants.DEFAULT_PORT)
config_certfile = Column(String)
@@ -79,13 +83,15 @@ class _Settings(_Base):
config_random_books = Column(Integer, default=4)
config_authors_max = Column(Integer, default=0)
config_read_column = Column(Integer, default=0)
config_title_regex = Column(String, default=r'^(A|The|An|Der|Die|Das|Den|Ein|Eine|Einen|Dem|Des|Einem|Eines|Le|La|Les|L\'|Un|Une)\s+')
config_title_regex = Column(String,
default=r"^(A|The|An|Der|Die|Das|Den|Ein|Eine"
r"|Einen|Dem|Des|Einem|Eines|Le|La|Les|L'|Un|Une)(\s+|(?<='))")
config_theme = Column(Integer, default=0)
config_log_level = Column(SmallInteger, default=logger.DEFAULT_LOG_LEVEL)
config_logfile = Column(String)
config_logfile = Column(String, default=logger.DEFAULT_LOG_FILE)
config_access_log = Column(SmallInteger, default=0)
config_access_logfile = Column(String)
config_access_logfile = Column(String, default=logger.DEFAULT_ACCESS_LOG)
config_uploading = Column(SmallInteger, default=0)
config_anonbrowse = Column(SmallInteger, default=0)
@@ -111,8 +117,7 @@ class _Settings(_Base):
config_use_goodreads = Column(Boolean, default=False)
config_goodreads_api_key = Column(String)
config_goodreads_api_secret_e = Column(String)
config_goodreads_api_secret = Column(String)
config_googlebooks_api_key = Column(String, default='')
config_register_email = Column(Boolean, default=False)
config_login_type = Column(Integer, default=0)
@@ -138,10 +143,12 @@ class _Settings(_Base):
config_kepubifypath = Column(String, default=None)
config_converterpath = Column(String, default=None)
config_binariesdir = Column(String, default=None)
config_calibre = Column(String)
config_rarfile_location = Column(String, default=None)
config_upload_formats = Column(String, default=','.join(constants.EXTENSIONS_UPLOAD))
config_unicode_filename = Column(Boolean, default=False)
config_embed_metadata = Column(Boolean, default=True)
config_updatechannel = Column(Integer, default=constants.UPDATE_STABLE)
@@ -160,9 +167,13 @@ class _Settings(_Base):
config_password_number = Column(Boolean, default=True)
config_password_lower = Column(Boolean, default=True)
config_password_upper = Column(Boolean, default=True)
config_password_character = Column(Boolean, default=True)
config_password_special = Column(Boolean, default=True)
config_session = Column(Integer, default=1)
config_ratelimiter = Column(Boolean, default=True)
config_limiter_uri = Column(String, default="")
config_limiter_options = Column(String, default="")
config_check_extensions = Column(Boolean, default=True)
def __repr__(self):
return self.__class__.__name__
@@ -184,15 +195,17 @@ class ConfigSQL(object):
self.load()
change = False
if self.config_converterpath == None: # pylint: disable=access-member-before-definition
change = True
self.config_converterpath = autodetect_calibre_binary()
if self.config_kepubifypath == None: # pylint: disable=access-member-before-definition
if self.config_binariesdir is None:
change = True
self.config_binariesdir = autodetect_calibre_binaries()
self.config_converterpath = autodetect_converter_binary(self.config_binariesdir)
if self.config_kepubifypath is None:
change = True
self.config_kepubifypath = autodetect_kepubify_binary()
if self.config_rarfile_location == None: # pylint: disable=access-member-before-definition
if self.config_rarfile_location is None:
change = True
self.config_rarfile_location = autodetect_unrar_binary()
if change:
@@ -256,19 +269,19 @@ class ConfigSQL(object):
def list_denied_tags(self):
mct = self.config_denied_tags or ""
return [t.strip() for t in mct.split(",")]
return [strip_whitespaces(t) for t in mct.split(",")]
def list_allowed_tags(self):
mct = self.config_allowed_tags or ""
return [t.strip() for t in mct.split(",")]
return [strip_whitespaces(t) for t in mct.split(",")]
def list_denied_column_values(self):
mct = self.config_denied_column_value or ""
return [t.strip() for t in mct.split(",")]
return [strip_whitespaces(t) for t in mct.split(",")]
def list_allowed_column_values(self):
mct = self.config_allowed_column_value or ""
return [t.strip() for t in mct.split(",")]
return [strip_whitespaces(t) for t in mct.split(",")]
def get_log_level(self):
return logger.get_level_name(self.config_log_level)
@@ -313,7 +326,9 @@ class ConfigSQL(object):
def to_dict(self):
storage = {}
for k, v in self.__dict__.items():
if k[0] != '_' and not k.endswith("_e") and not k == "cli":
if k[0] != '_' and not k.endswith("_e") and not k == "cli" \
and 'api' not in k.lower() and 'token' not in k.lower() \
and 'secret' not in k.lower():
storage[k] = v
return storage
@@ -340,15 +355,18 @@ class ConfigSQL(object):
db_file = os.path.join(self.config_calibre_dir, 'metadata.db')
have_metadata_db = os.path.isfile(db_file)
self.db_configured = have_metadata_db
constants.EXTENSIONS_UPLOAD = [x.lstrip().rstrip().lower() for x in self.config_upload_formats.split(',')]
from . import cli_param
if os.environ.get('FLASK_DEBUG'):
logfile = logger.setup(logger.LOG_TO_STDOUT, logger.logging.DEBUG)
else:
# pylint: disable=access-member-before-definition
logfile = logger.setup(self.config_logfile, self.config_log_level)
if logfile != self.config_logfile:
log.warning("Log path %s not valid, falling back to default", self.config_logfile)
logfile = logger.setup(cli_param.logpath or self.config_logfile, self.config_log_level)
if logfile != os.path.abspath(self.config_logfile):
if logfile != os.path.abspath(cli_param.logpath):
log.warning("Log path %s not valid, falling back to default", self.config_logfile)
self.config_logfile = logfile
s.config_logfile = logfile
self._session.merge(s)
try:
self._session.commit()
@@ -386,12 +404,17 @@ class ConfigSQL(object):
self.db_configured = False
self.save()
def get_book_path(self):
return self.config_calibre_split_dir if self.config_calibre_split else self.config_calibre_dir
def store_calibre_uuid(self, calibre_db, Library_table):
from . import app
try:
calibre_uuid = calibre_db.session.query(Library_table).one_or_none()
if self.config_calibre_uuid != calibre_uuid.uuid:
self.config_calibre_uuid = calibre_uuid.uuid
self.save()
with app.app_context():
calibre_uuid = calibre_db.session.query(Library_table).one_or_none()
if self.config_calibre_uuid != calibre_uuid.uuid:
self.config_calibre_uuid = calibre_uuid.uuid
self.save()
except AttributeError:
pass
@@ -405,24 +428,17 @@ def _encrypt_fields(session, secret_key):
session.query(exists().where(_Settings.mail_password_e)).scalar()
except OperationalError:
with session.bind.connect() as conn:
conn.execute("ALTER TABLE settings ADD column 'mail_password_e' String")
conn.execute("ALTER TABLE settings ADD column 'config_goodreads_api_secret_e' String")
conn.execute("ALTER TABLE settings ADD column 'config_ldap_serv_password_e' String")
conn.execute(text("ALTER TABLE settings ADD column 'mail_password_e' String"))
conn.execute(text("ALTER TABLE settings ADD column 'config_ldap_serv_password_e' String"))
session.commit()
crypter = Fernet(secret_key)
settings = session.query(_Settings.mail_password, _Settings.config_goodreads_api_secret,
_Settings.config_ldap_serv_password).first()
settings = session.query(_Settings.mail_password, _Settings.config_ldap_serv_password).first()
if settings.mail_password:
session.query(_Settings).update(
{_Settings.mail_password_e: crypter.encrypt(settings.mail_password.encode())})
if settings.config_goodreads_api_secret:
session.query(_Settings).update(
{_Settings.config_goodreads_api_secret_e:
crypter.encrypt(settings.config_goodreads_api_secret.encode())})
if settings.config_ldap_serv_password:
session.query(_Settings).update(
{_Settings.config_ldap_serv_password_e:
crypter.encrypt(settings.config_ldap_serv_password.encode())})
{_Settings.config_ldap_serv_password_e: crypter.encrypt(settings.config_ldap_serv_password.encode())})
session.commit()
@@ -466,17 +482,37 @@ def _migrate_table(session, orm_class, secret_key=None):
session.rollback()
def autodetect_calibre_binary():
def autodetect_calibre_binaries():
if sys.platform == "win32":
calibre_path = ["C:\\program files\\calibre\\ebook-convert.exe",
"C:\\program files(x86)\\calibre\\ebook-convert.exe",
"C:\\program files(x86)\\calibre2\\ebook-convert.exe",
"C:\\program files\\calibre2\\ebook-convert.exe"]
calibre_path = ["C:\\program files\\calibre\\",
"C:\\program files(x86)\\calibre\\",
"C:\\program files(x86)\\calibre2\\",
"C:\\program files\\calibre2\\"]
elif sys.platform.startswith("freebsd"):
calibre_path = ["/usr/local/bin/"]
else:
calibre_path = ["/opt/calibre/ebook-convert"]
calibre_path = ["/opt/calibre/"]
for element in calibre_path:
if os.path.isfile(element) and os.access(element, os.X_OK):
return element
supported_binary_paths = [os.path.join(element, binary)
for binary in constants.SUPPORTED_CALIBRE_BINARIES.values()]
if all(os.path.isfile(binary_path) and os.access(binary_path, os.X_OK)
for binary_path in supported_binary_paths):
values = [process_wait([binary_path, "--version"],
pattern=r'\(calibre (.*)\)') for binary_path in supported_binary_paths]
if all(values):
version = values[0].group(1)
log.debug("calibre version %s", version)
return element
return ""
def autodetect_converter_binary(calibre_path):
if sys.platform == "win32":
converter_path = os.path.join(calibre_path, "ebook-convert.exe")
else:
converter_path = os.path.join(calibre_path, "ebook-convert")
if calibre_path and os.path.isfile(converter_path) and os.access(converter_path, os.X_OK):
return converter_path
return ""
@@ -484,6 +520,8 @@ def autodetect_unrar_binary():
if sys.platform == "win32":
calibre_path = ["C:\\program files\\WinRar\\unRAR.exe",
"C:\\program files(x86)\\WinRar\\unRAR.exe"]
elif sys.platform.startswith("freebsd"):
calibre_path = ["/usr/local/bin/unrar"]
else:
calibre_path = ["/usr/bin/unrar"]
for element in calibre_path:
@@ -496,6 +534,8 @@ def autodetect_kepubify_binary():
if sys.platform == "win32":
calibre_path = ["C:\\program files\\kepubify\\kepubify-windows-64Bit.exe",
"C:\\program files(x86)\\kepubify\\kepubify-windows-64Bit.exe"]
elif sys.platform.startswith("freebsd"):
calibre_path = ["/usr/local/bin/kepubify"]
else:
calibre_path = ["/opt/kepubify/kepubify-linux-64bit", "/opt/kepubify/kepubify-linux-32bit"]
for element in calibre_path:
@@ -520,7 +560,7 @@ def load_configuration(session, secret_key):
def get_flask_session_key(_session):
flask_settings = _session.query(_Flask_Settings).one_or_none()
if flask_settings == None:
if flask_settings is None:
flask_settings = _Flask_Settings(os.urandom(32))
_session.add(flask_settings)
_session.commit()
@@ -531,7 +571,8 @@ def get_encryption_key(key_path):
key_file = os.path.join(key_path, ".key")
generate = True
error = ""
if os.path.exists(key_file) and os.path.getsize(key_file) > 32:
key = None
if os.path.exists(key_file) and os.path.getsize(key_file) > 32:
with open(key_file, "rb") as f:
key = f.read()
try:
@@ -544,6 +585,7 @@ def get_encryption_key(key_path):
try:
with open(key_file, "wb") as f:
f.write(key)
os.chmod(key_file, 0o600)
except PermissionError as e:
error = e
return key, error
+21 -11
View File
@@ -19,9 +19,6 @@
import sys
import os
from collections import namedtuple
from sqlalchemy import __version__ as sql_version
sqlalchemy_version2 = ([int(x) for x in sql_version.split('.')] >= [2, 0, 0])
# APP_MODE - production, development, or test
APP_MODE = os.environ.get('APP_MODE', 'production')
@@ -34,13 +31,18 @@ UPDATER_AVAILABLE = True
# Base dir is parent of current file, necessary if called from different folder
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir))
# if executable file the files should be placed in the parent dir (parallel to the exe file)
STATIC_DIR = os.path.join(BASE_DIR, 'cps', 'static')
TEMPLATES_DIR = os.path.join(BASE_DIR, 'cps', 'templates')
TRANSLATIONS_DIR = os.path.join(BASE_DIR, 'cps', 'translations')
# Cache dir - use CACHE_DIR environment variable, otherwise use the default directory: cps/cache
# Cache dir - use CACHE_DIRECTORY environment variable, otherwise CACHE_DIR (for backwards compatibility),
# otherwise use the default directory: cps/cache
DEFAULT_CACHE_DIR = os.path.join(BASE_DIR, 'cps', 'cache')
CACHE_DIR = os.environ.get('CACHE_DIR', DEFAULT_CACHE_DIR)
CACHE_DIRECTORY = os.environ.get(
'CACHE_DIRECTORY', os.environ.get('CACHE_DIR', DEFAULT_CACHE_DIR)
)
if HOME_CONFIG:
home_dir = os.path.join(os.path.expanduser("~"), ".calibre-web")
@@ -49,6 +51,9 @@ if HOME_CONFIG:
CONFIG_DIR = os.environ.get('CALIBRE_DBPATH', home_dir)
else:
CONFIG_DIR = os.environ.get('CALIBRE_DBPATH', BASE_DIR)
if getattr(sys, 'frozen', False):
CONFIG_DIR = os.path.abspath(os.path.join(CONFIG_DIR, os.pardir))
DEFAULT_SETTINGS_FILE = "app.db"
DEFAULT_GDRIVE_FILE = "gdrive.db"
@@ -144,17 +149,23 @@ del env_CALIBRE_PORT
EXTENSIONS_AUDIO = {'mp3', 'mp4', 'ogg', 'opus', 'wav', 'flac', 'm4a', 'm4b'}
EXTENSIONS_CONVERT_FROM = ['pdf', 'epub', 'mobi', 'azw3', 'docx', 'rtf', 'fb2', 'lit', 'lrf',
'txt', 'htmlz', 'rtf', 'odt', 'cbz', 'cbr']
'txt', 'htmlz', 'rtf', 'odt', 'cbz', 'cbr', 'prc']
EXTENSIONS_CONVERT_TO = ['pdf', 'epub', 'mobi', 'azw3', 'docx', 'rtf', 'fb2',
'lit', 'lrf', 'txt', 'htmlz', 'rtf', 'odt']
EXTENSIONS_UPLOAD = {'txt', 'pdf', 'epub', 'kepub', 'mobi', 'azw', 'azw3', 'cbr', 'cbz', 'cbt', 'djvu',
EXTENSIONS_UPLOAD = {'txt', 'pdf', 'epub', 'kepub', 'mobi', 'azw', 'azw3', 'cbr', 'cbz', 'cbt', 'cb7', 'djvu', 'djv',
'prc', 'doc', 'docx', 'fb2', 'html', 'rtf', 'lit', 'odt', 'mp3', 'mp4', 'ogg',
'opus', 'wav', 'flac', 'm4a', 'm4b'}
_extension = ""
if sys.platform == "win32":
_extension = ".exe"
SUPPORTED_CALIBRE_BINARIES = {binary: binary + _extension for binary in ["ebook-convert", "calibredb"]}
def has_flag(value, bit_flag):
return bit_flag == (bit_flag & (value or 0))
def selected_roles(dictionary):
return sum(v for k, v in ALL_ROLES.items() if k in dictionary)
@@ -163,13 +174,12 @@ def selected_roles(dictionary):
BookMeta = namedtuple('BookMeta', 'file_path, extension, title, author, cover, description, tags, series, '
'series_id, languages, publisher, pubdate, identifiers')
STABLE_VERSION = {'version': '0.6.20'}
# python build process likes to have x.y.zbw -> b for beta and w a counting number
STABLE_VERSION = '0.6.27b'
NIGHTLY_VERSION = dict()
NIGHTLY_VERSION[0] = '$Format:%H$'
NIGHTLY_VERSION[1] = '$Format:%cI$'
# NIGHTLY_VERSION[0] = 'bb7d2c6273ae4560e83950d36d64533343623a57'
# NIGHTLY_VERSION[1] = '2018-09-09T10:13:08+02:00'
# CACHE
CACHE_TYPE_THUMBNAILS = 'thumbnails'
@@ -183,7 +193,7 @@ THUMBNAIL_TYPE_AUTHOR = 3
COVER_THUMBNAIL_ORIGINAL = 0
COVER_THUMBNAIL_SMALL = 1
COVER_THUMBNAIL_MEDIUM = 2
COVER_THUMBNAIL_LARGE = 3
COVER_THUMBNAIL_LARGE = 4
# clean-up the module namespace
del sys, os, namedtuple
+4 -3
View File
@@ -29,13 +29,14 @@ NO_JPEG_EXTENSIONS = ['.png', '.webp', '.bmp']
COVER_EXTENSIONS = ['.png', '.webp', '.bmp', '.jpg', '.jpeg']
def cover_processing(tmp_file_name, img, extension):
tmp_cover_name = os.path.join(os.path.dirname(tmp_file_name), 'cover.jpg')
def cover_processing(tmp_file_path, img, extension):
# tmp_cover_name = os.path.join(os.path.dirname(tmp_file_name), 'cover.jpg')
tmp_cover_name = tmp_file_path + '.jpg'
if extension in NO_JPEG_EXTENSIONS:
if use_IM:
with Image(blob=img) as imgc:
imgc.format = 'jpeg'
imgc.transform_colorspace('rgb')
imgc.transform_colorspace('srgb')
imgc.save(filename=tmp_cover_name)
return tmp_cover_name
else:
+22
View File
@@ -0,0 +1,22 @@
#
# Copyright 2015 Jordan Milne
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Source: https://github.com/JordanMilne/Advocate
from .adapters import ValidatingHTTPAdapter
from .api import *
from .addrvalidator import AddrValidator
from .exceptions import UnacceptableAddressException
+48
View File
@@ -0,0 +1,48 @@
#
# Copyright 2015 Jordan Milne
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Source: https://github.com/JordanMilne/Advocate
from requests.adapters import HTTPAdapter, DEFAULT_POOLBLOCK
from .addrvalidator import AddrValidator
from .exceptions import ProxyDisabledException
from .poolmanager import ValidatingPoolManager
class ValidatingHTTPAdapter(HTTPAdapter):
__attrs__ = HTTPAdapter.__attrs__ + ['_validator']
def __init__(self, *args, **kwargs):
self._validator = kwargs.pop('validator', None)
if not self._validator:
self._validator = AddrValidator()
super().__init__(*args, **kwargs)
def init_poolmanager(self, connections, maxsize, block=DEFAULT_POOLBLOCK,
**pool_kwargs):
self._pool_connections = connections
self._pool_maxsize = maxsize
self._pool_block = block
self.poolmanager = ValidatingPoolManager(
num_pools=connections,
maxsize=maxsize,
block=block,
validator=self._validator,
**pool_kwargs
)
def proxy_manager_for(self, proxy, **proxy_kwargs):
raise ProxyDisabledException("Proxies cannot be used with Advocate")
+281
View File
@@ -0,0 +1,281 @@
#
# Copyright 2015 Jordan Milne
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Source: https://github.com/JordanMilne/Advocate
import functools
import fnmatch
import ipaddress
import re
try:
import netifaces
HAVE_NETIFACES = True
except ImportError:
netifaces = None
HAVE_NETIFACES = False
from .exceptions import NameserverException, ConfigException
def canonicalize_hostname(hostname):
"""Lowercase and punycodify a hostname"""
# We do the lowercasing after IDNA encoding because we only want to
# lowercase the *ASCII* chars.
# TODO: The differences between IDNA2003 and IDNA2008 might be relevant
# to us, but both specs are damn confusing.
return str(hostname.encode("idna").lower(), 'utf-8')
def determine_local_addresses():
"""Get all IPs that refer to this machine according to netifaces"""
if not HAVE_NETIFACES:
raise ConfigException("Tried to determine local addresses, "
"but netifaces module was not importable")
ips = []
for interface in netifaces.interfaces():
if_families = netifaces.ifaddresses(interface)
for family_kind in {netifaces.AF_INET, netifaces.AF_INET6}:
addrs = if_families.get(family_kind, [])
for addr in (x.get("addr", "") for x in addrs):
if family_kind == netifaces.AF_INET6:
# We can't do anything sensible with the scope here
addr = addr.split("%")[0]
ips.append(ipaddress.ip_network(addr))
return ips
def add_local_address_arg(func):
"""Add the "_local_addresses" kwarg if it's missing
IMO this information shouldn't be cached between calls (what if one of the
adapters got a new IP at runtime?,) and we don't want each function to
recalculate it. Just recalculate it if the caller didn't provide it for us.
"""
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
if "_local_addresses" not in kwargs:
if self.autodetect_local_addresses:
kwargs["_local_addresses"] = determine_local_addresses()
else:
kwargs["_local_addresses"] = []
return func(self, *args, **kwargs)
return wrapper
class AddrValidator:
_6TO4_RELAY_NET = ipaddress.ip_network("192.88.99.0/24")
# Just the well known prefix, DNS64 servers can set their own
# prefix, but in practice most probably don't.
_DNS64_WK_PREFIX = ipaddress.ip_network("64:ff9b::/96")
DEFAULT_PORT_WHITELIST = {80, 8080, 443, 8443, 8000}
def __init__(
self,
ip_blacklist=None,
ip_whitelist=None,
port_whitelist=None,
port_blacklist=None,
hostname_blacklist=None,
allow_ipv6=False,
allow_teredo=False,
allow_6to4=False,
allow_dns64=False,
# Must be explicitly set to "False" if you don't want to try
# detecting local interface addresses with netifaces.
autodetect_local_addresses=True,
):
if not port_blacklist and not port_whitelist:
# An assortment of common HTTPS? ports.
port_whitelist = self.DEFAULT_PORT_WHITELIST.copy()
self.ip_blacklist = ip_blacklist or set()
self.ip_whitelist = ip_whitelist or set()
self.port_blacklist = port_blacklist or set()
self.port_whitelist = port_whitelist or set()
# TODO: ATM this can contain either regexes or globs that are converted
# to regexes upon every check. Create a collection that automagically
# converts them to regexes on insert?
self.hostname_blacklist = hostname_blacklist or set()
self.allow_ipv6 = allow_ipv6
self.allow_teredo = allow_teredo
self.allow_6to4 = allow_6to4
self.allow_dns64 = allow_dns64
self.autodetect_local_addresses = autodetect_local_addresses
@add_local_address_arg
def is_ip_allowed(self, addr_ip, _local_addresses=None):
if not isinstance(addr_ip,
(ipaddress.IPv4Address, ipaddress.IPv6Address)):
addr_ip = ipaddress.ip_address(addr_ip)
# The whitelist should take precedence over the blacklist so we can
# punch holes in blacklisted ranges
if any(addr_ip in net for net in self.ip_whitelist):
return True
if any(addr_ip in net for net in self.ip_blacklist):
return False
if any(addr_ip in net for net in _local_addresses):
return False
if addr_ip.version == 4:
if not addr_ip.is_private:
# IPs for carrier-grade NAT. Seems weird that it doesn't set
# `is_private`, but we need to check `not is_global`
if not ipaddress.ip_network(addr_ip).is_global:
return False
elif addr_ip.version == 6:
# You'd better have a good reason for enabling IPv6
# because Advocate's techniques don't work well without NAT.
if not self.allow_ipv6:
return False
# v6 addresses can also map to IPv4 addresses! Tricky!
v4_nested = []
if addr_ip.ipv4_mapped:
v4_nested.append(addr_ip.ipv4_mapped)
# WTF IPv6? Why you gotta have a billion tunneling mechanisms?
# XXX: Do we even really care about these? If we're tunneling
# through public servers we shouldn't be able to access
# addresses on our private network, right?
if addr_ip.sixtofour:
if not self.allow_6to4:
return False
v4_nested.append(addr_ip.sixtofour)
if addr_ip.teredo:
if not self.allow_teredo:
return False
# Check both the client *and* server IPs
v4_nested.extend(addr_ip.teredo)
if addr_ip in self._DNS64_WK_PREFIX:
if not self.allow_dns64:
return False
# When using the well-known prefix the last 4 bytes
# are the IPv4 addr
v4_nested.append(ipaddress.ip_address(addr_ip.packed[-4:]))
if not all(self.is_ip_allowed(addr_v4) for addr_v4 in v4_nested):
return False
# fec0::*, apparently deprecated?
if addr_ip.is_site_local:
return False
else:
raise ValueError("Unsupported IP version(?): %r" % addr_ip)
# 169.254.XXX.XXX, AWS uses these for autoconfiguration
if addr_ip.is_link_local:
return False
# 127.0.0.1, ::1, etc.
if addr_ip.is_loopback:
return False
if addr_ip.is_multicast:
return False
# 192.168.XXX.XXX, 10.XXX.XXX.XXX
if addr_ip.is_private:
return False
# 255.255.255.255, ::ffff:XXXX:XXXX (v6->v4) mapping
if addr_ip.is_reserved:
return False
# There's no reason to connect directly to a 6to4 relay
if addr_ip in self._6TO4_RELAY_NET:
return False
# 0.0.0.0
if addr_ip.is_unspecified:
return False
# It doesn't look bad, so... it's must be ok!
return True
def _hostname_matches_pattern(self, hostname, pattern):
# If they specified a string, just assume they only want basic globbing.
# This stops people from not realizing they're dealing in REs and
# not escaping their periods unless they specifically pass in an RE.
# This has the added benefit of letting us sanely handle globbed
# IDNs by default.
if isinstance(pattern, str):
# convert the glob to a punycode glob, then a regex
pattern = fnmatch.translate(canonicalize_hostname(pattern))
hostname = canonicalize_hostname(hostname)
# Down the line the hostname may get treated as a null-terminated string
# (as with `socket.getaddrinfo`.) Try to account for that.
#
# >>> socket.getaddrinfo("example.com\x00aaaa", 80)
# [(2, 1, 6, '', ('93.184.216.34', 80)), [...]
no_null_hostname = hostname.split("\x00")[0]
return any(re.match(pattern, x.strip(".")) for x
in (no_null_hostname, hostname))
def is_hostname_allowed(self, hostname):
# Sometimes (like with "external" services that your IP has privileged
# access to) you might not always know the IP range to blacklist access
# to, or the `A` record might change without you noticing.
# For e.x.: `foocorp.external.org`.
#
# Another option is doing something like:
#
# for addrinfo in socket.getaddrinfo("foocorp.external.org", 80):
# global_validator.ip_blacklist.add(ip_address(addrinfo[4][0]))
#
# but that's not always a good idea if they're behind a third-party lb.
for pattern in self.hostname_blacklist:
if self._hostname_matches_pattern(hostname, pattern):
return False
return True
@add_local_address_arg
def is_addrinfo_allowed(self, addrinfo, _local_addresses=None):
assert(len(addrinfo) == 5)
# XXX: Do we care about any of the other elements? Guessing not.
family, socktype, proto, canonname, sockaddr = addrinfo
# The 4th elem inaddrinfo may either be a touple of two or four items,
# depending on whether we're dealing with IPv4 or v6
if len(sockaddr) == 2:
# v4
ip, port = sockaddr
elif len(sockaddr) == 4:
# v6
# XXX: what *are* `flow_info` and `scope_id`? Anything useful?
# Seems like we can figure out all we need about the scope from
# the `is_<x>` properties.
ip, port, flow_info, scope_id = sockaddr
else:
raise ValueError("Unexpected addrinfo format %r" % sockaddr)
# Probably won't help protect against SSRF, but might prevent our being
# used to attack others' non-HTTP services. See
# http://www.remote.org/jochen/sec/hfpa/
if self.port_whitelist and port not in self.port_whitelist:
return False
if port in self.port_blacklist:
return False
if self.hostname_blacklist:
if not canonname:
raise NameserverException(
"addrinfo must contain the canon name to do blacklisting "
"based on hostname. Make sure you use the "
"`socket.AI_CANONNAME` flag, and that each record contains "
"the canon name. Your DNS server might also be garbage."
)
if not self.is_hostname_allowed(canonname):
return False
return self.is_ip_allowed(ip, _local_addresses=_local_addresses)
+202
View File
@@ -0,0 +1,202 @@
#
# Copyright 2015 Jordan Milne
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Source: https://github.com/JordanMilne/Advocate
"""
advocate.api
~~~~~~~~~~~~
This module implements the Requests API, largely a copy/paste from `requests`
itself.
:copyright: (c) 2015 by Jordan Milne.
:license: Apache2, see LICENSE for more details.
"""
from collections import OrderedDict
import hashlib
import pickle
from requests import Session as RequestsSession
# import cw_advocate
from .adapters import ValidatingHTTPAdapter
from .exceptions import MountDisabledException
class Session(RequestsSession):
"""Convenience wrapper around `requests.Session` set up for `advocate`ing"""
__attrs__ = RequestsSession.__attrs__ + ["validator"]
DEFAULT_VALIDATOR = None
"""
User-replaceable default validator to use for all Advocate sessions,
includes sessions created by advocate.get()
"""
def __init__(self, *args, **kwargs):
self.validator = kwargs.pop("validator", None) or self.DEFAULT_VALIDATOR
adapter_kwargs = kwargs.pop("_adapter_kwargs", {})
# `Session.__init__()` calls `mount()` internally, so we need to allow
# it temporarily
self.__mount_allowed = True
RequestsSession.__init__(self, *args, **kwargs)
# Drop any existing adapters
self.adapters = OrderedDict()
self.mount("http://", ValidatingHTTPAdapter(validator=self.validator, **adapter_kwargs))
self.mount("https://", ValidatingHTTPAdapter(validator=self.validator, **adapter_kwargs))
self.__mount_allowed = False
def mount(self, *args, **kwargs):
"""Wrapper around `mount()` to prevent a protection bypass"""
if self.__mount_allowed:
super().mount(*args, **kwargs)
else:
raise MountDisabledException(
"mount() is disabled to prevent protection bypasses"
)
def session(*args, **kwargs):
return Session(*args, **kwargs)
def request(method, url, **kwargs):
"""Constructs and sends a :class:`Request <Request>`.
:param method: method for the new :class:`Request` object.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
:param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body of the :class:`Request`.
:param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
:param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
:param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': ('filename', fileobj)}``) for multipart encoding upload.
:param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
:param timeout: (optional) How long to wait for the server to send data
before giving up, as a float, or a (`connect timeout, read timeout
<user/advanced.html#timeouts>`_) tuple.
:type timeout: float or tuple
:param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.
:type allow_redirects: bool
:param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
:param verify: (optional) if ``True``, the SSL cert will be verified. A CA_BUNDLE path can also be provided.
:param stream: (optional) if ``False``, the response content will be immediately downloaded.
:param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
validator = kwargs.pop("validator", None)
with Session(validator=validator) as sess:
response = sess.request(method=method, url=url, **kwargs)
return response
def get(url, **kwargs):
"""Sends a GET request.
:param url: URL for the new :class:`Request` object.
:param **kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
kwargs.setdefault('allow_redirects', True)
return request('get', url, **kwargs)
class RequestsAPIWrapper:
"""Provides a `requests.api`-like interface with a specific validator"""
# Due to how the classes are dynamically constructed pickling may not work
# correctly unless loaded within the same interpreter instance.
# Enable at your peril.
SUPPORT_WRAPPER_PICKLING = False
def __init__(self, validator):
# Do this here to avoid circular import issues
try:
from .futures import FuturesSession
have_requests_futures = True
except ImportError as e:
have_requests_futures = False
self.validator = validator
outer_self = self
class _WrappedSession(Session):
"""An `advocate.Session` that uses the wrapper's blacklist
the wrapper is meant to be a transparent replacement for `requests`,
so people should be able to subclass `wrapper.Session` and still
get the desired validation behaviour
"""
DEFAULT_VALIDATOR = outer_self.validator
self._make_wrapper_cls_global(_WrappedSession)
if have_requests_futures:
class _WrappedFuturesSession(FuturesSession):
"""Like _WrappedSession, but for `FuturesSession`s"""
DEFAULT_VALIDATOR = outer_self.validator
self._make_wrapper_cls_global(_WrappedFuturesSession)
self.FuturesSession = _WrappedFuturesSession
self.request = self._default_arg_wrapper(request)
self.get = self._default_arg_wrapper(get)
self.Session = _WrappedSession
def __getattr__(self, item):
# This class is meant to mimic the requests base module, so if we don't
# have this attribute, it might be on the base module (like the Request
# class, etc.)
try:
return object.__getattribute__(self, item)
except AttributeError:
from . import cw_advocate
return getattr(cw_advocate, item)
def _default_arg_wrapper(self, fun):
def wrapped_func(*args, **kwargs):
kwargs.setdefault("validator", self.validator)
return fun(*args, **kwargs)
return wrapped_func
def _make_wrapper_cls_global(self, cls):
if not self.SUPPORT_WRAPPER_PICKLING:
return
# Gnarly, but necessary to give pickle a consistent module-level
# reference for each wrapper.
wrapper_hash = hashlib.sha256(pickle.dumps(self)).hexdigest()
cls.__name__ = "_".join((cls.__name__, wrapper_hash))
cls.__qualname__ = ".".join((__name__, cls.__name__))
if not globals().get(cls.__name__):
globals()[cls.__name__] = cls
__all__ = (
"get",
"request",
"session",
"Session",
"RequestsAPIWrapper",
)
+201
View File
@@ -0,0 +1,201 @@
#
# Copyright 2015 Jordan Milne
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Source: https://github.com/JordanMilne/Advocate
import ipaddress
import socket
from socket import timeout as SocketTimeout
from urllib3.connection import HTTPSConnection, HTTPConnection
from urllib3.exceptions import ConnectTimeoutError
from urllib3.util.connection import _set_socket_options
from urllib3.util.connection import create_connection as old_create_connection
from . import addrvalidator
from .exceptions import UnacceptableAddressException
def advocate_getaddrinfo(host, port, get_canonname=False):
addrinfo = socket.getaddrinfo(
host,
port,
0,
socket.SOCK_STREAM,
0,
# We need what the DNS client sees the hostname as, correctly handles
# IDNs and tricky things like `private.foocorp.org\x00.google.com`.
# All IDNs will be converted to punycode.
socket.AI_CANONNAME if get_canonname else 0,
)
return fix_addrinfo(addrinfo)
def fix_addrinfo(records):
"""
Propagate the canonname across records and parse IPs
I'm not sure if this is just the behaviour of `getaddrinfo` on Linux, but
it seems like only the first record in the set has the canonname field
populated.
"""
def fix_record(record, canonname):
sa = record[4]
sa = (ipaddress.ip_address(sa[0]),) + sa[1:]
return record[0], record[1], record[2], canonname, sa
canonname = None
if records:
# Apparently the canonical name is only included in the first record?
# Add it to all of them.
assert(len(records[0]) == 5)
canonname = records[0][3]
return tuple(fix_record(x, canonname) for x in records)
# Lifted from requests' urllib3, which in turn lifted it from `socket.py`. Oy!
def validating_create_connection(address,
timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
source_address=None, socket_options=None,
validator=None):
"""Connect to *address* and return the socket object.
Convenience function. Connect to *address* (a 2-tuple ``(host,
port)``) and return the socket object. Passing the optional
*timeout* parameter will set the timeout on the socket instance
before attempting to connect. If no *timeout* is supplied, the
global default timeout setting returned by :func:`getdefaulttimeout`
is used. If *source_address* is set it must be a tuple of (host, port)
for the socket to bind as a source address before making the connection.
An host of '' or port 0 tells the OS to use the default.
"""
host, port = address
# We can skip asking for the canon name if we're not doing hostname-based
# blacklisting.
need_canonname = False
if validator.hostname_blacklist:
need_canonname = True
# We check both the non-canonical and canonical hostnames so we can
# catch both of these:
# CNAME from nonblacklisted.com -> blacklisted.com
# CNAME from blacklisted.com -> nonblacklisted.com
if not validator.is_hostname_allowed(host):
raise UnacceptableAddressException(host)
err = None
addrinfo = advocate_getaddrinfo(host, port, get_canonname=need_canonname)
if addrinfo:
if validator.autodetect_local_addresses:
local_addresses = addrvalidator.determine_local_addresses()
else:
local_addresses = []
for res in addrinfo:
# Are we allowed to connect with this result?
if not validator.is_addrinfo_allowed(
res,
_local_addresses=local_addresses,
):
continue
af, socktype, proto, canonname, sa = res
# Unparse the validated IP
sa = (sa[0].exploded,) + sa[1:]
sock = None
try:
sock = socket.socket(af, socktype, proto)
# If provided, set socket level options before connecting.
# This is the only addition urllib3 makes to this function.
_set_socket_options(sock, socket_options)
if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
sock.settimeout(timeout)
if source_address:
sock.bind(source_address)
sock.connect(sa)
return sock
except socket.error as _:
err = _
if sock is not None:
sock.close()
sock = None
if err is None:
# If we got here, none of the results were acceptable
err = UnacceptableAddressException(address)
if err is not None:
raise err
else:
raise socket.error("getaddrinfo returns an empty list")
# TODO: Is there a better way to add this to multiple classes with different
# base classes? I tried a mixin, but it used the base method instead.
def _validating_new_conn(self):
""" Establish a socket connection and set nodelay settings on it.
:return: New socket connection.
"""
extra_kw = {}
if self.source_address:
extra_kw['source_address'] = self.source_address
if self.socket_options:
extra_kw['socket_options'] = self.socket_options
try:
# Hack around HTTPretty's patched sockets
# TODO: some better method of hacking around it that checks if we
# _would have_ connected to a private addr?
conn_func = validating_create_connection
if socket.getaddrinfo.__module__.startswith("httpretty"):
conn_func = old_create_connection
else:
extra_kw["validator"] = self._validator
conn = conn_func(
(self.host, self.port),
self.timeout,
**extra_kw
)
except SocketTimeout:
raise ConnectTimeoutError(
self, "Connection to %s timed out. (connect timeout=%s)" %
(self.host, self.timeout))
return conn
# Don't silently break if the private API changes across urllib3 versions
assert(hasattr(HTTPConnection, '_new_conn'))
assert(hasattr(HTTPSConnection, '_new_conn'))
class ValidatingHTTPConnection(HTTPConnection):
_new_conn = _validating_new_conn
def __init__(self, *args, **kwargs):
self._validator = kwargs.pop("validator")
HTTPConnection.__init__(self, *args, **kwargs)
class ValidatingHTTPSConnection(HTTPSConnection):
_new_conn = _validating_new_conn
def __init__(self, *args, **kwargs):
self._validator = kwargs.pop("validator")
HTTPSConnection.__init__(self, *args, **kwargs)
+39
View File
@@ -0,0 +1,39 @@
#
# Copyright 2015 Jordan Milne
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Source: https://github.com/JordanMilne/Advocate
from urllib3 import HTTPConnectionPool, HTTPSConnectionPool
from .connection import (
ValidatingHTTPConnection,
ValidatingHTTPSConnection,
)
# Don't silently break if the private API changes across urllib3 versions
assert(hasattr(HTTPConnectionPool, 'ConnectionCls'))
assert(hasattr(HTTPSConnectionPool, 'ConnectionCls'))
assert(hasattr(HTTPConnectionPool, 'scheme'))
assert(hasattr(HTTPSConnectionPool, 'scheme'))
class ValidatingHTTPConnectionPool(HTTPConnectionPool):
scheme = 'http'
ConnectionCls = ValidatingHTTPConnection
class ValidatingHTTPSConnectionPool(HTTPSConnectionPool):
scheme = 'https'
ConnectionCls = ValidatingHTTPSConnection
+39
View File
@@ -0,0 +1,39 @@
#
# Copyright 2015 Jordan Milne
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Source: https://github.com/JordanMilne/Advocate
class AdvocateException(Exception):
pass
class UnacceptableAddressException(AdvocateException):
pass
class NameserverException(AdvocateException):
pass
class MountDisabledException(AdvocateException):
pass
class ProxyDisabledException(NotImplementedError, AdvocateException):
pass
class ConfigException(AdvocateException):
pass
+61
View File
@@ -0,0 +1,61 @@
#
# Copyright 2015 Jordan Milne
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Source: https://github.com/JordanMilne/Advocate
import collections
import functools
from urllib3 import PoolManager
from urllib3.poolmanager import _default_key_normalizer, PoolKey
from .connectionpool import (
ValidatingHTTPSConnectionPool,
ValidatingHTTPConnectionPool,
)
pool_classes_by_scheme = {
"http": ValidatingHTTPConnectionPool,
"https": ValidatingHTTPSConnectionPool,
}
AdvocatePoolKey = collections.namedtuple('AdvocatePoolKey',
PoolKey._fields + ('key_validator',))
def key_normalizer(key_class, request_context):
request_context = request_context.copy()
# TODO: add ability to serialize validator rules to dict,
# allowing pool to be shared between sessions with the same
# rules.
request_context["validator"] = id(request_context["validator"])
return _default_key_normalizer(key_class, request_context)
key_fn_by_scheme = {
'http': functools.partial(key_normalizer, AdvocatePoolKey),
'https': functools.partial(key_normalizer, AdvocatePoolKey),
}
class ValidatingPoolManager(PoolManager):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Make sure the API hasn't changed
assert (hasattr(self, 'pool_classes_by_scheme'))
self.pool_classes_by_scheme = pool_classes_by_scheme
self.key_fn_by_scheme = key_fn_by_scheme.copy()
+3 -2
View File
@@ -2,7 +2,7 @@ from babel import negotiate_locale
from flask_babel import Babel, Locale
from babel.core import UnknownLocaleError
from flask import request
from flask_login import current_user
from .cw_login import current_user
from . import logger
@@ -10,6 +10,7 @@ log = logger.create()
babel = Babel()
def get_locale():
# if a user is logged in, use the locale from the user settings
if current_user is not None and hasattr(current_user, "locale"):
@@ -33,7 +34,7 @@ def get_user_locale_language(user_language):
def get_available_locale():
return [Locale('en')] + babel.list_translations()
return sorted(babel.list_translations(), key=lambda x: x.display_name.lower())
def get_available_translations():
+98
View File
@@ -0,0 +1,98 @@
# from .__about__ import __version__
from .config import AUTH_HEADER_NAME
from .config import COOKIE_DURATION
from .config import COOKIE_HTTPONLY
from .config import COOKIE_NAME
from .config import COOKIE_SECURE
from .config import ID_ATTRIBUTE
from .config import LOGIN_MESSAGE
from .config import LOGIN_MESSAGE_CATEGORY
from .config import REFRESH_MESSAGE
from .config import REFRESH_MESSAGE_CATEGORY
from .login_manager import LoginManager
from .mixins import AnonymousUserMixin
from .mixins import UserMixin
from .signals import session_protected
from .signals import user_accessed
from .signals import user_loaded_from_cookie
from .signals import user_loaded_from_request
from .signals import user_logged_in
from .signals import user_logged_out
from .signals import user_login_confirmed
from .signals import user_needs_refresh
from .signals import user_unauthorized
# from .test_client import FlaskLoginClient
from .utils import confirm_login
from .utils import current_user
from .utils import decode_cookie
from .utils import encode_cookie
from .utils import fresh_login_required
from .utils import login_fresh
from .utils import login_remembered
from .utils import login_required
from .utils import login_url
from .utils import login_user
from .utils import logout_user
from .utils import make_next_param
from .utils import set_login_view
__version_info__ = ("0", "6", "3")
__version__ = ".".join(__version_info__)
__all__ = [
"__version__",
"AUTH_HEADER_NAME",
"COOKIE_DURATION",
"COOKIE_HTTPONLY",
"COOKIE_NAME",
"COOKIE_SECURE",
"ID_ATTRIBUTE",
"LOGIN_MESSAGE",
"LOGIN_MESSAGE_CATEGORY",
"REFRESH_MESSAGE",
"REFRESH_MESSAGE_CATEGORY",
"LoginManager",
"AnonymousUserMixin",
"UserMixin",
"session_protected",
"user_accessed",
"user_loaded_from_cookie",
"user_loaded_from_request",
"user_logged_in",
"user_logged_out",
"user_login_confirmed",
"user_needs_refresh",
"user_unauthorized",
# "FlaskLoginClient",
"confirm_login",
"current_user",
"decode_cookie",
"encode_cookie",
"fresh_login_required",
"login_fresh",
"login_remembered",
"login_required",
"login_url",
"login_user",
"logout_user",
"make_next_param",
"set_login_view",
]
def __getattr__(name):
if name == "user_loaded_from_header":
import warnings
from .signals import _user_loaded_from_header
warnings.warn(
"'user_loaded_from_header' is deprecated and will be"
" removed in Flask-Login 0.7. Use"
" 'user_loaded_from_request' instead.",
DeprecationWarning,
stacklevel=2,
)
return _user_loaded_from_header
raise AttributeError(name)
+55
View File
@@ -0,0 +1,55 @@
from datetime import timedelta
#: The default name of the "remember me" cookie (``remember_token``)
COOKIE_NAME = "remember_token"
#: The default time before the "remember me" cookie expires (365 days).
COOKIE_DURATION = timedelta(days=365)
#: Whether the "remember me" cookie requires Secure; defaults to ``False``
COOKIE_SECURE = False
#: Whether the "remember me" cookie uses HttpOnly or not; defaults to ``True``
COOKIE_HTTPONLY = True
#: Whether the "remember me" cookie requires same origin; defaults to ``None``
COOKIE_SAMESITE = None
#: The default flash message to display when users need to log in.
LOGIN_MESSAGE = "Please log in to access this page."
#: The default flash message category to display when users need to log in.
LOGIN_MESSAGE_CATEGORY = "message"
#: The default flash message to display when users need to reauthenticate.
REFRESH_MESSAGE = "Please reauthenticate to access this page."
#: The default flash message category to display when users need to
#: reauthenticate.
REFRESH_MESSAGE_CATEGORY = "message"
#: The default attribute to retreive the str id of the user
ID_ATTRIBUTE = "get_id"
#: Default name of the auth header (``Authorization``)
AUTH_HEADER_NAME = "Authorization"
#: A set of session keys that are populated by Flask-Login. Use this set to
#: purge keys safely and accurately.
SESSION_KEYS = {
"_user_id",
"_remember",
"_remember_seconds",
"_id",
"_fresh",
"next",
}
#: A set of HTTP methods which are exempt from `login_required` and
#: `fresh_login_required`. By default, this is just ``OPTIONS``.
EXEMPT_METHODS = {"OPTIONS"}
#: If true, the page the user is attempting to access is stored in the session
#: rather than a url parameter when redirecting to the login view; defaults to
#: ``False``.
USE_SESSION_FOR_NEXT = False
+523
View File
@@ -0,0 +1,523 @@
from datetime import datetime
from datetime import timezone
from datetime import timedelta
import hashlib
from flask import abort
from flask import current_app
from flask import flash
from flask import g
from flask import redirect
from flask import request
from flask import session
from itsdangerous import URLSafeSerializer
from flask.json.tag import TaggedJSONSerializer
from .config import AUTH_HEADER_NAME
from .config import COOKIE_DURATION
from .config import COOKIE_HTTPONLY
from .config import COOKIE_NAME
from .config import COOKIE_SAMESITE
from .config import COOKIE_SECURE
from .config import ID_ATTRIBUTE
from .config import LOGIN_MESSAGE
from .config import LOGIN_MESSAGE_CATEGORY
from .config import REFRESH_MESSAGE
from .config import REFRESH_MESSAGE_CATEGORY
from .config import SESSION_KEYS
from .config import USE_SESSION_FOR_NEXT
from .mixins import AnonymousUserMixin
from .signals import session_protected
from .signals import user_accessed
from .signals import user_loaded_from_cookie
from .signals import user_loaded_from_request
from .signals import user_needs_refresh
from .signals import user_unauthorized
from .utils import _create_identifier
from .utils import _user_context_processor
from .utils import confirm_login
from .utils import expand_login_view
from .utils import login_url as make_login_url
from .utils import make_next_param
class LoginManager:
"""This object is used to hold the settings used for logging in. Instances
of :class:`LoginManager` are *not* bound to specific apps, so you can
create one in the main body of your code and then bind it to your
app in a factory function.
"""
def __init__(self, app=None, add_context_processor=True):
#: A class or factory function that produces an anonymous user, which
#: is used when no one is logged in.
self.anonymous_user = AnonymousUserMixin
#: The name of the view to redirect to when the user needs to log in.
#: (This can be an absolute URL as well, if your authentication
#: machinery is external to your application.)
self.login_view = None
#: Names of views to redirect to when the user needs to log in,
#: per blueprint. If the key value is set to None the value of
#: :attr:`login_view` will be used instead.
self.blueprint_login_views = {}
#: The message to flash when a user is redirected to the login page.
self.login_message = LOGIN_MESSAGE
#: The message category to flash when a user is redirected to the login
#: page.
self.login_message_category = LOGIN_MESSAGE_CATEGORY
#: The name of the view to redirect to when the user needs to
#: reauthenticate.
self.refresh_view = None
#: The message to flash when a user is redirected to the 'needs
#: refresh' page.
self.needs_refresh_message = REFRESH_MESSAGE
#: The message category to flash when a user is redirected to the
#: 'needs refresh' page.
self.needs_refresh_message_category = REFRESH_MESSAGE_CATEGORY
#: The mode to use session protection in. This can be either
#: ``'basic'`` (the default) or ``'strong'``, or ``None`` to disable
#: it.
self.session_protection = "basic"
#: If present, used to translate flash messages ``self.login_message``
#: and ``self.needs_refresh_message``
self.localize_callback = None
self.unauthorized_callback = None
self.needs_refresh_callback = None
self.id_attribute = ID_ATTRIBUTE
self._user_callback = None
self._header_callback = None
self._request_callback = None
self._session_identifier_generator = _create_identifier
if app is not None:
self.init_app(app, add_context_processor)
def setup_app(self, app, add_context_processor=True): # pragma: no cover
"""
This method has been deprecated. Please use
:meth:`LoginManager.init_app` instead.
"""
import warnings
warnings.warn(
"'setup_app' is deprecated and will be removed in"
" Flask-Login 0.7. Use 'init_app' instead.",
DeprecationWarning,
stacklevel=2,
)
self.init_app(app, add_context_processor)
def init_app(self, app, add_context_processor=True):
"""
Configures an application. This registers an `after_request` call, and
attaches this `LoginManager` to it as `app.login_manager`.
:param app: The :class:`flask.Flask` object to configure.
:type app: :class:`flask.Flask`
:param add_context_processor: Whether to add a context processor to
the app that adds a `current_user` variable to the template.
Defaults to ``True``.
:type add_context_processor: bool
"""
app.login_manager = self
app.after_request(self._update_remember_cookie)
if add_context_processor:
app.context_processor(_user_context_processor)
def unauthorized(self):
"""
This is called when the user is required to log in. If you register a
callback with :meth:`LoginManager.unauthorized_handler`, then it will
be called. Otherwise, it will take the following actions:
- Flash :attr:`LoginManager.login_message` to the user.
- If the app is using blueprints find the login view for
the current blueprint using `blueprint_login_views`. If the app
is not using blueprints or the login view for the current
blueprint is not specified use the value of `login_view`.
- Redirect the user to the login view. (The page they were
attempting to access will be passed in the ``next`` query
string variable, so you can redirect there if present instead
of the homepage. Alternatively, it will be added to the session
as ``next`` if USE_SESSION_FOR_NEXT is set.)
If :attr:`LoginManager.login_view` is not defined, then it will simply
raise a HTTP 401 (Unauthorized) error instead.
This should be returned from a view or before/after_request function,
otherwise the redirect will have no effect.
"""
user_unauthorized.send(current_app._get_current_object())
if self.unauthorized_callback:
return self.unauthorized_callback()
if request.blueprint in self.blueprint_login_views:
login_view = self.blueprint_login_views[request.blueprint]
else:
login_view = self.login_view
if not login_view:
abort(401)
if self.login_message:
if self.localize_callback is not None:
flash(
self.localize_callback(self.login_message),
category=self.login_message_category,
)
else:
flash(self.login_message, category=self.login_message_category)
config = current_app.config
if config.get("USE_SESSION_FOR_NEXT", USE_SESSION_FOR_NEXT):
login_url = expand_login_view(login_view)
session["_id"] = self._session_identifier_generator()
session["next"] = make_next_param(login_url, request.url)
redirect_url = make_login_url(login_view)
else:
redirect_url = make_login_url(login_view, next_url=request.url)
return redirect(redirect_url)
def user_loader(self, callback):
"""
This sets the callback for reloading a user from the session. The
function you set should take a user ID (a ``str``) and return a
user object, or ``None`` if the user does not exist.
:param callback: The callback for retrieving a user object.
:type callback: callable
"""
self._user_callback = callback
return self.user_callback
@property
def user_callback(self):
"""Gets the user_loader callback set by user_loader decorator."""
return self._user_callback
def request_loader(self, callback):
"""
This sets the callback for loading a user from a Flask request.
The function you set should take Flask request object and
return a user object, or `None` if the user does not exist.
:param callback: The callback for retrieving a user object.
:type callback: callable
"""
self._request_callback = callback
return self.request_callback
@property
def request_callback(self):
"""Gets the request_loader callback set by request_loader decorator."""
return self._request_callback
def unauthorized_handler(self, callback):
"""
This will set the callback for the `unauthorized` method, which among
other things is used by `login_required`. It takes no arguments, and
should return a response to be sent to the user instead of their
normal view.
:param callback: The callback for unauthorized users.
:type callback: callable
"""
self.unauthorized_callback = callback
return callback
def needs_refresh_handler(self, callback):
"""
This will set the callback for the `needs_refresh` method, which among
other things is used by `fresh_login_required`. It takes no arguments,
and should return a response to be sent to the user instead of their
normal view.
:param callback: The callback for unauthorized users.
:type callback: callable
"""
self.needs_refresh_callback = callback
return callback
def needs_refresh(self):
"""
This is called when the user is logged in, but they need to be
reauthenticated because their session is stale. If you register a
callback with `needs_refresh_handler`, then it will be called.
Otherwise, it will take the following actions:
- Flash :attr:`LoginManager.needs_refresh_message` to the user.
- Redirect the user to :attr:`LoginManager.refresh_view`. (The page
they were attempting to access will be passed in the ``next``
query string variable, so you can redirect there if present
instead of the homepage.)
If :attr:`LoginManager.refresh_view` is not defined, then it will
simply raise a HTTP 401 (Unauthorized) error instead.
This should be returned from a view or before/after_request function,
otherwise the redirect will have no effect.
"""
user_needs_refresh.send(current_app._get_current_object())
if self.needs_refresh_callback:
return self.needs_refresh_callback()
if not self.refresh_view:
abort(401)
if self.needs_refresh_message:
if self.localize_callback is not None:
flash(
self.localize_callback(self.needs_refresh_message),
category=self.needs_refresh_message_category,
)
else:
flash(
self.needs_refresh_message,
category=self.needs_refresh_message_category,
)
config = current_app.config
if config.get("USE_SESSION_FOR_NEXT", USE_SESSION_FOR_NEXT):
login_url = expand_login_view(self.refresh_view)
session["_id"] = self._session_identifier_generator()
session["next"] = make_next_param(login_url, request.url)
redirect_url = make_login_url(self.refresh_view)
else:
login_url = self.refresh_view
redirect_url = make_login_url(login_url, next_url=request.url)
return redirect(redirect_url)
def _update_request_context_with_user(self, user=None):
"""Store the given user as ctx.user."""
if user is None:
user = self.anonymous_user()
g._login_user = user
def _load_user(self):
"""Loads user from session or remember_me cookie as applicable"""
if self._user_callback is None and self._request_callback is None:
raise Exception(
"Missing user_loader or request_loader. Refer to "
"https://flask-login.readthedocs.io/#how-it-works "
"for more info."
)
user_accessed.send(current_app._get_current_object())
# Check SESSION_PROTECTION
if self._session_protection_failed():
return self._update_request_context_with_user()
user = None
# Load user from Flask Session
user_id = session.get("_user_id")
user_random = session.get("_random")
user_session_key = session.get("_id")
if (user_id is not None
and user_random is not None
and user_session_key is not None
and self._user_callback is not None):
user = self._user_callback(user_id, user_random, user_session_key)
# Load user from Remember Me Cookie or Request Loader
if user is None:
config = current_app.config
cookie_name = config.get("REMEMBER_COOKIE_NAME", COOKIE_NAME)
header_name = config.get("AUTH_HEADER_NAME", AUTH_HEADER_NAME)
has_cookie = (
cookie_name in request.cookies and session.get("_remember") != "clear"
)
if has_cookie:
cookie = request.cookies[cookie_name]
user = self._load_user_from_remember_cookie(cookie)
elif self._request_callback:
user = self._load_user_from_request(request)
elif header_name in request.headers:
header = request.headers[header_name]
user = self._load_user_from_header(header)
if not user:
self._update_request_context_with_user()
return self._update_request_context_with_user(user)
def _session_protection_failed(self):
sess = session._get_current_object()
ident = self._session_identifier_generator()
app = current_app._get_current_object()
mode = app.config.get("SESSION_PROTECTION", self.session_protection)
if not mode or mode not in ["basic", "strong"]:
return False
# if the sess is empty, it's an anonymous user or just logged out
# so we can skip this
if sess and ident != sess.get("_id", None):
if mode == "basic" or sess.permanent:
if sess.get("_fresh") is not False:
sess["_fresh"] = False
session_protected.send(app)
return False
elif mode == "strong":
for k in SESSION_KEYS:
sess.pop(k, None)
sess["_remember"] = "clear"
session_protected.send(app)
return True
return False
def _load_user_from_remember_cookie(self, cookie):
signer_kwargs = dict(
key_derivation="hmac", digest_method=hashlib.sha1
)
try:
remember_dict = URLSafeSerializer(
current_app.secret_key,
salt="remember",
serializer=TaggedJSONSerializer(),
signer_kwargs=signer_kwargs,
).loads(cookie)
except Exception:
return None
if remember_dict['user'] is not None:
session["_user_id"] = remember_dict['user']
if "_random" not in session:
session["_random"] = remember_dict['random']
session["_fresh"] = False
user = None
if self._user_callback:
user = self._user_callback(remember_dict['user'], session["_random"], None)
if user is not None:
app = current_app._get_current_object()
user_loaded_from_cookie.send(app, user=user)
# if session was restored from remember me cookie make login valid
confirm_login()
return user
return None
def _load_user_from_header(self, header):
if self._header_callback:
user = self._header_callback(header)
if user is not None:
app = current_app._get_current_object()
from .signals import _user_loaded_from_header
_user_loaded_from_header.send(app, user=user)
return user
return None
def _load_user_from_request(self, request):
if self._request_callback:
user = self._request_callback(request)
if user is not None:
app = current_app._get_current_object()
user_loaded_from_request.send(app, user=user)
return user
return None
def _update_remember_cookie(self, response):
# Don't modify the session unless there's something to do.
if "_remember" not in session and current_app.config.get(
"REMEMBER_COOKIE_REFRESH_EACH_REQUEST"
):
session["_remember"] = "set"
if "_remember" in session:
operation = session.pop("_remember", None)
if operation == "set" and "_user_id" in session:
self._set_cookie(response)
elif operation == "clear":
self._clear_cookie(response)
return response
def _set_cookie(self, response):
# cookie settings
config = current_app.config
cookie_name = config.get("REMEMBER_COOKIE_NAME", COOKIE_NAME)
domain = config.get("REMEMBER_COOKIE_DOMAIN")
path = config.get("REMEMBER_COOKIE_PATH", current_app.wsgi_app.script_name)
secure = config.get("REMEMBER_COOKIE_SECURE", COOKIE_SECURE)
httponly = config.get("REMEMBER_COOKIE_HTTPONLY", COOKIE_HTTPONLY)
samesite = config.get("REMEMBER_COOKIE_SAMESITE", COOKIE_SAMESITE)
if "_remember_seconds" in session:
duration = timedelta(seconds=session["_remember_seconds"])
else:
duration = config.get("REMEMBER_COOKIE_DURATION", COOKIE_DURATION)
# prepare data
max_age = int(current_app.permanent_session_lifetime.total_seconds())
signer_kwargs = dict(
key_derivation="hmac", digest_method=hashlib.sha1
)
# save
data = URLSafeSerializer(
current_app.secret_key,
salt="remember",
serializer=TaggedJSONSerializer(),
signer_kwargs=signer_kwargs,
).dumps({"user":session["_user_id"], "random":session["_random"]})
if isinstance(duration, int):
duration = timedelta(seconds=duration)
try:
expires = datetime.now(timezone.utc) + duration
except TypeError as e:
raise Exception(
"REMEMBER_COOKIE_DURATION must be a datetime.timedelta,"
f" instead got: {duration}"
) from e
# actually set it
response.set_cookie(
cookie_name,
value=data,
expires=expires,
domain=domain,
path=path,
secure=secure,
httponly=httponly,
samesite=samesite,
)
def _clear_cookie(self, response):
config = current_app.config
cookie_name = config.get("REMEMBER_COOKIE_NAME", COOKIE_NAME)
domain = config.get("REMEMBER_COOKIE_DOMAIN")
path = config.get("REMEMBER_COOKIE_PATH", current_app.wsgi_app.script_name)
response.delete_cookie(cookie_name, domain=domain, path=path)
+65
View File
@@ -0,0 +1,65 @@
class UserMixin:
"""
This provides default implementations for the methods that Flask-Login
expects user objects to have.
"""
# Python 3 implicitly set __hash__ to None if we override __eq__
# We set it back to its default implementation
__hash__ = object.__hash__
@property
def is_active(self):
return True
@property
def is_authenticated(self):
return self.is_active
@property
def is_anonymous(self):
return False
def get_id(self):
try:
return str(self.id)
except AttributeError:
raise NotImplementedError("No `id` attribute - override `get_id`") from None
def __eq__(self, other):
"""
Checks the equality of two `UserMixin` objects using `get_id`.
"""
if isinstance(other, UserMixin):
return self.get_id() == other.get_id()
return NotImplemented
def __ne__(self, other):
"""
Checks the inequality of two `UserMixin` objects using `get_id`.
"""
equal = self.__eq__(other)
if equal is NotImplemented:
return NotImplemented
return not equal
class AnonymousUserMixin:
"""
This is the default object for representing an anonymous user.
"""
@property
def is_authenticated(self):
return False
@property
def is_active(self):
return False
@property
def is_anonymous(self):
return True
def get_id(self):
return
+61
View File
@@ -0,0 +1,61 @@
from flask.signals import Namespace
_signals = Namespace()
#: Sent when a user is logged in. In addition to the app (which is the
#: sender), it is passed `user`, which is the user being logged in.
user_logged_in = _signals.signal("logged-in")
#: Sent when a user is logged out. In addition to the app (which is the
#: sender), it is passed `user`, which is the user being logged out.
user_logged_out = _signals.signal("logged-out")
#: Sent when the user is loaded from the cookie. In addition to the app (which
#: is the sender), it is passed `user`, which is the user being reloaded.
user_loaded_from_cookie = _signals.signal("loaded-from-cookie")
#: Sent when the user is loaded from the header. In addition to the app (which
#: is the #: sender), it is passed `user`, which is the user being reloaded.
_user_loaded_from_header = _signals.signal("loaded-from-header")
#: Sent when the user is loaded from the request. In addition to the app (which
#: is the #: sender), it is passed `user`, which is the user being reloaded.
user_loaded_from_request = _signals.signal("loaded-from-request")
#: Sent when a user's login is confirmed, marking it as fresh. (It is not
#: called for a normal login.)
#: It receives no additional arguments besides the app.
user_login_confirmed = _signals.signal("login-confirmed")
#: Sent when the `unauthorized` method is called on a `LoginManager`. It
#: receives no additional arguments besides the app.
user_unauthorized = _signals.signal("unauthorized")
#: Sent when the `needs_refresh` method is called on a `LoginManager`. It
#: receives no additional arguments besides the app.
user_needs_refresh = _signals.signal("needs-refresh")
#: Sent whenever the user is accessed/loaded
#: receives no additional arguments besides the app.
user_accessed = _signals.signal("accessed")
#: Sent whenever session protection takes effect, and a session is either
#: marked non-fresh or deleted. It receives no additional arguments besides
#: the app.
session_protected = _signals.signal("session-protected")
def __getattr__(name):
if name == "user_loaded_from_header":
import warnings
warnings.warn(
"'user_loaded_from_header' is deprecated and will be"
" removed in Flask-Login 0.7. Use"
" 'user_loaded_from_request' instead.",
DeprecationWarning,
stacklevel=2,
)
return _user_loaded_from_header
raise AttributeError(name)
+424
View File
@@ -0,0 +1,424 @@
import hmac
import os
from functools import wraps
from hashlib import sha512
from urllib.parse import parse_qs
from urllib.parse import urlencode
from urllib.parse import urlsplit
from urllib.parse import urlunsplit
from flask import current_app
from flask import g
from flask import has_request_context
from flask import request
from flask import session
from flask import url_for
from werkzeug.local import LocalProxy
from .config import COOKIE_NAME
from .config import EXEMPT_METHODS
from .signals import user_logged_in
from .signals import user_logged_out
from .signals import user_login_confirmed
#: A proxy for the current user. If no user is logged in, this will be an
#: anonymous user
current_user = LocalProxy(lambda: _get_user())
def encode_cookie(payload, key=None):
"""
This will encode a ``str`` value into a cookie, and sign that cookie
with the app's secret key.
:param payload: The value to encode, as `str`.
:type payload: str
:param key: The key to use when creating the cookie digest. If not
specified, the SECRET_KEY value from app config will be used.
:type key: str
"""
return f"{payload}|{_cookie_digest(payload, key=key)}"
def decode_cookie(cookie, key=None):
"""
This decodes a cookie given by `encode_cookie`. If verification of the
cookie fails, ``None`` will be implicitly returned.
:param cookie: An encoded cookie.
:type cookie: str
:param key: The key to use when creating the cookie digest. If not
specified, the SECRET_KEY value from app config will be used.
:type key: str
"""
try:
payload, digest = cookie.rsplit("|", 1)
if hasattr(digest, "decode"):
digest = digest.decode("ascii") # pragma: no cover
except ValueError:
return
if hmac.compare_digest(_cookie_digest(payload, key=key), digest):
return payload
def make_next_param(login_url, current_url):
"""
Reduces the scheme and host from a given URL so it can be passed to
the given `login` URL more efficiently.
:param login_url: The login URL being redirected to.
:type login_url: str
:param current_url: The URL to reduce.
:type current_url: str
"""
l_url = urlsplit(login_url)
c_url = urlsplit(current_url)
if (not l_url.scheme or l_url.scheme == c_url.scheme) and (
not l_url.netloc or l_url.netloc == c_url.netloc
):
return urlunsplit(("", "", c_url.path, c_url.query, ""))
return current_url
def expand_login_view(login_view):
"""
Returns the url for the login view, expanding the view name to a url if
needed.
:param login_view: The name of the login view or a URL for the login view.
:type login_view: str
"""
if login_view.startswith(("https://", "http://", "/")):
return login_view
return url_for(login_view)
def login_url(login_view, next_url=None, next_field="next"):
"""
Creates a URL for redirecting to a login page. If only `login_view` is
provided, this will just return the URL for it. If `next_url` is provided,
however, this will append a ``next=URL`` parameter to the query string
so that the login view can redirect back to that URL. Flask-Login's default
unauthorized handler uses this function when redirecting to your login url.
To force the host name used, set `FORCE_HOST_FOR_REDIRECTS` to a host. This
prevents from redirecting to external sites if request headers Host or
X-Forwarded-For are present.
:param login_view: The name of the login view. (Alternately, the actual
URL to the login view.)
:type login_view: str
:param next_url: The URL to give the login view for redirection.
:type next_url: str
:param next_field: What field to store the next URL in. (It defaults to
``next``.)
:type next_field: str
"""
base = expand_login_view(login_view)
if next_url is None:
return base
parsed_result = urlsplit(base)
md = parse_qs(parsed_result.query, keep_blank_values=True)
md[next_field] = make_next_param(base, next_url)
netloc = current_app.config.get("FORCE_HOST_FOR_REDIRECTS") or parsed_result.netloc
parsed_result = parsed_result._replace(
netloc=netloc, query=urlencode(md, doseq=True)
)
return urlunsplit(parsed_result)
def login_fresh():
"""
This returns ``True`` if the current login is fresh.
"""
return session.get("_fresh", False)
def login_remembered():
"""
This returns ``True`` if the current login is remembered across sessions.
"""
config = current_app.config
cookie_name = config.get("REMEMBER_COOKIE_NAME", COOKIE_NAME)
has_cookie = cookie_name in request.cookies and session.get("_remember") != "clear"
if has_cookie:
cookie = request.cookies[cookie_name]
user_id = decode_cookie(cookie)
return user_id is not None
return False
def login_user(user, remember=False, duration=None, force=False, fresh=True):
"""
Logs a user in. You should pass the actual user object to this. If the
user's `is_active` property is ``False``, they will not be logged in
unless `force` is ``True``.
This will return ``True`` if the log in attempt succeeds, and ``False`` if
it fails (i.e. because the user is inactive).
:param user: The user object to log in.
:type user: object
:param remember: Whether to remember the user after their session expires.
Defaults to ``False``.
:type remember: bool
:param duration: The amount of time before the remember cookie expires. If
``None`` the value set in the settings is used. Defaults to ``None``.
:type duration: :class:`datetime.timedelta`
:param force: If the user is inactive, setting this to ``True`` will log
them in regardless. Defaults to ``False``.
:type force: bool
:param fresh: setting this to ``False`` will log in the user with a session
marked as not "fresh". Defaults to ``True``.
:type fresh: bool
"""
if not force and not user.is_active:
return False
user_id = getattr(user, current_app.login_manager.id_attribute)()
session["_user_id"] = user_id
session["_fresh"] = fresh
session["_id"] = current_app.login_manager._session_identifier_generator()
session["_random"] = os.urandom(10).hex()
if remember:
session["_remember"] = "set"
if duration is not None:
try:
# equal to timedelta.total_seconds() but works with Python 2.6
session["_remember_seconds"] = (
duration.microseconds
+ (duration.seconds + duration.days * 24 * 3600) * 10**6
) / 10.0**6
except AttributeError as e:
raise Exception(
f"duration must be a datetime.timedelta, instead got: {duration}"
) from e
current_app.login_manager._update_request_context_with_user(user)
user_logged_in.send(current_app._get_current_object(), user=_get_user())
return True
def logout_user():
"""
Logs a user out. (You do not need to pass the actual user.) This will
also clean up the remember me cookie if it exists.
"""
user = _get_user()
if "_user_id" in session:
session.pop("_user_id")
if "_fresh" in session:
session.pop("_fresh")
if "_id" in session:
session.pop("_id")
if "_random" in session:
session.pop("_random")
cookie_name = current_app.config.get("REMEMBER_COOKIE_NAME", COOKIE_NAME)
if cookie_name in request.cookies:
session["_remember"] = "clear"
if "_remember_seconds" in session:
session.pop("_remember_seconds")
user_logged_out.send(current_app._get_current_object(), user=user)
current_app.login_manager._update_request_context_with_user()
return True
def confirm_login():
"""
This sets the current session as fresh. Sessions become stale when they
are reloaded from a cookie.
"""
session["_fresh"] = True
session["_id"] = current_app.login_manager._session_identifier_generator()
user_login_confirmed.send(current_app._get_current_object())
def login_required(func):
"""
If you decorate a view with this, it will ensure that the current user is
logged in and authenticated before calling the actual view. (If they are
not, it calls the :attr:`LoginManager.unauthorized` callback.) For
example::
@app.route('/post')
@user_login_required
def post():
pass
If there are only certain times you need to require that your user is
logged in, you can do so with::
if not current_user.is_authenticated:
return current_app.login_manager.unauthorized()
...which is essentially the code that this function adds to your views.
It can be convenient to globally turn off authentication when unit testing.
To enable this, if the application configuration variable `LOGIN_DISABLED`
is set to `True`, this decorator will be ignored.
.. Note ::
Per `W3 guidelines for CORS preflight requests
<http://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0>`_,
HTTP ``OPTIONS`` requests are exempt from login checks.
:param func: The view function to decorate.
:type func: function
"""
@wraps(func)
def decorated_view(*args, **kwargs):
if request.method in EXEMPT_METHODS or current_app.config.get("LOGIN_DISABLED"):
pass
elif not current_user.is_authenticated:
return current_app.login_manager.unauthorized()
# flask 1.x compatibility
# current_app.ensure_sync is only available in Flask >= 2.0
if callable(getattr(current_app, "ensure_sync", None)):
return current_app.ensure_sync(func)(*args, **kwargs)
return func(*args, **kwargs)
return decorated_view
def fresh_login_required(func):
"""
If you decorate a view with this, it will ensure that the current user's
login is fresh - i.e. their session was not restored from a 'remember me'
cookie. Sensitive operations, like changing a password or e-mail, should
be protected with this, to impede the efforts of cookie thieves.
If the user is not authenticated, :meth:`LoginManager.unauthorized` is
called as normal. If they are authenticated, but their session is not
fresh, it will call :meth:`LoginManager.needs_refresh` instead. (In that
case, you will need to provide a :attr:`LoginManager.refresh_view`.)
Behaves identically to the :func:`login_required` decorator with respect
to configuration variables.
.. Note ::
Per `W3 guidelines for CORS preflight requests
<http://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0>`_,
HTTP ``OPTIONS`` requests are exempt from login checks.
:param func: The view function to decorate.
:type func: function
"""
@wraps(func)
def decorated_view(*args, **kwargs):
if request.method in EXEMPT_METHODS or current_app.config.get("LOGIN_DISABLED"):
pass
elif not current_user.is_authenticated:
return current_app.login_manager.unauthorized()
elif not login_fresh():
return current_app.login_manager.needs_refresh()
try:
# current_app.ensure_sync available in Flask >= 2.0
return current_app.ensure_sync(func)(*args, **kwargs)
except AttributeError: # pragma: no cover
return func(*args, **kwargs)
return decorated_view
def set_login_view(login_view, blueprint=None):
"""
Sets the login view for the app or blueprint. If a blueprint is passed,
the login view is set for this blueprint on ``blueprint_login_views``.
:param login_view: The user object to log in.
:type login_view: str
:param blueprint: The blueprint which this login view should be set on.
Defaults to ``None``.
:type blueprint: object
"""
num_login_views = len(current_app.login_manager.blueprint_login_views)
if blueprint is not None or num_login_views != 0:
(current_app.login_manager.blueprint_login_views[blueprint.name]) = login_view
if (
current_app.login_manager.login_view is not None
and None not in current_app.login_manager.blueprint_login_views
):
(
current_app.login_manager.blueprint_login_views[None]
) = current_app.login_manager.login_view
current_app.login_manager.login_view = None
else:
current_app.login_manager.login_view = login_view
def _get_user():
if has_request_context():
if "flask_httpauth_user" in g:
if g.flask_httpauth_user is not None:
return g.flask_httpauth_user
if "_login_user" not in g:
current_app.login_manager._load_user()
return g._login_user
return None
def _cookie_digest(payload, key=None):
key = _secret_key(key)
return hmac.new(key, payload.encode("utf-8"), sha512).hexdigest()
def _get_remote_addr():
address = request.headers.get("X-Forwarded-For", request.remote_addr)
if address is not None:
# An 'X-Forwarded-For' header includes a comma separated list of the
# addresses, the first address being the actual remote address.
address = address.encode("utf-8").split(b",")[0].strip()
return address
def _create_identifier():
user_agent = request.headers.get("User-Agent")
if user_agent is not None:
user_agent = user_agent.encode("utf-8")
base = f"{_get_remote_addr()}|{user_agent}"
if str is bytes:
base = str(base, "utf-8", errors="replace") # pragma: no cover
h = sha512()
h.update(base.encode("utf8"))
return h.hexdigest()
def _user_context_processor():
return dict(current_user=_get_user())
def _secret_key(key=None):
if key is None:
key = current_app.config["SECRET_KEY"]
if isinstance(key, str): # pragma: no cover
key = key.encode("latin1") # ensure bytes
return key
+301 -165
View File
@@ -20,15 +20,17 @@
import os
import re
import json
from datetime import datetime
from datetime import datetime, timezone
from urllib.parse import quote
import unidecode
# from weakref import WeakSet
from uuid import uuid4
from sqlite3 import OperationalError as sqliteOperationalError
from sqlalchemy import create_engine
from sqlalchemy import Table, Column, ForeignKey, CheckConstraint
from sqlalchemy import String, Integer, Boolean, TIMESTAMP, Float
from sqlalchemy.orm import relationship, sessionmaker, scoped_session
from sqlalchemy.orm import relationship, sessionmaker, scoped_session, selectinload
from sqlalchemy.orm.collections import InstrumentedList
from sqlalchemy.ext.declarative import DeclarativeMeta
from sqlalchemy.exc import OperationalError
@@ -40,16 +42,14 @@ except ImportError:
from sqlalchemy.pool import StaticPool
from sqlalchemy.sql.expression import and_, true, false, text, func, or_
from sqlalchemy.ext.associationproxy import association_proxy
from flask_login import current_user
from .cw_login import current_user
from flask_babel import gettext as _
from flask_babel import get_locale
from flask import flash
from flask import flash, g, Flask
from . import logger, ub, isoLanguages
from .pagination import Pagination
from weakref import WeakSet
from .string_helper import strip_whitespaces
log = logger.create()
@@ -102,8 +102,19 @@ class Identifiers(Base):
type = Column(String(collation='NOCASE'), nullable=False, default="isbn")
val = Column(String(collation='NOCASE'), nullable=False)
book = Column(Integer, ForeignKey('books.id'), nullable=False)
amazon = {
"jp": "co.jp",
"uk": "co.uk",
"us": "com",
"au": "com.au",
"be": "com.be",
"br": "com.br",
"tr": "com.tr",
"mx": "com.mx",
}
def __init__(self, val, id_type, book):
super().__init__()
self.val = val
self.type = id_type
self.book = book
@@ -113,7 +124,11 @@ class Identifiers(Base):
if format_type == 'amazon':
return "Amazon"
elif format_type.startswith("amazon_"):
return "Amazon.{0}".format(format_type[7:])
label_amazon = "Amazon.{0}"
country_code = format_type[7:].lower()
if country_code not in self.amazon:
return label_amazon.format(country_code)
return label_amazon.format(self.amazon[country_code])
elif format_type == "isbn":
return "ISBN"
elif format_type == "doi":
@@ -128,12 +143,20 @@ class Identifiers(Base):
return "Google Books"
elif format_type == "kobo":
return "Kobo"
elif format_type == "barnesnoble":
return "Barnes & Noble"
elif format_type == "litres":
return "ЛитРес"
elif format_type == "issn":
return "ISSN"
elif format_type == "isfdb":
return "ISFDB"
elif format_type == "storygraph":
return "StoryGraph"
elif format_type == "ebooks":
return "eBooks.com"
elif format_type == "smashwords":
return "Smashwords"
if format_type == "lubimyczytac":
return "Lubimyczytac"
if format_type == "databazeknih":
@@ -146,7 +169,11 @@ class Identifiers(Base):
if format_type == "amazon" or format_type == "asin":
return "https://amazon.com/dp/{0}".format(self.val)
elif format_type.startswith('amazon_'):
return "https://amazon.{0}/dp/{1}".format(format_type[7:], self.val)
link_amazon = "https://amazon.{0}/dp/{1}"
country_code = format_type[7:].lower()
if country_code not in self.amazon:
return link_amazon.format(country_code, self.val)
return link_amazon.format(self.amazon[country_code], self.val)
elif format_type == "isbn":
return "https://www.worldcat.org/isbn/{0}".format(self.val)
elif format_type == "doi":
@@ -161,6 +188,8 @@ class Identifiers(Base):
return "https://books.google.com/books?id={0}".format(self.val)
elif format_type == "kobo":
return "https://www.kobo.com/ebook/{0}".format(self.val)
elif format_type == "barnesnoble":
return "https://www.barnesandnoble.com/w/{0}".format(self.val)
elif format_type == "lubimyczytac":
return "https://lubimyczytac.pl/ksiazka/{0}/ksiazka".format(self.val)
elif format_type == "litres":
@@ -168,11 +197,20 @@ class Identifiers(Base):
elif format_type == "issn":
return "https://portal.issn.org/resource/ISSN/{0}".format(self.val)
elif format_type == "isfdb":
return "http://www.isfdb.org/cgi-bin/pl.cgi?{0}".format(self.val)
return "https://www.isfdb.org/cgi-bin/pl.cgi?{0}".format(self.val)
elif format_type == "databazeknih":
return "https://www.databazeknih.cz/knihy/{0}".format(self.val)
elif format_type == "storygraph":
return "https://app.thestorygraph.com/books/{0}".format(self.val)
elif format_type == "ebooks":
return "https://www.ebooks.com/en-us/book/{0}".format(self.val)
elif format_type == "smashwords":
return "https://www.smashwords.com/books/view/{0}".format(self.val)
elif self.val.lower().startswith("javascript:"):
return quote(self.val)
elif self.val.lower().startswith("data:"):
link, __, __ = str.partition(self.val, ",")
return link
else:
return "{0}".format(self.val)
@@ -185,6 +223,7 @@ class Comments(Base):
text = Column(String(collation='NOCASE'), nullable=False)
def __init__(self, comment, book):
super().__init__()
self.text = comment
self.book = book
@@ -202,11 +241,15 @@ class Tags(Base):
name = Column(String(collation='NOCASE'), unique=True, nullable=False)
def __init__(self, name):
super().__init__()
self.name = name
def get(self):
return self.name
def __eq__(self, other):
return self.name == other
def __repr__(self):
return "<Tags('{0})>".format(self.name)
@@ -219,7 +262,8 @@ class Authors(Base):
sort = Column(String(collation='NOCASE'))
link = Column(String, nullable=False, default="")
def __init__(self, name, sort, link):
def __init__(self, name, sort, link=""):
super().__init__()
self.name = name
self.sort = sort
self.link = link
@@ -227,6 +271,9 @@ class Authors(Base):
def get(self):
return self.name
def __eq__(self, other):
return self.name == other
def __repr__(self):
return "<Authors('{0},{1}{2}')>".format(self.name, self.sort, self.link)
@@ -239,12 +286,16 @@ class Series(Base):
sort = Column(String(collation='NOCASE'))
def __init__(self, name, sort):
super().__init__()
self.name = name
self.sort = sort
def get(self):
return self.name
def __eq__(self, other):
return self.name == other
def __repr__(self):
return "<Series('{0},{1}')>".format(self.name, self.sort)
@@ -256,11 +307,15 @@ class Ratings(Base):
rating = Column(Integer, CheckConstraint('rating>-1 AND rating<11'), unique=True)
def __init__(self, rating):
super().__init__()
self.rating = rating
def get(self):
return self.rating
def __eq__(self, other):
return self.rating == other
def __repr__(self):
return "<Ratings('{0}')>".format(self.rating)
@@ -272,14 +327,18 @@ class Languages(Base):
lang_code = Column(String(collation='NOCASE'), nullable=False, unique=True)
def __init__(self, lang_code):
super().__init__()
self.lang_code = lang_code
def get(self):
if self.language_name:
if hasattr(self, "language_name"):
return self.language_name
else:
return self.lang_code
def __eq__(self, other):
return self.lang_code == other
def __repr__(self):
return "<Languages('{0}')>".format(self.lang_code)
@@ -292,12 +351,16 @@ class Publishers(Base):
sort = Column(String(collation='NOCASE'))
def __init__(self, name, sort):
super().__init__()
self.name = name
self.sort = sort
def get(self):
return self.name
def __eq__(self, other):
return self.name == other
def __repr__(self):
return "<Publishers('{0},{1}')>".format(self.name, self.sort)
@@ -313,6 +376,7 @@ class Data(Base):
name = Column(String, nullable=False)
def __init__(self, book, book_format, uncompressed_size, name):
super().__init__()
self.book = book
self.format = book_format
self.uncompressed_size = uncompressed_size
@@ -332,6 +396,7 @@ class Metadata_Dirtied(Base):
book = Column(Integer, ForeignKey('books.id'), nullable=False, unique=True)
def __init__(self, book):
super().__init__()
self.book = book
@@ -344,15 +409,15 @@ class Books(Base):
title = Column(String(collation='NOCASE'), nullable=False, default='Unknown')
sort = Column(String(collation='NOCASE'))
author_sort = Column(String(collation='NOCASE'))
timestamp = Column(TIMESTAMP, default=datetime.utcnow)
timestamp = Column(TIMESTAMP, default=lambda: datetime.now(timezone.utc))
pubdate = Column(TIMESTAMP, default=DEFAULT_PUBDATE)
series_index = Column(String, nullable=False, default="1.0")
last_modified = Column(TIMESTAMP, default=datetime.utcnow)
last_modified = Column(TIMESTAMP, default=lambda: datetime.now(timezone.utc))
path = Column(String, default="", nullable=False)
has_cover = Column(Integer, default=0)
uuid = Column(String)
isbn = Column(String(collation='NOCASE'), default="")
flags = Column(Integer, nullable=False, default=1)
# isbn = Column(String(collation='NOCASE'), default="")
# flags = Column(Integer, nullable=False, default=1)
authors = relationship(Authors, secondary=books_authors_link, backref='books')
tags = relationship(Tags, secondary=books_tags_link, backref='books', order_by="Tags.name")
@@ -366,6 +431,7 @@ class Books(Base):
def __init__(self, title, sort, author_sort, timestamp, pubdate, series_index, last_modified, path, has_cover,
authors, tags, languages=None):
super().__init__()
self.title = title
self.sort = sort
self.author_sort = author_sort
@@ -374,16 +440,23 @@ class Books(Base):
self.series_index = series_index
self.last_modified = last_modified
self.path = path
self.has_cover = (has_cover != None)
self.has_cover = (has_cover is not None)
def __repr__(self):
return "<Books('{0},{1}{2}{3}{4}{5}{6}{7}{8}')>".format(self.title, self.sort, self.author_sort,
self.timestamp, self.pubdate, self.series_index,
self.last_modified, self.path, self.has_cover)
self.timestamp, self.pubdate, self.series_index,
self.last_modified, self.path, self.has_cover)
@property
def atom_timestamp(self):
return self.timestamp.strftime('%Y-%m-%dT%H:%M:%S+00:00') or ''
# OPDS atom:updated is defined as "the most recent instant in time
# when the entry was modified". Books.timestamp is the date added and
# never changes after import, so metadata and cover edits were
# invisible to OPDS sync clients. Use last_modified, which Calibre
# updates on every metadata or cover change; fall back to timestamp
# only if last_modified happens to be missing.
t = self.last_modified or self.timestamp
return t.strftime('%Y-%m-%dT%H:%M:%S+00:00') if t else ''
class CustomColumns(Base):
@@ -423,11 +496,13 @@ class CustomColumns(Base):
content['is_editable'] = self.editable
content['rec_index'] = sequence + 22 # toDo why ??
if isinstance(value, datetime):
content['#value#'] = {"__class__": "datetime.datetime", "__value__": value.strftime("%Y-%m-%dT%H:%M:%S+00:00")}
content['#value#'] = {"__class__": "datetime.datetime",
"__value__": value.strftime("%Y-%m-%dT%H:%M:%S+00:00")}
else:
content['#value#'] = value
content['#extra#'] = extra
content['is_multiple2'] = {} if not self.is_multiple else {"cache_to_list": "|", "ui_to_list": ",", "list_to_ui": ", "}
content['is_multiple2'] = {} if not self.is_multiple else {"cache_to_list": "|", "ui_to_list": ",",
"list_to_ui": ", "}
return json.dumps(content, ensure_ascii=False)
@@ -472,35 +547,25 @@ class AlchemyEncoder(json.JSONEncoder):
class CalibreDB:
_init = False
engine = None
config = None
session_factory = None
# This is a WeakSet so that references here don't keep other CalibreDB
# instances alive once they reach the end of their respective scopes
instances = WeakSet()
config_calibre_dir = None
app_db_path = None
def __init__(self, expire_on_commit=True, init=False):
def __init__(self, _app: Flask=None): # , expire_on_commit=True, init=False):
""" Initialize a new CalibreDB session
"""
self.session = None
if init:
self.init_db(expire_on_commit)
self.Session = None
#if init:
# self.init_db(expire_on_commit)
if _app is not None and not _app._got_first_request:
self.init_app(_app)
def init_db(self, expire_on_commit=True):
if self._init:
self.init_session(expire_on_commit)
self.instances.add(self)
def init_session(self, expire_on_commit=True):
self.session = self.session_factory()
self.session.expire_on_commit = expire_on_commit
self.update_title_sort(self.config)
def init_app(self, _app):
_app.teardown_appcontext(self.teardown)
@classmethod
def setup_db_cc_classes(cls, cc):
global cc_classes
cc_ids = []
books_custom_column_links = {}
for row in cc:
@@ -568,8 +633,6 @@ class CalibreDB:
secondary=books_custom_column_links[cc_id[0]],
backref='books'))
return cc_classes
@classmethod
def check_valid_db(cls, config_calibre_dir, app_db_path, config_calibre_uuid):
if not config_calibre_dir:
@@ -584,12 +647,11 @@ class CalibreDB:
connect_args={'check_same_thread': False},
poolclass=StaticPool)
with check_engine.begin() as connection:
connection.execute(text("attach database '{}' as calibre;".format(dbpath)))
connection.execute(text("attach database '{}' as app_settings;".format(app_db_path)))
connection.execute(text("attach database '{}' as calibre;".format(dbpath.replace("'", "''"))))
connection.execute(text("attach database '{}' as app_settings;".format(app_db_path.replace("'", "''"))))
local_session = scoped_session(sessionmaker())
local_session.configure(bind=connection)
database_uuid = local_session().query(Library_Id).one_or_none()
# local_session.dispose()
check_engine.connect()
db_change = config_calibre_uuid != database_uuid.uuid
@@ -597,13 +659,30 @@ class CalibreDB:
return False, False
return True, db_change
def teardown(self, exception):
ctx = g.get("lib_sql")
if ctx:
ctx.close()
@property
def session(self):
# connect or get active connection
if not g.get("lib_sql"):
g.lib_sql = self.connect()
return g.lib_sql
@classmethod
def update_config(cls, config):
def update_config(cls, config, config_calibre_dir, app_db_path):
cls.config = config
cls.config_calibre_dir = config_calibre_dir
cls.app_db_path = app_db_path
def connect(self):
return self.setup_db(self.config_calibre_dir, self.app_db_path)
@classmethod
def setup_db(cls, config_calibre_dir, app_db_path):
cls.dispose()
if not config_calibre_dir:
cls.config.invalidate()
@@ -615,16 +694,17 @@ class CalibreDB:
return None
try:
cls.engine = create_engine('sqlite://',
engine = create_engine('sqlite://',
echo=False,
isolation_level="SERIALIZABLE",
connect_args={'check_same_thread': False},
poolclass=StaticPool)
with cls.engine.begin() as connection:
connection.execute(text("attach database '{}' as calibre;".format(dbpath)))
connection.execute(text("attach database '{}' as app_settings;".format(app_db_path)))
with engine.begin() as connection:
connection.execute(text('PRAGMA cache_size = 10000;'))
connection.execute(text("attach database '{}' as calibre;".format(dbpath.replace("'", "''"))))
connection.execute(text("attach database '{}' as app_settings;".format(app_db_path.replace("'", "''"))))
conn = cls.engine.connect()
conn = engine.connect()
# conn.text_factory = lambda b: b.decode(errors = 'ignore') possible fix for #1302
except Exception as ex:
cls.config.invalidate(ex)
@@ -640,13 +720,10 @@ class CalibreDB:
log.error_or_exception(e)
return None
cls.session_factory = scoped_session(sessionmaker(autocommit=False,
autoflush=True,
bind=cls.engine))
for inst in cls.instances:
inst.init_session()
return scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=engine, future=True))
cls._init = True
def get_book(self, book_id):
return self.session.query(Books).filter(Books.id == book_id).first()
@@ -676,7 +753,8 @@ class CalibreDB:
.filter(self.common_filters(allow_show_archived)).first())
def get_book_by_uuid(self, book_uuid):
return self.session.query(Books).filter(Books.uuid == book_uuid).first()
return self.session.query(Books).filter(Books.uuid == book_uuid). \
filter(self.common_filters()).first()
def get_book_format(self, book_id, file_format):
return self.session.query(Data).filter(Data.book == book_id).filter(Data.format == file_format).first()
@@ -697,8 +775,8 @@ class CalibreDB:
def common_filters(self, allow_show_archived=False, return_all_languages=False):
if not allow_show_archived:
archived_books = (ub.session.query(ub.ArchivedBook)
.filter(ub.ArchivedBook.user_id == int(current_user.id))
.filter(ub.ArchivedBook.is_archived == True)
.filter(ub.ArchivedBook.user_id==int(current_user.id))
.filter(ub.ArchivedBook.is_archived==True)
.all())
archived_book_ids = [archived_book.book_id for archived_book in archived_books]
archived_filter = Books.id.notin_(archived_book_ids)
@@ -818,8 +896,7 @@ class CalibreDB:
entries = list()
pagination = list()
try:
pagination = Pagination(page, pagesize,
len(query.all()))
pagination = Pagination(page, pagesize, query.count())
entries = query.order_by(*order).offset(off).limit(pagesize).all()
except Exception as ex:
log.error_or_exception(ex)
@@ -829,32 +906,39 @@ class CalibreDB:
# Orders all Authors in the list according to authors sort
def order_authors(self, entries, list_return=False, combined=False):
# entries_copy = copy.deepcopy(entries)
# entries_copy =[]
for entry in entries:
if combined:
sort_authors = entry.Books.author_sort.split('&')
ids = [a.id for a in entry.Books.authors]
authors_list = entry.Books.authors
else:
sort_authors = entry.author_sort.split('&')
ids = [a.id for a in entry.authors]
authors_ordered = list()
# error = False
authors_list = entry.authors
# Create dictionary for O(1) lookup instead of nested loops
authors_by_sort = {}
authors_by_id = {}
for author in authors_list:
authors_by_sort[author.sort] = author
authors_by_id[author.id] = author
authors_ordered = []
ids_remaining = set(authors_by_id.keys())
# Order authors based on sort field using dictionary lookup
for auth in sort_authors:
results = self.session.query(Authors).filter(Authors.sort == auth.lstrip().strip()).all()
# ToDo: How to handle not found author name
if not len(results):
log.error("Author {} not found to display name in right order".format(auth.strip()))
# error = True
break
for r in results:
if r.id in ids:
authors_ordered.append(r)
ids.remove(r.id)
for author_id in ids:
result = self.session.query(Authors).filter(Authors.id == author_id).first()
authors_ordered.append(result)
auth = strip_whitespaces(auth)
if auth in authors_by_sort:
author = authors_by_sort[auth]
authors_ordered.append(author)
ids_remaining.discard(author.id)
else:
# This can happen if author_sort has stale data or formatting issues
book_id = entry.id if isinstance(entry, Books) else (entry.Books.id if combined else entry.id)
log.warning("Author '{}' of book {} not found in author list, skipping in sort order".format(auth, book_id))
# Add any remaining authors not in sort order
for author_id in ids_remaining:
authors_ordered.append(authors_by_id[author_id])
if list_return:
if combined:
@@ -867,15 +951,14 @@ class CalibreDB:
def get_typeahead(self, database, query, replace=('', ''), tag_filter=true()):
query = query or ''
self.session.connection().connection.connection.create_function("lower", 1, lcase)
self.create_functions()
entries = self.session.query(database).filter(tag_filter). \
filter(func.lower(database.name).ilike("%" + query + "%")).all()
# json_dumps = json.dumps([dict(name=escape(r.name.replace(*replace))) for r in entries])
json_dumps = json.dumps([dict(name=r.name.replace(*replace)) for r in entries])
return json_dumps
def check_exists_book(self, authr, title):
self.session.connection().connection.connection.create_function("lower", 1, lcase)
self.create_functions()
q = list()
author_terms = re.split(r'\s*&\s*', authr)
for author_term in author_terms:
@@ -885,35 +968,93 @@ class CalibreDB:
.filter(and_(Books.authors.any(and_(*q)), func.lower(Books.title).ilike("%" + title + "%"))).first()
def search_query(self, term, config, *join):
term.strip().lower()
self.session.connection().connection.connection.create_function("lower", 1, lcase)
q = list()
author_terms = re.split("[, ]+", term)
for author_term in author_terms:
q.append(Books.authors.any(func.lower(Authors.name).ilike("%" + author_term + "%")))
query = self.generate_linked_query(config.config_read_column, Books)
if len(join) == 6:
query = query.outerjoin(join[0], join[1]).outerjoin(join[2]).outerjoin(join[3], join[4]).outerjoin(join[5])
if len(join) == 3:
query = query.outerjoin(join[0], join[1]).outerjoin(join[2])
elif len(join) == 2:
query = query.outerjoin(join[0], join[1])
elif len(join) == 1:
query = query.outerjoin(join[0])
term = strip_whitespaces(term).lower()
self.create_functions()
# Try FTS5 search first for better performance
fts_ids = None
# Check if FTS5 table exists before attempting search
if not hasattr(self, '_fts_available'):
try:
result = self.session.execute(
text("SELECT name FROM sqlite_master WHERE type='table' AND name='books_fts'")
).fetchone()
self._fts_available = result is not None
except Exception:
self._fts_available = False
if self._fts_available:
try:
# Escape FTS5 special characters to prevent query errors
term_fts = term.replace('"', '""')
# Wrap in quotes for phrase matching and better accuracy
fts_results = self.session.execute(
text("SELECT DISTINCT rowid FROM books_fts WHERE books_fts MATCH :term"),
{"term": f'"{term_fts}"'}
).fetchall()
if fts_results:
fts_ids = [r[0] for r in fts_results]
except Exception as ex:
# FTS5 query failed, fall back to traditional search
log.debug("FTS5 search failed for term '{}', using fallback: {}".format(term, ex))
# Build base query with optimized joins
base_query = self.generate_linked_query(config.config_read_column, Books)
base_query = base_query.filter(self.common_filters(True))
# Apply eager loading for authors to avoid N+1 queries
base_query = base_query.options(selectinload(Books.authors))
if len(join) == 6:
base_query = base_query.outerjoin(join[0], join[1]).outerjoin(join[2]).outerjoin(join[3], join[4]).outerjoin(join[5])
if len(join) == 3:
base_query = base_query.outerjoin(join[0], join[1]).outerjoin(join[2])
elif len(join) == 2:
base_query = base_query.outerjoin(join[0], join[1])
elif len(join) == 1:
base_query = base_query.outerjoin(join[0])
# If FTS5 found results, use those IDs
if fts_ids:
return base_query.filter(Books.id.in_(fts_ids))
# Fallback to traditional search with optimized subqueries
author_terms = re.split("[, ]+", term)
# Use subquery for authors to avoid expensive .any() with OR
author_subquery = self.session.query(books_authors_link.c.book).join(
Authors, books_authors_link.c.author == Authors.id
)
author_filters = []
for author_term in author_terms:
author_filters.append(func.lower(Authors.name).ilike("%" + author_term + "%"))
if author_filters:
author_subquery = author_subquery.filter(and_(*author_filters))
# Build optimized filter expressions
cc = self.get_cc_columns(config, filter_config_custom_read=True)
filter_expression = [Books.tags.any(func.lower(Tags.name).ilike("%" + term + "%")),
Books.series.any(func.lower(Series.name).ilike("%" + term + "%")),
Books.authors.any(and_(*q)),
Books.publishers.any(func.lower(Publishers.name).ilike("%" + term + "%")),
func.lower(Books.title).ilike("%" + term + "%")]
filter_expression = [
Books.id.in_(self.session.query(books_tags_link.c.book).join(
Tags, books_tags_link.c.tag == Tags.id
).filter(func.lower(Tags.name).ilike("%" + term + "%"))),
Books.id.in_(self.session.query(books_series_link.c.book).join(
Series, books_series_link.c.series == Series.id
).filter(func.lower(Series.name).ilike("%" + term + "%"))),
Books.id.in_(author_subquery),
Books.id.in_(self.session.query(books_publishers_link.c.book).join(
Publishers, books_publishers_link.c.publisher == Publishers.id
).filter(func.lower(Publishers.name).ilike("%" + term + "%"))),
func.lower(Books.title).ilike("%" + term + "%")
]
for c in cc:
if c.datatype not in ["datetime", "rating", "bool", "int", "float"]:
filter_expression.append(
getattr(Books,
'custom_column_' + str(c.id)).any(
func.lower(cc_classes[c.id].value).ilike("%" + term + "%")))
return query.filter(self.common_filters(True)).filter(or_(*filter_expression))
return base_query.filter(or_(*filter_expression))
def get_cc_columns(self, config, filter_config_custom_read=False):
tmp_cc = self.session.query(CustomColumns).filter(CustomColumns.datatype.notin_(cc_exceptions)).all()
@@ -935,18 +1076,32 @@ class CalibreDB:
def get_search_results(self, term, config, offset=None, order=None, limit=None, *join):
order = order[0] if order else [Books.sort]
pagination = None
result = self.search_query(term, config, *join).order_by(*order).all()
result_count = len(result)
if offset != None and limit != None:
if offset is not None and limit is not None:
offset = int(offset)
limit_all = offset + int(limit)
pagination = Pagination((offset / (int(limit)) + 1), limit, result_count)
limit_int = int(limit)
# Use LIMIT+1 pattern to estimate total count without expensive count()
query = self.search_query(term, config, *join).order_by(*order)
result = query.limit(offset + limit_int + 1).all()
# Check if there are more results
has_more = len(result) > (offset + limit_int)
if has_more:
result_count = offset + limit_int + 1 # Estimate: at least this many
else:
result_count = len(result)
# Extract the page of results
result = result[offset:offset + limit_int]
pagination = Pagination((offset / limit_int + 1), limit_int, result_count)
else:
offset = 0
limit_all = result_count
# No pagination, fetch all results
result = self.search_query(term, config, *join).order_by(*order).all()
result_count = len(result)
ub.store_combo_ids(result)
entries = self.order_authors(result[offset:limit_all], list_return=True, combined=True)
entries = self.order_authors(result, list_return=True, combined=True)
return entries, result_count, pagination
@@ -967,11 +1122,11 @@ class CalibreDB:
if not return_all_languages:
no_lang_count = (self.session.query(Books)
.outerjoin(books_languages_link).outerjoin(Languages)
.filter(Languages.lang_code == None)
.filter(Languages.lang_code==None)
.filter(self.common_filters())
.count())
if no_lang_count:
tags.append([Category(_("None"), "none"), no_lang_count])
tags.append([Category(_("None"), "None", "none"), no_lang_count])
return sorted(tags, key=lambda x: x[0].name.lower(), reverse=reverse_order)
else:
if not languages:
@@ -984,7 +1139,7 @@ class CalibreDB:
lang.name = isoLanguages.get_language_name(get_locale(), lang.lang_code)
return sorted(languages, key=lambda x: x.name, reverse=reverse_order)
def update_title_sort(self, config, conn=None):
def create_functions(self, config=None):
# user defined sort function for calibre databases (Series, etc.)
def _title_sort(title):
# calibre sort stuff
@@ -993,51 +1148,27 @@ class CalibreDB:
if match:
prep = match.group(1)
title = title[len(prep):] + ', ' + prep
return title.strip()
return strip_whitespaces(title)
conn = conn or self.session.connection().connection.connection
try:
conn.create_function("title_sort", 1, _title_sort)
# sqlalchemy <1.4.24 and sqlalchemy 2.0
conn = self.session.connection().connection.driver_connection
except AttributeError:
# sqlalchemy >1.4.24
conn = self.session.connection().connection.connection
try:
if config:
conn.create_function("title_sort", 1, _title_sort)
conn.create_function('uuid4', 0, lambda: str(uuid4()))
conn.create_function("lower", 1, lcase)
except sqliteOperationalError:
pass
@classmethod
def dispose(cls):
# global session
for inst in cls.instances:
old_session = inst.session
inst.session = None
if old_session:
try:
old_session.close()
except Exception:
pass
if old_session.bind:
try:
old_session.bind.dispose()
except Exception:
pass
for attr in list(Books.__dict__.keys()):
if attr.startswith("custom_column_"):
setattr(Books, attr, None)
for db_class in cc_classes.values():
Base.metadata.remove(db_class.__table__)
cc_classes.clear()
for table in reversed(Base.metadata.sorted_tables):
name = table.key
if name.startswith("custom_column_") or name.startswith("books_custom_column_"):
if table is not None:
Base.metadata.remove(table)
def reconnect_db(self, config, app_db_path):
self.dispose()
self.engine.dispose()
# self.dispose()
# self.engine.dispose()
self.setup_db(config.config_calibre_dir, app_db_path)
self.update_config(config)
self.update_config(config, config.config_calibre_dir, app_db_path)
def lcase(s):
@@ -1049,20 +1180,25 @@ def lcase(s):
return s.lower()
def title_sort(title, config):
# calibre sort stuff
title_pat = re.compile(config.config_title_regex, re.IGNORECASE)
match = title_pat.search(title)
if match:
prep = match.group(1)
title = title[len(prep):] + ', ' + prep
return strip_whitespaces(title)
class Category:
name = None
sort = None
id = None
count = None
rating = None
def __init__(self, name, cat_id, rating=None):
self.name = name
self.sort = name
self.id = cat_id
self.rating = rating
self.count = 1
'''class Count:
count = None
def __init__(self, count):
self.count = count'''
+8 -4
View File
@@ -23,16 +23,17 @@ import zipfile
import json
from io import BytesIO
from flask_babel.speaklater import LazyString
from importlib.metadata import metadata
import os
from flask import send_file, __version__
from flask import send_file
from . import logger, config
from .about import collect_stats
log = logger.create()
class lazyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, LazyString):
@@ -40,6 +41,7 @@ class lazyEncoder(json.JSONEncoder):
# Let the base class default method raise the TypeError
return json.JSONEncoder.default(self, obj)
def assemble_logfiles(file_name):
log_list = sorted(glob.glob(file_name + '*'), reverse=True)
wfd = BytesIO()
@@ -47,7 +49,8 @@ def assemble_logfiles(file_name):
with open(f, 'rb') as fd:
shutil.copyfileobj(fd, wfd)
wfd.seek(0)
if int(__version__.split('.')[0]) < 2:
version = metadata("flask")["Version"]
if int(version.split('.')[0]) < 2:
return send_file(wfd,
as_attachment=True,
attachment_filename=os.path.basename(file_name))
@@ -70,7 +73,8 @@ def send_debug():
for fp in file_list:
zf.write(fp, os.path.basename(fp))
memory_zip.seek(0)
if int(__version__.split('.')[0]) < 2:
version = metadata("flask")["Version"]
if int(version.split('.')[0]) < 2:
return send_file(memory_zip,
as_attachment=True,
attachment_filename="Calibre-Web-debug-pack.zip")
+20 -2
View File
@@ -39,8 +39,24 @@ def load_dependencies(optional=False):
with open(req_path, 'r') as f:
for line in f:
if not line.startswith('#') and not line == '\n' and not line.startswith('git'):
res = re.match(r'(.*?)([<=>\s]+)([\d\.]+),?\s?([<=>\s]+)?([\d\.]+)?', line.strip())
res = re.match(r'(.*?)([<=>\s]+)([\d\.]+),?\s?([<=>\s]+)?([\d\.]+)?(?:\s?;\s?'
r'(?:(python_version)\s?([<=>]+)\s?\'([\d\.]+)\'|'
r'(sys_platform)\s?([\!=]+)\s?\'([\w]+)\'))?', line.strip())
try:
if res.group(7) and res.group(8):
val = res.group(8).split(".")
if not eval(str(sys.version_info[0]) + "." + "{:02d}".format(sys.version_info[1]) +
res.group(7) + val[0] + "." + "{:02d}".format(int(val[1]))):
continue
elif res.group(10) and res.group(11):
# only installed if platform is eqal, don't check if platform is not equal
if res.group(10) == "==":
if sys.platform != res.group(11):
continue
# installed if platform is not eqal, don't check if platform is equal
elif res.group(10) == "!=":
if sys.platform == res.group(11):
continue
if getattr(sys, 'frozen', False):
dep_version = exe_deps[res.group(1).lower().replace('_', '-')]
else:
@@ -58,10 +74,12 @@ def load_dependencies(optional=False):
def dependency_check(optional=False):
d = list()
dep_version_int = None
low_check = None
deps = load_dependencies(optional)
for dep in deps:
try:
dep_version_int = [int(x) for x in dep[0].split('.')]
dep_version_int = [int(x) if x.isnumeric() else 0 for x in dep[0].split('.')[:3]]
low_check = [int(x) for x in dep[3].split('.')]
high_check = [int(x) for x in dep[5].split('.')]
except AttributeError:
Executable → Regular
+941 -649
View File
File diff suppressed because it is too large Load Diff
+62
View File
@@ -0,0 +1,62 @@
# -*- coding: utf-8 -*-
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
# Copyright (C) 2024 OzzieIsaacs
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from uuid import uuid4
import os
from .file_helper import get_temp_dir
from .subproc_wrapper import process_open
from . import logger, config
from .constants import SUPPORTED_CALIBRE_BINARIES
log = logger.create()
def do_calibre_export(book_id, book_format):
try:
quotes = [4, 6]
tmp_dir = get_temp_dir()
calibredb_binarypath = get_calibre_binarypath("calibredb")
temp_file_name = str(uuid4())
my_env = os.environ.copy()
if config.config_calibre_split:
my_env['CALIBRE_OVERRIDE_DATABASE_PATH'] = os.path.join(config.config_calibre_dir, "metadata.db")
library_path = config.get_book_path()
opf_command = [calibredb_binarypath, 'export', '--dont-write-opf', '--dont-save-cover',
'--with-library', library_path,
'--to-dir', tmp_dir, '--formats', book_format, "--template", "{}".format(temp_file_name),
str(book_id)]
p = process_open(opf_command, quotes, my_env)
_, err = p.communicate()
if err:
log.error('Metadata embedder encountered an error: %s', err)
return tmp_dir, temp_file_name
except OSError as ex:
# ToDo real error handling
log.error_or_exception(ex)
return None, None
def get_calibre_binarypath(binary):
binariesdir = config.config_binariesdir
if binariesdir:
try:
return os.path.join(binariesdir, SUPPORTED_CALIBRE_BINARIES[binary])
except KeyError as ex:
log.error("Binary not supported by Calibre-Web: %s", SUPPORTED_CALIBRE_BINARIES[binary])
pass
return ""
+24 -25
View File
@@ -21,9 +21,13 @@ import zipfile
from lxml import etree
from . import isoLanguages, cover
from . import config
from . import config, logger
from .helper import split_authors
from .epub_helper import get_content_opf, default_ns
from .constants import BookMeta
from .string_helper import strip_whitespaces
log = logger.create()
def _extract_cover(zip_file, cover_file, cover_path, tmp_file_name):
@@ -42,22 +46,19 @@ def _extract_cover(zip_file, cover_file, cover_path, tmp_file_name):
cf = zip_file.read(zip_cover_path)
return cover.cover_processing(tmp_file_name, cf, extension)
def get_epub_layout(book, book_data):
ns = {
'n': 'urn:oasis:names:tc:opendocument:xmlns:container',
'pkg': 'http://www.idpf.org/2007/opf',
}
file_path = os.path.normpath(os.path.join(config.config_calibre_dir, book.path, book_data.name + "." + book_data.format.lower()))
file_path = os.path.normpath(os.path.join(config.get_book_path(),
book.path, book_data.name + "." + book_data.format.lower()))
epubZip = zipfile.ZipFile(file_path)
txt = epubZip.read('META-INF/container.xml')
tree = etree.fromstring(txt)
cfname = tree.xpath('n:rootfiles/n:rootfile/@full-path', namespaces=ns)[0]
cf = epubZip.read(cfname)
tree = etree.fromstring(cf)
p = tree.xpath('/pkg:package/pkg:metadata', namespaces=ns)[0]
try:
tree, __ = get_content_opf(file_path, default_ns)
p = tree.xpath('/pkg:package/pkg:metadata', namespaces=default_ns)[0]
layout = p.xpath('pkg:meta[@property="rendition:layout"]/text()', namespaces=ns)
layout = p.xpath('pkg:meta[@property="rendition:layout"]/text()', namespaces=default_ns)
except (etree.XMLSyntaxError, KeyError, IndexError, OSError, UnicodeDecodeError) as e:
log.error("Could not parse epub metadata of book {} during kobo sync: {}".format(book.id, e))
layout = []
if len(layout) == 0:
return None
@@ -65,20 +66,14 @@ def get_epub_layout(book, book_data):
return layout[0]
def get_epub_info(tmp_file_path, original_file_name, original_file_extension):
def get_epub_info(tmp_file_path, original_file_name, original_file_extension, no_cover_processing):
ns = {
'n': 'urn:oasis:names:tc:opendocument:xmlns:container',
'pkg': 'http://www.idpf.org/2007/opf',
'dc': 'http://purl.org/dc/elements/1.1/'
}
epub_zip = zipfile.ZipFile(tmp_file_path)
txt = epub_zip.read('META-INF/container.xml')
tree = etree.fromstring(txt)
cf_name = tree.xpath('n:rootfiles/n:rootfile/@full-path', namespaces=ns)[0]
cf = epub_zip.read(cf_name)
tree = etree.fromstring(cf)
tree, cf_name = get_content_opf(tmp_file_path, ns)
cover_path = os.path.dirname(cf_name)
@@ -96,7 +91,7 @@ def get_epub_info(tmp_file_path, original_file_name, original_file_extension):
elif s == 'date':
epub_metadata[s] = tmp[0][:10]
else:
epub_metadata[s] = tmp[0]
epub_metadata[s] = strip_whitespaces(tmp[0])
else:
epub_metadata[s] = 'Unknown'
@@ -121,7 +116,11 @@ def get_epub_info(tmp_file_path, original_file_name, original_file_extension):
epub_metadata = parse_epub_series(ns, tree, epub_metadata)
cover_file = parse_epub_cover(ns, tree, epub_zip, cover_path, tmp_file_path)
epub_zip = zipfile.ZipFile(tmp_file_path)
if not no_cover_processing:
cover_file = parse_epub_cover(ns, tree, epub_zip, cover_path, tmp_file_path)
else:
cover_file = None
identifiers = []
for node in p.xpath('dc:identifier', namespaces=ns):
@@ -176,7 +175,7 @@ def parse_epub_cover(ns, tree, epub_zip, cover_path, tmp_file_path):
for cs in cover_section:
if cs.endswith('.xhtml') or cs.endswith('.html'):
markup = epub_zip.read(os.path.join(cover_path, cs))
markup_tree = etree.fromstring(markup)
markup_tree = etree.fromstring(markup, parser=etree.XMLParser(resolve_entities=False, no_network=True))
# no matter xhtml or html with no namespace
img_src = markup_tree.xpath("//*[local-name() = 'img']/@src")
# Alternative image source
+173
View File
@@ -0,0 +1,173 @@
# -*- coding: utf-8 -*-
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
# Copyright (C) 2018 lemmsh, Kennyl, Kyosfonica, matthazinski
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import zipfile
from lxml import etree
from . import isoLanguages
default_ns = {
'n': 'urn:oasis:names:tc:opendocument:xmlns:container',
'pkg': 'http://www.idpf.org/2007/opf',
}
OPF_NAMESPACE = "http://www.idpf.org/2007/opf"
PURL_NAMESPACE = "http://purl.org/dc/elements/1.1/"
OPF = "{%s}" % OPF_NAMESPACE
PURL = "{%s}" % PURL_NAMESPACE
etree.register_namespace("opf", OPF_NAMESPACE)
etree.register_namespace("dc", PURL_NAMESPACE)
OPF_NS = {None: OPF_NAMESPACE} # the default namespace (no prefix)
NSMAP = {'dc': PURL_NAMESPACE, 'opf': OPF_NAMESPACE}
def updateEpub(src, dest, filename, data, ):
# create a temp copy of the archive without filename
with zipfile.ZipFile(src, 'r') as zin:
with zipfile.ZipFile(dest, 'w') as zout:
zout.comment = zin.comment # preserve the comment
for item in zin.infolist():
if item.filename != filename:
zout.writestr(item, zin.read(item.filename))
# now add filename with its new data
with zipfile.ZipFile(dest, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
zf.writestr(filename, data)
# Safe parser: disable entity resolution and network access to prevent XXE attacks
_safe_parser = etree.XMLParser(resolve_entities=False, no_network=True)
def get_content_opf(file_path, ns=None):
if ns is None:
ns = default_ns
epubZip = zipfile.ZipFile(file_path)
txt = epubZip.read('META-INF/container.xml')
tree = etree.fromstring(txt, parser=_safe_parser)
cf_name = tree.xpath('n:rootfiles/n:rootfile/@full-path', namespaces=ns)[0]
cf = epubZip.read(cf_name)
return etree.fromstring(cf, parser=_safe_parser), cf_name
def create_new_metadata_backup(book, custom_columns, export_language, translated_cover_name, lang_type=3):
# generate root package element
package = etree.Element(OPF + "package", nsmap=OPF_NS)
package.set("unique-identifier", "uuid_id")
package.set("version", "2.0")
# generate metadata element and all sub elements of it
metadata = etree.SubElement(package, "metadata", nsmap=NSMAP)
identifier = etree.SubElement(metadata, PURL + "identifier", id="calibre_id", nsmap=NSMAP)
identifier.set(OPF + "scheme", "calibre")
identifier.text = str(book.id)
identifier2 = etree.SubElement(metadata, PURL + "identifier", id="uuid_id", nsmap=NSMAP)
identifier2.set(OPF + "scheme", "uuid")
identifier2.text = book.uuid
for i in book.identifiers:
identifier = etree.SubElement(metadata, PURL + "identifier", nsmap=NSMAP)
identifier.set(OPF + "scheme", i.format_type())
identifier.text = str(i.val)
title = etree.SubElement(metadata, PURL + "title", nsmap=NSMAP)
title.text = book.title
for author in book.authors:
creator = etree.SubElement(metadata, PURL + "creator", nsmap=NSMAP)
creator.text = str(author.name)
creator.set(OPF + "file-as", book.author_sort) # ToDo Check
creator.set(OPF + "role", "aut")
contributor = etree.SubElement(metadata, PURL + "contributor", nsmap=NSMAP)
contributor.text = "calibre (5.7.2) [https://calibre-ebook.com]"
contributor.set(OPF + "file-as", "calibre") # ToDo Check
contributor.set(OPF + "role", "bkp")
date = etree.SubElement(metadata, PURL + "date", nsmap=NSMAP)
date.text = '{d.year:04}-{d.month:02}-{d.day:02}T{d.hour:02}:{d.minute:02}:{d.second:02}'.format(d=book.pubdate)
if book.comments and book.comments[0].text:
for b in book.comments:
description = etree.SubElement(metadata, PURL + "description", nsmap=NSMAP)
description.text = b.text
for b in book.publishers:
publisher = etree.SubElement(metadata, PURL + "publisher", nsmap=NSMAP)
publisher.text = str(b.name)
if not book.languages:
language = etree.SubElement(metadata, PURL + "language", nsmap=NSMAP)
language.text = export_language
else:
for b in book.languages:
language = etree.SubElement(metadata, PURL + "language", nsmap=NSMAP)
language.text = str(b.lang_code) if lang_type == 3 else isoLanguages.get(part3=b.lang_code).part1
for b in book.tags:
subject = etree.SubElement(metadata, PURL + "subject", nsmap=NSMAP)
subject.text = str(b.name)
etree.SubElement(metadata, "meta", name="calibre:author_link_map",
content="{" + ", ".join(['"' + str(a.name) + '": ""' for a in book.authors]) + "}",
nsmap=NSMAP)
for b in book.series:
etree.SubElement(metadata, "meta", name="calibre:series",
content=str(str(b.name)),
nsmap=NSMAP)
if book.series:
etree.SubElement(metadata, "meta", name="calibre:series_index",
content=str(book.series_index),
nsmap=NSMAP)
if len(book.ratings) and book.ratings[0].rating > 0:
etree.SubElement(metadata, "meta", name="calibre:rating",
content=str(book.ratings[0].rating),
nsmap=NSMAP)
etree.SubElement(metadata, "meta", name="calibre:timestamp",
content='{d.year:04}-{d.month:02}-{d.day:02}T{d.hour:02}:{d.minute:02}:{d.second:02}'.format(
d=book.timestamp),
nsmap=NSMAP)
etree.SubElement(metadata, "meta", name="calibre:title_sort",
content=book.sort,
nsmap=NSMAP)
sequence = 0
for cc in custom_columns:
value = None
extra = None
cc_entry = getattr(book, "custom_column_" + str(cc.id))
if cc_entry.__len__():
value = [c.value for c in cc_entry] if cc.is_multiple else cc_entry[0].value
extra = cc_entry[0].extra if hasattr(cc_entry[0], "extra") else None
etree.SubElement(metadata, "meta", name="calibre:user_metadata:#{}".format(cc.label),
content=cc.to_json(value, extra, sequence),
nsmap=NSMAP)
sequence += 1
# generate guide element and all sub elements of it
# Title is translated from default export language
guide = etree.SubElement(package, "guide")
etree.SubElement(guide, "reference", type="cover", title=translated_cover_name, href="cover.jpg")
return package
def replace_metadata(tree, package):
rep_element = tree.xpath('/pkg:package/pkg:metadata', namespaces=default_ns)[0]
new_element = package.xpath('//metadata', namespaces=default_ns)[0]
tree.replace(rep_element, new_element)
return etree.tostring(tree,
xml_declaration=True,
encoding='utf-8',
pretty_print=True).decode('utf-8')
+53 -5
View File
@@ -18,40 +18,71 @@
import traceback
from flask import render_template
from flask import render_template, request, flash, make_response
from flask_limiter import RateLimitExceeded
from flask_babel import gettext as _
from werkzeug.exceptions import default_exceptions
from .cw_login import current_user
try:
from werkzeug.exceptions import FailedDependency
except ImportError:
from werkzeug.exceptions import UnprocessableEntity as FailedDependency
from . import config, app, logger, services
from .render_template import render_title_template
from .web import render_login
from .usermanagement import auth
from cps.string_helper import strip_whitespaces
log = logger.create()
# custom error page
def error_http(error):
headers = {'WWW-Authenticate': 'Basic realm="calibre-web"'} if error.code == 401 else {}
return render_template('http_error.html',
error_code="Error {0}".format(error.code),
error_name=error.name,
issue=False,
goto_admin=False,
unconfigured=not config.db_configured,
instance=config.config_calibre_web_title
), error.code
), error.code, headers
def internal_error(error):
if (isinstance(error.original_exception, AttributeError) and
error.original_exception.args[0] == "'NoneType' object has no attribute 'query'"
and error.original_exception.name == "query"):
return render_template('http_error.html',
error_code="Database Error",
error_name='The library used is invalid or has permission errors',
issue=False,
goto_admin=True,
unconfigured=False,
error_stack="",
instance=config.config_calibre_web_title
), 500
log.error("500 Internal Server Error: %s", traceback.format_exc())
error_stack = ""
try:
if current_user.is_authenticated and current_user.role_admin():
error_stack = traceback.format_exc().split("\n")
except Exception:
pass
return render_template('http_error.html',
error_code="500 Internal Server Error",
error_name='The server encountered an internal error and was unable to complete your '
'request. There is an error in the application.',
issue=True,
goto_admin=False,
unconfigured=False,
error_stack=traceback.format_exc().split("\n"),
error_stack=error_stack,
instance=config.config_calibre_web_title
), 500
def init_errorhandler():
# http error handling
for ex in default_exceptions:
@@ -60,7 +91,6 @@ def init_errorhandler():
elif ex == 500:
app.register_error_handler(ex, internal_error)
if services.ldap:
# Only way of catching the LDAPException upon logging in with LDAP server down
@app.errorhandler(services.ldap.LDAPException)
@@ -69,3 +99,21 @@ def init_errorhandler():
log.debug('LDAP server not accessible while trying to login to opds feed')
return error_http(FailedDependency())
@app.errorhandler(RateLimitExceeded)
def handle_rate_limit(__):
log.error("Rate limit exceeded {}".format(request.endpoint))
if "register" in request.endpoint:
flash(_(u"Please wait one minute to register next user"), category="error")
return render_title_template('register.html', config=config, title=_("Register"), page="register")
elif "login" in request.endpoint:
form = request.form.to_dict()
username = strip_whitespaces(form.get('username', "")).lower().replace("\n", "").replace("\r", "")
flash(_("Please wait one minute before next login"), category="error")
return render_login(username, form.get("password", ""))
elif "opds" in request.endpoint:
return auth.auth_error_callback(429)
else:
return make_response('', 429)
+4 -1
View File
@@ -20,6 +20,9 @@ from lxml import etree
from .constants import BookMeta
# Safe parser: disable entity resolution and network access to prevent XXE attacks
_safe_parser = etree.XMLParser(resolve_entities=False, no_network=True)
def get_fb2_info(tmp_file_path, original_file_extension):
@@ -29,7 +32,7 @@ def get_fb2_info(tmp_file_path, original_file_extension):
}
fb2_file = open(tmp_file_path, encoding="utf-8")
tree = etree.fromstring(fb2_file.read().encode())
tree = etree.fromstring(fb2_file.read().encode(), parser=_safe_parser)
authors = tree.xpath('/fb:FictionBook/fb:description/fb:title-info/fb:author', namespaces=ns)
+83
View File
@@ -0,0 +1,83 @@
# -*- coding: utf-8 -*-
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
# Copyright (C) 2023 OzzieIsaacs
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from tempfile import gettempdir
import os
import shutil
import zipfile
import mimetypes
from io import BytesIO
from . import logger
log = logger.create()
try:
import magic
error = None
except ImportError as e:
error = "Cannot import python-magic, checking uploaded file metadata will not work: {}".format(e)
def get_mimetype(ext):
# overwrite some mimetypes for proper file detection
mimes = {".fb2": "text/xml",
".cbz": "application/zip",
".cbr": "application/x-rar"
}
return mimes.get(ext, mimetypes.types_map[ext])
def get_temp_dir():
tmp_dir = os.path.join(gettempdir(), 'calibre_web')
if not os.path.isdir(tmp_dir):
os.mkdir(tmp_dir)
return tmp_dir
def del_temp_dir():
tmp_dir = os.path.join(gettempdir(), 'calibre_web')
shutil.rmtree(tmp_dir)
def validate_mime_type(file_buffer, allowed_extensions):
if error:
log.error(error)
return False
mime = magic.Magic(mime=True)
allowed_mimetypes = list()
for x in allowed_extensions:
try:
allowed_mimetypes.append(get_mimetype("." + x))
except KeyError:
log.error("Unkown mimetype for Extension: {}".format(x))
tmp_mime_type = mime.from_buffer(file_buffer.read())
file_buffer.seek(0)
if any(mime_type in tmp_mime_type for mime_type in allowed_mimetypes):
return True
# Some epubs show up as zip mimetypes
elif "zip" in tmp_mime_type:
try:
with zipfile.ZipFile(BytesIO(file_buffer.read()), 'r') as epub:
file_buffer.seek(0)
if "mimetype" in epub.namelist():
return True
except:
file_buffer.seek(0)
log.error("Mimetype '{}' not found in allowed types".format(tmp_mime_type))
return False
+2 -2
View File
@@ -17,7 +17,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from . import logger
from .constants import CACHE_DIR
from .constants import CACHE_DIRECTORY
from os import makedirs, remove
from os.path import isdir, isfile, join
from shutil import rmtree
@@ -25,7 +25,7 @@ from shutil import rmtree
class FileSystem:
_instance = None
_cache_dir = CACHE_DIR
_cache_dir = CACHE_DIRECTORY
def __new__(cls):
if cls._instance is None:
+12 -12
View File
@@ -23,17 +23,17 @@
import os
import hashlib
import json
import tempfile
from uuid import uuid4
from time import time
from shutil import move, copyfile
from flask import Blueprint, flash, request, redirect, url_for, abort
from flask_babel import gettext as _
from flask_login import login_required
from . import logger, gdriveutils, config, ub, calibre_db, csrf
from .admin import admin_required
from .file_helper import get_temp_dir
from .usermanagement import user_login_required
gdrive = Blueprint('gdrive', __name__, url_prefix='/gdrive')
log = logger.create()
@@ -45,11 +45,11 @@ except ImportError as err:
current_milli_time = lambda: int(round(time() * 1000))
gdrive_watch_callback_token = 'target=calibreweb-watch_files' #nosec
gdrive_watch_callback_token = 'target=calibreweb-watch_files' # nosec
@gdrive.route("/authenticate")
@login_required
@user_login_required
@admin_required
def authenticate_google_drive():
try:
@@ -76,7 +76,7 @@ def google_drive_callback():
@gdrive.route("/watch/subscribe")
@login_required
@user_login_required
@admin_required
def watch_gdrive():
if not config.config_google_drive_watch_changes_response:
@@ -86,11 +86,12 @@ def watch_gdrive():
notification_id = str(uuid4())
try:
result = gdriveutils.watchChange(gdriveutils.Gdrive.Instance().drive, notification_id,
'web_hook', address, gdrive_watch_callback_token, current_milli_time() + 604800*1000)
'web_hook', address, gdrive_watch_callback_token, current_milli_time() + 604800*1000)
config.config_google_drive_watch_changes_response = result
config.save()
except HttpError as e:
reason=json.loads(e.content)['error']['errors'][0]
reason = json.loads(e.content)['error']['errors'][0]
if reason['reason'] == 'push.webhookUrlUnauthorized':
flash(_('Callback domain is not verified, '
'please follow steps to verify domain in google developer console'), category="error")
@@ -101,7 +102,7 @@ def watch_gdrive():
@gdrive.route("/watch/revoke")
@login_required
@user_login_required
@admin_required
def revoke_watch_gdrive():
last_watch_response = config.config_google_drive_watch_changes_response
@@ -115,6 +116,7 @@ def revoke_watch_gdrive():
config.save()
return redirect(url_for('admin.db_configuration'))
try:
@csrf.exempt
@gdrive.route("/watch/callback", methods=['GET', 'POST'])
@@ -138,10 +140,8 @@ try:
if response:
dbpath = os.path.join(config.config_calibre_dir, "metadata.db").encode()
if not response['deleted'] and response['file']['title'] == 'metadata.db' \
and response['file']['md5Checksum'] != hashlib.md5(dbpath): # nosec
tmp_dir = os.path.join(tempfile.gettempdir(), 'calibre_web')
if not os.path.isdir(tmp_dir):
os.mkdir(tmp_dir)
and response['file']['md5Checksum'] != hashlib.md5(dbpath).hexdigest(): # nosec
tmp_dir = get_temp_dir()
log.info('Database file updated')
copyfile(dbpath, os.path.join(tmp_dir, "metadata.db_" + str(current_milli_time())))
+72 -45
View File
@@ -21,7 +21,10 @@ import json
import shutil
import chardet
import ssl
import sqlite3
import mimetypes
from werkzeug.datastructures import Headers
from flask import Response, stream_with_context
from sqlalchemy import create_engine
from sqlalchemy import Column, UniqueConstraint
@@ -34,7 +37,6 @@ except ImportError:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.exc import OperationalError, InvalidRequestError, IntegrityError
from sqlalchemy.orm.exc import StaleDataError
from sqlalchemy.sql.expression import text
try:
from httplib2 import __version__ as httplib2_version
@@ -64,7 +66,7 @@ except ImportError as err:
importError = err
gdrive_support = False
from . import logger, cli_param, config
from . import logger, cli_param, config, db
from .constants import CONFIG_DIR as _CONFIG_DIR
@@ -147,7 +149,7 @@ engine = create_engine('sqlite:///{0}'.format(cli_param.gd_path), echo=False)
Base = declarative_base()
# Open session for database connection
Session = sessionmaker()
Session = sessionmaker(autoflush=False)
Session.configure(bind=engine)
session = scoped_session(Session)
@@ -208,6 +210,7 @@ def getDrive(drive=None, gauth=None):
log.error("Google Drive error: {}".format(e))
return drive
def listRootFolders():
try:
drive = getDrive(Gdrive.Instance().drive)
@@ -225,7 +228,7 @@ def getEbooksFolder(drive):
def getFolderInFolder(parentId, folderName, drive):
# drive = getDrive(drive)
query=""
query = ""
if folderName:
query = "title = '%s' and " % folderName.replace("'", r"\'")
folder = query + "'%s' in parents and mimeType = 'application/vnd.google-apps.folder'" \
@@ -236,6 +239,7 @@ def getFolderInFolder(parentId, folderName, drive):
else:
return fileList[0]
# Search for id of root folder in gdrive database, if not found request from gdrive and store in internal database
def getEbooksFolderId(drive=None):
storedPathName = session.query(GdriveId).filter(GdriveId.path == '/').first()
@@ -257,17 +261,20 @@ def getEbooksFolderId(drive=None):
return gDriveId.gdrive_id
def getFile(pathId, fileName, drive):
metaDataFile = "'%s' in parents and trashed = false and title = '%s'" % (pathId, fileName.replace("'", r"\'"))
def getFile(pathId, fileName, drive, nocase):
metaDataFile = "'%s' in parents and trashed = false and title contains '%s'" % (pathId, fileName.replace("'", r"\'"))
fileList = drive.ListFile({'q': metaDataFile}).GetList()
if fileList.__len__() == 0:
return None
else:
return fileList[0]
if nocase:
return fileList[0] if db.lcase(fileList[0]['title']) == db.lcase(fileName) else None
for f in fileList:
if f['title'] == fileName:
return f
return None
def getFolderId(path, drive):
# drive = getDrive(drive)
currentFolderId = None
try:
currentFolderId = getEbooksFolderId(drive)
@@ -301,7 +308,7 @@ def getFolderId(path, drive):
session.commit()
else:
currentFolderId = storedPathName.gdrive_id
except (OperationalError, IntegrityError, StaleDataError) as ex:
except (OperationalError, IntegrityError, StaleDataError, sqlite3.IntegrityError) as ex:
log.error_or_exception('Database error: {}'.format(ex))
session.rollback()
except ApiRequestError as ex:
@@ -312,7 +319,7 @@ def getFolderId(path, drive):
return currentFolderId
def getFileFromEbooksFolder(path, fileName):
def getFileFromEbooksFolder(path, fileName, nocase=False):
drive = getDrive(Gdrive.Instance().drive)
if path:
# sqlCheckPath=path if path[-1] =='/' else path + '/'
@@ -320,7 +327,7 @@ def getFileFromEbooksFolder(path, fileName):
else:
folderId = getEbooksFolderId(drive)
if folderId:
return getFile(folderId, fileName, drive)
return getFile(folderId, fileName, drive, nocase)
else:
return None
@@ -336,33 +343,37 @@ def downloadFile(path, filename, output):
f.GetContentFile(output)
def moveGdriveFolderRemote(origin_file, target_folder):
def moveGdriveFolderRemote(origin_file, target_folder, single_book=False):
drive = getDrive(Gdrive.Instance().drive)
previous_parents = ",".join([parent["id"] for parent in origin_file.get('parents')])
children = drive.auth.service.children().list(folderId=previous_parents).execute()
gFileTargetDir = getFileFromEbooksFolder(None, target_folder)
if not gFileTargetDir:
gFileTargetDir = drive.CreateFile(
{'title': target_folder, 'parents': [{"kind": "drive#fileLink", 'id': getEbooksFolderId()}],
"mimeType": "application/vnd.google-apps.folder"})
gFileTargetDir.Upload()
# Move the file to the new folder
drive.auth.service.files().update(fileId=origin_file['id'],
addParents=gFileTargetDir['id'],
removeParents=previous_parents,
fields='id, parents').execute()
elif gFileTargetDir['title'] != target_folder:
if single_book:
gFileTargetDir = getFileFromEbooksFolder(None, target_folder, nocase=True)
if gFileTargetDir:
# Move the file to the new folder
drive.auth.service.files().update(fileId=origin_file['id'],
addParents=gFileTargetDir['id'],
removeParents=previous_parents,
fields='id, parents').execute()
else:
gFileTargetDir = drive.CreateFile(
{'title': target_folder, 'parents': [{"kind": "drive#fileLink", 'id': getEbooksFolderId()}],
"mimeType": "application/vnd.google-apps.folder"})
gFileTargetDir.Upload()
# Move the file to the new folder
drive.auth.service.files().update(fileId=origin_file['id'],
addParents=gFileTargetDir['id'],
removeParents=previous_parents,
fields='id, parents').execute()
elif origin_file['title'] != target_folder:
#gFileTargetDir = getFileFromEbooksFolder(None, target_folder, nocase=True)
#if gFileTargetDir:
deleteDatabasePath(origin_file['title'])
# Folder is not existing, create, and move folder
drive.auth.service.files().patch(fileId=origin_file['id'],
body={'title': target_folder},
fields='title').execute()
else:
# Move the file to the new folder
drive.auth.service.files().update(fileId=origin_file['id'],
addParents=gFileTargetDir['id'],
removeParents=previous_parents,
fields='id, parents').execute()
# if previous_parents has no children anymore, delete original fileparent
if len(children['items']) == 1:
deleteDatabaseEntry(previous_parents)
@@ -370,20 +381,20 @@ def moveGdriveFolderRemote(origin_file, target_folder):
def copyToDrive(drive, uploadFile, createRoot, replaceFiles,
ignoreFiles=None,
parent=None, prevDir=''):
ignoreFiles=None,
parent=None, prevDir=''):
ignoreFiles = ignoreFiles or []
drive = getDrive(drive)
isInitial = not bool(parent)
if not parent:
parent = getEbooksFolder(drive)
if os.path.isdir(os.path.join(prevDir,uploadFile)):
if os.path.isdir(os.path.join(prevDir, uploadFile)):
existingFolder = drive.ListFile({'q': "title = '%s' and '%s' in parents and trashed = false" %
(os.path.basename(uploadFile).replace("'", r"\'"), parent['id'])}).GetList()
if len(existingFolder) == 0 and (not isInitial or createRoot):
parent = drive.CreateFile({'title': os.path.basename(uploadFile),
'parents': [{"kind": "drive#fileLink", 'id': parent['id']}],
"mimeType": "application/vnd.google-apps.folder"})
"mimeType": "application/vnd.google-apps.folder"})
parent.Upload()
else:
if (not isInitial or createRoot) and len(existingFolder) > 0:
@@ -399,7 +410,7 @@ def copyToDrive(drive, uploadFile, createRoot, replaceFiles,
driveFile = existingFiles[0]
else:
driveFile = drive.CreateFile({'title': os.path.basename(uploadFile).replace("'", r"\'"),
'parents': [{"kind":"drive#fileLink", 'id': parent['id']}], })
'parents': [{"kind": "drive#fileLink", 'id': parent['id']}], })
driveFile.SetContentFile(os.path.join(prevDir, uploadFile))
driveFile.Upload()
@@ -411,7 +422,7 @@ def uploadFileToEbooksFolder(destFile, f, string=False):
for i, x in enumerate(splitDir):
if i == len(splitDir)-1:
existing_Files = drive.ListFile({'q': "title = '%s' and '%s' in parents and trashed = false" %
(x.replace("'", r"\'"), parent['id'])}).GetList()
(x.replace("'", r"\'"), parent['id'])}).GetList()
if len(existing_Files) > 0:
driveFile = existing_Files[0]
else:
@@ -424,17 +435,17 @@ def uploadFileToEbooksFolder(destFile, f, string=False):
driveFile.Upload()
else:
existing_Folder = drive.ListFile({'q': "title = '%s' and '%s' in parents and trashed = false" %
(x.replace("'", r"\'"), parent['id'])}).GetList()
(x.replace("'", r"\'"), parent['id'])}).GetList()
if len(existing_Folder) == 0:
parent = drive.CreateFile({'title': x, 'parents': [{"kind": "drive#fileLink", 'id': parent['id']}],
"mimeType": "application/vnd.google-apps.folder"})
"mimeType": "application/vnd.google-apps.folder"})
parent.Upload()
else:
parent = existing_Folder[0]
def watchChange(drive, channel_id, channel_type, channel_address,
channel_token=None, expiration=None):
channel_token=None, expiration=None):
# Watch for all changes to a user's Drive.
# Args:
# service: Drive API service instance.
@@ -505,7 +516,7 @@ def stopChannel(drive, channel_id, resource_id):
return drive.auth.service.channels().stop(body=body).execute()
def getChangeById (drive, change_id):
def getChangeById(drive, change_id):
# Print a single Change resource information.
#
# Args:
@@ -539,8 +550,9 @@ def updateGdriveCalibreFromLocal():
if os.path.isdir(os.path.join(config.config_calibre_dir, x)):
shutil.rmtree(os.path.join(config.config_calibre_dir, x))
# update gdrive.db on edit of books title
def updateDatabaseOnEdit(ID,newPath):
def updateDatabaseOnEdit(ID, newPath):
sqlCheckPath = newPath if newPath[-1] == '/' else newPath + '/'
storedPathName = session.query(GdriveId).filter(GdriveId.gdrive_id == ID).first()
if storedPathName:
@@ -561,6 +573,14 @@ def deleteDatabaseEntry(ID):
log.error_or_exception('Database error: {}'.format(ex))
session.rollback()
def deleteDatabasePath(Pathname):
session.query(GdriveId).filter(GdriveId.path.contains(Pathname)).delete()
try:
session.commit()
except OperationalError as ex:
log.error_or_exception('Database error: {}'.format(ex))
session.rollback()
# Gets cover file from gdrive
# ToDo: Check is this right everyone get read permissions on cover files?
@@ -579,13 +599,17 @@ def get_cover_via_gdrive(cover_path):
session.add(permissionAdded)
try:
session.commit()
except OperationalError as ex:
except (OperationalError, IntegrityError) as ex:
log.error_or_exception('Database error: {}'.format(ex))
session.rollback()
return df.metadata.get('webContentLink')
headers = Headers()
headers["Content-Type"] = 'image/jpeg'
resp, content = df.auth.Get_Http_Object().request(df.metadata.get('downloadUrl'), headers=headers)
return content
else:
return None
# Gets cover file from gdrive
def get_metadata_backup_via_gdrive(metadata_path):
df = getFileFromEbooksFolder(metadata_path, 'metadata.opf')
@@ -609,6 +633,7 @@ def get_metadata_backup_via_gdrive(metadata_path):
else:
return None
# Creates chunks for downloading big files
def partial(total_byte_len, part_size_limit):
s = []
@@ -617,6 +642,7 @@ def partial(total_byte_len, part_size_limit):
s.append([p, last])
return s
# downloads files in chunks from gdrive
def do_gdrive_download(df, headers, convert_encoding=False):
total_size = int(df.metadata.get('fileSize'))
@@ -656,6 +682,7 @@ oauth_scope:
- https://www.googleapis.com/auth/drive
"""
def update_settings(client_id, client_secret, redirect_uri):
if redirect_uri.endswith('/'):
redirect_uri = redirect_uri[:-1]
+24 -1
View File
@@ -16,9 +16,10 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from datetime import datetime
from gevent.pywsgi import WSGIHandler
class MyWSGIHandler(WSGIHandler):
def get_environ(self):
env = super().get_environ()
@@ -26,4 +27,26 @@ class MyWSGIHandler(WSGIHandler):
env['RAW_URI'] = path
return env
def format_request(self):
now = datetime.now().replace(microsecond=0)
length = self.response_length or '-'
if self.time_finish:
delta = '%.6f' % (self.time_finish - self.time_start)
else:
delta = '-'
forwarded = self.environ.get('HTTP_X_FORWARDED_FOR', None)
if forwarded:
client_address = forwarded
else:
client_address = self.client_address[0] if isinstance(self.client_address, tuple) else self.client_address
return '%s - - [%s] "%s" %s %s %s' % (
client_address or '-',
now,
self.requestline or '',
# Use the native string version of the status, saved so we don't have to
# decode. But fallback to the encoded 'status' in case of subclasses
# (Is that really necessary? At least there's no overhead.)
(self._orig_status or self.status or '000').split()[0],
length,
delta)
+337 -266
View File
@@ -22,18 +22,19 @@ import random
import io
import mimetypes
import re
import regex
import shutil
import socket
from datetime import datetime, timedelta
from tempfile import gettempdir
from datetime import datetime, timedelta, timezone
import requests
import unidecode
from uuid import uuid4
from flask import send_from_directory, make_response, redirect, abort, url_for
from flask import send_from_directory, make_response, abort, url_for, Response, request, after_this_request
from flask_babel import gettext as _
from flask_babel import lazy_gettext as N_
from flask_babel import get_locale
from flask_login import current_user
from .cw_login import current_user
from sqlalchemy.sql.expression import true, false, and_, or_, text, func
from sqlalchemy.exc import InvalidRequestError, OperationalError
from werkzeug.datastructures import Headers
@@ -42,24 +43,29 @@ from markupsafe import escape
from urllib.parse import quote
try:
import advocate
from advocate.exceptions import UnacceptableAddressException
from . import cw_advocate
from .cw_advocate.exceptions import UnacceptableAddressException
use_advocate = True
except ImportError:
except ImportError as e:
use_advocate = False
advocate = requests
UnacceptableAddressException = MissingSchema = BaseException
from . import calibre_db, cli_param
from .string_helper import strip_whitespaces
from .tasks.convert import TaskConvert
from . import logger, config, db, ub, fs
from . import gdriveutils as gd
from .constants import STATIC_DIR as _STATIC_DIR, CACHE_TYPE_THUMBNAILS, THUMBNAIL_TYPE_COVER, THUMBNAIL_TYPE_SERIES
from .constants import (STATIC_DIR as _STATIC_DIR, CACHE_TYPE_THUMBNAILS, THUMBNAIL_TYPE_COVER, THUMBNAIL_TYPE_SERIES,
SUPPORTED_CALIBRE_BINARIES)
from .subproc_wrapper import process_wait
from .services.worker import WorkerThread
from .tasks.mail import TaskEmail
from .tasks.thumbnail import TaskClearCoverThumbnailCache, TaskGenerateCoverThumbnails
from .tasks.metadata_backup import TaskBackupMetadata
from .file_helper import get_temp_dir
from .epub_helper import get_content_opf, create_new_metadata_backup, updateEpub, replace_metadata
from .embed_helper import do_calibre_export
log = logger.create()
@@ -112,9 +118,11 @@ def convert_book_format(book_id, calibre_path, old_book_format, new_book_format,
# Texts are not lazy translated as they are supposed to get send out as is
def send_test_mail(ereader_mail, user_name):
WorkerThread.add(user_name, TaskEmail(_('Calibre-Web Test Email'), None, None,
config.get_mail_settings(), ereader_mail, N_("Test Email"),
_('This Email has been sent via Calibre-Web.')))
for email in ereader_mail.split(','):
email = strip_whitespaces(email)
WorkerThread.add(user_name, TaskEmail(_('Calibre-Web Test Email'), None, None,
config.get_mail_settings(), email, N_("Test Email"),
_('This Email has been sent via Calibre-Web.')))
return
@@ -191,7 +199,7 @@ def check_send_to_ereader(entry):
# Check if a reader is existing for any of the book formats, if not, return empty list, otherwise return
# list with supported formats
def check_read_formats(entry):
extensions_reader = {'TXT', 'PDF', 'EPUB', 'CBZ', 'CBT', 'CBR', 'DJVU'}
extensions_reader = {'TXT', 'PDF', 'EPUB', 'KEPUB', 'CBZ', 'CBT', 'CBR', 'DJVU', 'DJV'}
book_formats = list()
if len(entry.data):
for ele in iter(entry.data):
@@ -220,14 +228,16 @@ def send_mail(book_id, book_format, convert, ereader_mail, calibrepath, user_id)
converted_file_name = entry.name + '.' + book_format.lower()
link = '<a href="{}">{}</a>'.format(url_for('web.show_book', book_id=book_id), escape(book.title))
email_text = N_("%(book)s send to eReader", book=link)
WorkerThread.add(user_id, TaskEmail(_("Send to eReader"), book.path, converted_file_name,
config.get_mail_settings(), ereader_mail,
email_text, _('This Email has been sent via Calibre-Web.')))
for email in ereader_mail.split(','):
email = strip_whitespaces(email)
WorkerThread.add(user_id, TaskEmail(_("Send to eReader"), book.path, converted_file_name,
config.get_mail_settings(), email,
email_text, _('This Email has been sent via Calibre-Web.'), book.id))
return
return _("The requested file could not be read. Maybe wrong permissions?")
def get_valid_filename(value, replace_whitespace=True, chars=128):
def get_valid_filename(value, replace_whitespace=True, chars=128, force_unidecode=False):
"""
Returns the given string converted to a string that can be used for a clean
filename. Limits num characters to 128 max.
@@ -235,7 +245,7 @@ def get_valid_filename(value, replace_whitespace=True, chars=128):
if value[-1:] == '.':
value = value[:-1]+'_'
value = value.replace("/", "_").replace(":", "_").strip('\0')
if config.config_unicode_filename:
if config.config_unicode_filename or force_unidecode:
value = (unidecode.unidecode(value))
if replace_whitespace:
# *+:\"/<>? are replaced by _
@@ -243,7 +253,7 @@ def get_valid_filename(value, replace_whitespace=True, chars=128):
# pipe has to be replaced with comma
value = re.sub(r'[|]+', ',', value, flags=re.U)
value = value.encode('utf-8')[:chars].decode('utf-8', errors='ignore').strip()
value = strip_whitespaces(value.encode('utf-8')[:chars].decode('utf-8', errors='ignore'))
if not value:
raise ValueError("Filename cannot be empty")
@@ -258,11 +268,11 @@ def split_authors(values):
commas = author.count(',')
if commas == 1:
author_split = author.split(',')
authors_list.append(author_split[1].strip() + ' ' + author_split[0].strip())
authors_list.append(strip_whitespaces(author_split[1]) + ' ' + strip_whitespaces(author_split[0]))
elif commas > 1:
authors_list.extend([x.strip() for x in author.split(',')])
authors_list.extend([strip_whitespaces(x) for x in author.split(',')])
else:
authors_list.append(author.strip())
authors_list.append(strip_whitespaces(author))
return authors_list
@@ -297,18 +307,16 @@ def edit_book_read_status(book_id, read_status=None):
if not config.config_read_column:
book = ub.session.query(ub.ReadBook).filter(and_(ub.ReadBook.user_id == int(current_user.id),
ub.ReadBook.book_id == book_id)).first()
if book:
if read_status is None:
if book.read_status == ub.ReadBook.STATUS_FINISHED:
book.read_status = ub.ReadBook.STATUS_UNREAD
else:
book.read_status = ub.ReadBook.STATUS_FINISHED
else:
book.read_status = ub.ReadBook.STATUS_FINISHED if read_status else ub.ReadBook.STATUS_UNREAD
else:
if not book:
read_book = ub.ReadBook(user_id=current_user.id, book_id=book_id)
read_book.read_status = ub.ReadBook.STATUS_FINISHED
book = read_book
if read_status is None:
if book.read_status == ub.ReadBook.STATUS_FINISHED:
book.read_status = ub.ReadBook.STATUS_UNREAD
else:
book.read_status = ub.ReadBook.STATUS_FINISHED
else:
book.read_status = ub.ReadBook.STATUS_FINISHED if read_status == True else ub.ReadBook.STATUS_UNREAD
if not book.kobo_reading_state:
kobo_reading_state = ub.KoboReadingState(user_id=current_user.id, book_id=book_id)
kobo_reading_state.current_bookmark = ub.KoboBookmark()
@@ -318,8 +326,8 @@ def edit_book_read_status(book_id, read_status=None):
ub.session_commit("Book {} readbit toggled".format(book_id))
else:
try:
calibre_db.update_title_sort(config)
book = calibre_db.get_filtered_book(book_id)
calibre_db.create_functions(config)
book = calibre_db.get_filtered_book(book_id, True)
book_read_status = getattr(book, 'custom_column_' + str(config.config_read_column))
if len(book_read_status):
if read_status is None:
@@ -383,75 +391,61 @@ def delete_book_file(book, calibrepath, book_format=None):
id=book.id,
path=book.path)
def clean_author_database(renamed_author, calibre_path="", local_book=None, gdrive=None):
valid_filename_authors = [get_valid_filename(r, chars=96) for r in renamed_author]
for r in renamed_author:
if local_book:
all_books = [local_book]
def rename_all_files_on_change(one_book, new_path, old_path, all_new_name, gdrive=False):
for file_format in one_book.data:
if not gdrive:
try:
if not os.path.exists(new_path):
os.makedirs(new_path)
shutil.move(os.path.join(old_path, file_format.name + '.' + file_format.format.lower()),
os.path.join(new_path, all_new_name + '.' + file_format.format.lower()))
except (PermissionError, FileNotFoundError) as ex:
log.error("Moving book-id %s folder %s failed: %s", one_book.id, new_path, ex)
return _("Moving book path of Book %(book_id)s to: '%(src)s' failed with error: %(error)s",
book_id=one_book.id, src=new_path, error=str(ex))
else:
all_books = calibre_db.session.query(db.Books) \
.filter(db.Books.authors.any(db.Authors.name == r)).all()
for book in all_books:
book_author_path = book.path.split('/')[0]
if book_author_path in valid_filename_authors or local_book:
new_author = calibre_db.session.query(db.Authors).filter(db.Authors.name == r).first()
all_new_authordir = get_valid_filename(new_author.name, chars=96)
all_titledir = book.path.split('/')[1]
all_new_path = os.path.join(calibre_path, all_new_authordir, all_titledir)
all_new_name = get_valid_filename(book.title, chars=42) + ' - ' \
+ get_valid_filename(new_author.name, chars=42)
# change location in database to new author/title path
book.path = os.path.join(all_new_authordir, all_titledir).replace('\\', '/')
for file_format in book.data:
if not gdrive:
shutil.move(os.path.normcase(os.path.join(all_new_path,
file_format.name + '.' + file_format.format.lower())),
os.path.normcase(os.path.join(all_new_path,
all_new_name + '.' + file_format.format.lower())))
else:
g_file = gd.getFileFromEbooksFolder(all_new_path,
file_format.name + '.' + file_format.format.lower())
if g_file:
gd.moveGdriveFileRemote(g_file, all_new_name + '.' + file_format.format.lower())
gd.updateDatabaseOnEdit(g_file['id'], all_new_name + '.' + file_format.format.lower())
else:
log.error("File {} not found on gdrive"
.format(all_new_path, file_format.name + '.' + file_format.format.lower()))
file_format.name = all_new_name
g_file = gd.getFileFromEbooksFolder(old_path,
file_format.name + '.' + file_format.format.lower())
if g_file:
gd.moveGdriveFileRemote(g_file, all_new_name + '.' + file_format.format.lower())
gd.updateDatabaseOnEdit(g_file['id'], all_new_name + '.' + file_format.format.lower())
else:
log.error("File {} not found on gdrive"
.format(old_path, file_format.name + '.' + file_format.format.lower()))
# change name in Database
file_format.name = all_new_name
return False
def rename_all_authors(first_author, renamed_author, calibre_path="", localbook=None, gdrive=False):
def rename_author_path(first_author, old_author_dir, renamed_author, calibre_path="", gdrive=False):
# Create new_author_dir from parameter or from database
# Create new title_dir from database and add id
if first_author:
new_authordir = get_valid_filename(first_author, chars=96)
for r in renamed_author:
new_author = calibre_db.session.query(db.Authors).filter(db.Authors.name == r).first()
old_author_dir = get_valid_filename(r, chars=96)
new_author_rename_dir = get_valid_filename(new_author.name, chars=96)
if gdrive:
g_file = gd.getFileFromEbooksFolder(None, old_author_dir)
if g_file:
gd.moveGdriveFolderRemote(g_file, new_author_rename_dir)
else:
if os.path.isdir(os.path.join(calibre_path, old_author_dir)):
try:
old_author_path = os.path.join(calibre_path, old_author_dir)
new_author_path = os.path.join(calibre_path, new_author_rename_dir)
shutil.move(os.path.normcase(old_author_path), os.path.normcase(new_author_path))
except OSError as ex:
log.error("Rename author from: %s to %s: %s", old_author_path, new_author_path, ex)
log.debug(ex, exc_info=True)
return _("Rename author from: '%(src)s' to '%(dest)s' failed with error: %(error)s",
src=old_author_path, dest=new_author_path, error=str(ex))
new_authordir = get_valid_filename(first_author, chars=96)
new_author_rename_dir = get_valid_filename(renamed_author, chars=96)
if gdrive:
g_file = gd.getFileFromEbooksFolder(None, old_author_dir)
if g_file:
gd.moveGdriveFolderRemote(g_file, new_author_rename_dir)
else:
new_authordir = get_valid_filename(localbook.authors[0].name, chars=96)
if os.path.isdir(os.path.join(calibre_path, old_author_dir)):
old_author_path = os.path.join(calibre_path, old_author_dir)
new_author_path = os.path.join(calibre_path, new_author_rename_dir)
try:
os.rename(old_author_path, new_author_path)
except OSError:
try:
shutil.move(old_author_path, new_author_path)
except OSError as ex:
log.error("Rename author from: %s to %s: %s", old_author_path, new_author_path, ex)
log.error_or_exception(ex)
raise Exception(_("Rename author from: '%(src)s' to '%(dest)s' failed with error: %(error)s",
src=old_author_path, dest=new_author_path, error=str(ex)))
return new_authordir
# Moves files in file storage during author/title rename, or from temp dir to file storage
def update_dir_structure_file(book_id, calibre_path, first_author, original_filepath, db_filename, renamed_author):
def update_dir_structure_file(book_id, calibre_path, original_filepath, new_author, db_filename):
# get book database entry from id, if original path overwrite source with original_filepath
local_book = calibre_db.get_book(book_id)
if original_filepath:
@@ -463,15 +457,11 @@ def update_dir_structure_file(book_id, calibre_path, first_author, original_file
author_dir = local_book.path.split('/')[0]
title_dir = local_book.path.split('/')[1]
# Create new_author_dir from parameter or from database
# Create new title_dir from database and add id
new_author_dir = rename_all_authors(first_author, renamed_author, calibre_path, local_book)
if first_author:
if first_author.lower() in [r.lower() for r in renamed_author]:
if os.path.isdir(os.path.join(calibre_path, new_author_dir)):
path = os.path.join(calibre_path, new_author_dir, title_dir)
new_title_dir = get_valid_filename(local_book.title, chars=96) + " (" + str(book_id) + ")"
if new_author:
new_author_dir = get_valid_filename(new_author, chars=96)
else:
new_author = new_author_dir = author_dir
if title_dir != new_title_dir or author_dir != new_author_dir or original_filepath:
error = move_files_on_change(calibre_path,
@@ -481,36 +471,40 @@ def update_dir_structure_file(book_id, calibre_path, first_author, original_file
db_filename,
original_filepath,
path)
if error:
return error
if not error:
new_path = os.path.join(calibre_path, new_author_dir, new_title_dir).replace('\\', '/')
all_new_name = get_valid_filename(local_book.title, chars=42) + ' - ' \
+ get_valid_filename(new_author, chars=42)
# Book folder already moved, only files need to be renamed
renameerror = rename_all_files_on_change(local_book, new_path, new_path, all_new_name)
# Rename all files from old names to new names
return rename_files_on_change(first_author, renamed_author, local_book, original_filepath, path, calibre_path)
if error or renameerror:
return error or renameerror
return False
def upload_new_file_gdrive(book_id, first_author, renamed_author, title, title_dir, original_filepath, filename_ext):
def upload_new_file_gdrive(book_id, first_author, title, title_dir, original_filepath, filename_ext):
book = calibre_db.get_book(book_id)
file_name = get_valid_filename(title, chars=42) + ' - ' + \
get_valid_filename(first_author, chars=42) + filename_ext
rename_all_authors(first_author, renamed_author, gdrive=True)
gdrive_path = os.path.join(get_valid_filename(first_author, chars=96),
title_dir + " (" + str(book_id) + ")")
book.path = gdrive_path.replace("\\", "/")
gd.uploadFileToEbooksFolder(os.path.join(gdrive_path, file_name).replace("\\", "/"), original_filepath)
return rename_files_on_change(first_author, renamed_author, local_book=book, gdrive=True)
return False
def update_dir_structure_gdrive(book_id, first_author, renamed_author):
def update_dir_structure_gdrive(book_id, first_author):
book = calibre_db.get_book(book_id)
authordir = book.path.split('/')[0]
titledir = book.path.split('/')[1]
new_authordir = rename_all_authors(first_author, renamed_author, gdrive=True)
# new_authordir = rename_all_authors(first_author, renamed_author, gdrive=True)
new_authordir = get_valid_filename(first_author, chars=96)
new_titledir = get_valid_filename(book.title, chars=96) + " (" + str(book_id) + ")"
if titledir != new_titledir:
g_file = gd.getFileFromEbooksFolder(os.path.dirname(book.path), titledir)
g_file = gd.getFileFromEbooksFolder(authordir, titledir)
if g_file:
gd.moveGdriveFileRemote(g_file, new_titledir)
book.path = book.path.split('/')[0] + '/' + new_titledir
@@ -518,71 +512,60 @@ def update_dir_structure_gdrive(book_id, first_author, renamed_author):
else:
return _('File %(file)s not found on Google Drive', file=book.path) # file not found
if authordir != new_authordir and authordir not in renamed_author:
g_file = gd.getFileFromEbooksFolder(os.path.dirname(book.path), new_titledir)
if authordir != new_authordir:
g_file = gd.getFileFromEbooksFolder(authordir, new_titledir)
if g_file:
gd.moveGdriveFolderRemote(g_file, new_authordir)
gd.moveGdriveFolderRemote(g_file, new_authordir, single_book=True)
book.path = new_authordir + '/' + book.path.split('/')[1]
gd.updateDatabaseOnEdit(g_file['id'], book.path)
else:
return _('File %(file)s not found on Google Drive', file=authordir) # file not found
# change location in database to new author/title path
book.path = os.path.join(new_authordir, new_titledir).replace('\\', '/')
return rename_files_on_change(first_author, renamed_author, book, gdrive=True)
if titledir != new_titledir or authordir != new_authordir :
all_new_name = get_valid_filename(book.title, chars=42) + ' - ' \
+ get_valid_filename(new_authordir, chars=42)
return rename_all_files_on_change(book, book.path, book.path, all_new_name, gdrive=True) # todo: Move filenames on gdrive
return False
def move_files_on_change(calibre_path, new_authordir, new_titledir, localbook, db_filename, original_filepath, path):
new_path = os.path.join(calibre_path, new_authordir, new_titledir)
new_name = get_valid_filename(localbook.title, chars=96) + ' - ' + new_authordir
def move_files_on_change(calibre_path, new_author_dir, new_titledir, localbook, db_filename, original_filepath, path):
new_path = os.path.join(calibre_path, new_author_dir, new_titledir)
try:
if original_filepath:
if not os.path.isdir(new_path):
os.makedirs(new_path)
shutil.move(os.path.normcase(original_filepath), os.path.normcase(os.path.join(new_path, db_filename)))
log.debug("Moving title: %s to %s/%s", original_filepath, new_path, new_name)
try:
shutil.move(original_filepath, os.path.join(new_path, db_filename))
except OSError:
log.error("Rename title from {} to {} failed with error, trying to "
"move without metadata".format(path, new_path))
shutil.move(original_filepath, os.path.join(new_path, db_filename), copy_function=shutil.copy)
log.debug("Moving title: %s to %s", original_filepath, new_path)
else:
# Check new path is not valid path
if not os.path.exists(new_path):
# move original path to new path
log.debug("Moving title: %s to %s", path, new_path)
shutil.move(os.path.normcase(path), os.path.normcase(new_path))
shutil.move(path, new_path)
else: # path is valid copy only files to new location (merge)
log.info("Moving title: %s into existing: %s", path, new_path)
# Take all files and subfolder from old path (strange command)
for dir_name, __, file_list in os.walk(path):
for file in file_list:
shutil.move(os.path.normcase(os.path.join(dir_name, file)),
os.path.normcase(os.path.join(new_path + dir_name[len(path):], file)))
shutil.move(os.path.join(dir_name, file), os.path.join(new_path + dir_name[len(path):], file))
if not os.listdir(os.path.split(path)[0]):
try:
shutil.rmtree(os.path.split(path)[0])
except (IOError, OSError) as ex:
log.error("Deleting authorpath for book %s failed: %s", localbook.id, ex)
# change location in database to new author/title path
localbook.path = os.path.join(new_authordir, new_titledir).replace('\\', '/')
except OSError as ex:
localbook.path = os.path.join(new_author_dir, new_titledir).replace('\\', '/')
except (OSError, FileNotFoundError) as ex:
log.error_or_exception("Rename title from {} to {} failed with error: {}".format(path, new_path, ex))
return _("Rename title from: '%(src)s' to '%(dest)s' failed with error: %(error)s",
src=path, dest=new_path, error=str(ex))
return False
def rename_files_on_change(first_author,
renamed_author,
local_book,
original_filepath="",
path="",
calibre_path="",
gdrive=False):
# Rename all files from old names to new names
try:
clean_author_database(renamed_author, calibre_path, gdrive=gdrive)
if first_author and first_author not in renamed_author:
clean_author_database([first_author], calibre_path, local_book, gdrive)
if not gdrive and not renamed_author and not original_filepath and len(os.listdir(os.path.dirname(path))) == 0:
shutil.rmtree(os.path.dirname(path))
except (OSError, FileNotFoundError) as ex:
log.error_or_exception("Error in rename file in path {}".format(ex))
return _("Error in rename file in path: {}".format(str(ex)))
return False
def delete_book_gdrive(book, book_format):
error = None
if book_format:
@@ -590,7 +573,7 @@ def delete_book_gdrive(book, book_format):
for entry in book.data:
if entry.format.upper() == book_format:
name = entry.name + '.' + book_format
g_file = gd.getFileFromEbooksFolder(book.path, name)
g_file = gd.getFileFromEbooksFolder(book.path, name, nocase=True)
else:
g_file = gd.getFileFromEbooksFolder(os.path.dirname(book.path), book.path.split('/')[1])
if g_file:
@@ -618,6 +601,7 @@ def reset_password(user_id):
ub.session.rollback()
return 0, None
def generate_random_password(min_length):
min_length = max(8, min_length) - 4
random_source = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%&*()?"
@@ -643,12 +627,6 @@ def generate_random_password(min_length):
return ''.join(password)
'''def generate_random_password(min_length):
s = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%&*()?"
passlen = min_length
return "".join(s[c % len(s)] for c in os.urandom(passlen))'''
def uniq(inpt):
output = []
inpt = [" ".join(inp.split()) for inp in inpt]
@@ -667,38 +645,44 @@ def check_email(email):
def check_username(username):
username = username.strip()
username = strip_whitespaces(username)
if ub.session.query(ub.User).filter(func.lower(ub.User.name) == username.lower()).scalar():
log.error("This username is already taken")
raise Exception(_("This username is already taken"))
return username
def valid_email(email):
email = email.strip()
# if email is not deleted
if email:
# Regex according to https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email#validation
if not re.search(r"^[\w.!#$%&'*+\\/=?^_`{|}~-]+@[\w](?:[\w-]{0,61}[\w])?(?:\.[\w](?:[\w-]{0,61}[\w])?)*$",
email):
log.error("Invalid Email address format")
raise Exception(_("Invalid Email address format"))
return email
def valid_email(emails):
valid_emails = []
for email in emails.split(','):
email = strip_whitespaces(email)
# if email is not deleted
if email:
# Regex according to https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email#validation
if not re.search(r"^[\w.!#$%&'*+\\/=?^_`{|}~-]+@[\w](?:[\w-]{0,61}[\w])?(?:\.[\w](?:[\w-]{0,61}[\w])?)*$",
email):
log.error("Invalid Email address format for {}".format(email))
raise Exception(_("Invalid Email address format"))
valid_emails.append(email)
return ",".join(valid_emails)
def valid_password(check_password):
if config.config_password_policy:
verify = ""
if config.config_password_min_length > 0:
verify += "^(?=.{" + str(config.config_password_min_length) + ",}$)"
verify += r"^(?=.{" + str(config.config_password_min_length) + ",}$)"
if config.config_password_number:
verify += "(?=.*?\d)"
verify += r"(?=.*?\d)"
if config.config_password_lower:
verify += "(?=.*?[a-z])"
verify += r"(?=.*?[\p{Ll}])"
if config.config_password_upper:
verify += "(?=.*?[A-Z])"
verify += r"(?=.*?[\p{Lu}])"
if config.config_password_character:
verify += r"(?=.*?[\p{Letter}])"
if config.config_password_special:
verify += "(?=.*?[^A-Za-z\s0-9])"
match = re.match(verify, check_password)
verify += r"(?=.*?[^\p{Letter}\s0-9])"
match = regex.match(verify, check_password)
if not match:
raise Exception(_("Password doesn't comply with password validation rules"))
return check_password
@@ -709,22 +693,20 @@ def update_dir_structure(book_id,
calibre_path,
first_author=None, # change author of book to this author
original_filepath=None,
db_filename=None,
renamed_author=None):
renamed_author = renamed_author or []
db_filename=None):
if config.config_use_google_drive:
return update_dir_structure_gdrive(book_id, first_author, renamed_author)
return update_dir_structure_gdrive(book_id, first_author)
else:
return update_dir_structure_file(book_id,
calibre_path,
first_author,
original_filepath,
db_filename, renamed_author)
first_author,
db_filename)
def delete_book(book, calibrepath, book_format):
if not book_format:
clear_cover_thumbnail_cache(book.id) ## here it breaks
clear_cover_thumbnail_cache(book.id) # here it breaks
calibre_db.delete_dirty_metadata(book.id)
if config.config_use_google_drive:
return delete_book_gdrive(book, book_format)
@@ -732,28 +714,27 @@ def delete_book(book, calibrepath, book_format):
return delete_book_file(book, calibrepath, book_format)
def get_cover_on_failure(use_generic_cover):
if use_generic_cover:
try:
return send_from_directory(_STATIC_DIR, "generic_cover.jpg")
except PermissionError:
log.error("No permission to access generic_cover.jpg file.")
abort(403)
abort(404)
def get_cover_on_failure():
try:
return send_from_directory(_STATIC_DIR, "generic_cover.jpg")
except PermissionError:
log.error("No permission to access generic_cover.jpg file.")
abort(403)
def get_book_cover(book_id, resolution=None):
book = calibre_db.get_filtered_book(book_id, allow_show_archived=True)
return get_book_cover_internal(book, use_generic_cover_on_failure=True, resolution=resolution)
return get_book_cover_internal(book, resolution=resolution)
# Called only by kobo sync -> cover not found should be answered with 404 and not with default cover
def get_book_cover_with_uuid(book_uuid, resolution=None):
book = calibre_db.get_book_by_uuid(book_uuid)
return get_book_cover_internal(book, use_generic_cover_on_failure=False, resolution=resolution)
if not book:
return # allows kobo.HandleCoverImageRequest to proxy request
return get_book_cover_internal(book, resolution=resolution)
def get_book_cover_internal(book, use_generic_cover_on_failure, resolution=None):
def get_book_cover_internal(book, resolution=None):
if book and book.has_cover:
# Send the book cover thumbnail if it exists in cache
@@ -769,49 +750,48 @@ def get_book_cover_internal(book, use_generic_cover_on_failure, resolution=None)
if config.config_use_google_drive:
try:
if not gd.is_gdrive_ready():
return get_cover_on_failure(use_generic_cover_on_failure)
path = gd.get_cover_via_gdrive(book.path)
if path:
return redirect(path)
return get_cover_on_failure()
cover_file = gd.get_cover_via_gdrive(book.path)
if cover_file:
return Response(cover_file, mimetype='image/jpeg')
else:
log.error('{}/cover.jpg not found on Google Drive'.format(book.path))
return get_cover_on_failure(use_generic_cover_on_failure)
return get_cover_on_failure()
except Exception as ex:
log.error_or_exception(ex)
return get_cover_on_failure(use_generic_cover_on_failure)
return get_cover_on_failure()
# Send the book cover from the Calibre directory
else:
cover_file_path = os.path.join(config.config_calibre_dir, book.path)
cover_file_path = os.path.join(config.get_book_path(), book.path)
if os.path.isfile(os.path.join(cover_file_path, "cover.jpg")):
return send_from_directory(cover_file_path, "cover.jpg")
else:
return get_cover_on_failure(use_generic_cover_on_failure)
return get_cover_on_failure()
else:
return get_cover_on_failure(use_generic_cover_on_failure)
return get_cover_on_failure()
def get_book_cover_thumbnail(book, resolution):
if book and book.has_cover:
return ub.session \
.query(ub.Thumbnail) \
.filter(ub.Thumbnail.type == THUMBNAIL_TYPE_COVER) \
.filter(ub.Thumbnail.entity_id == book.id) \
.filter(ub.Thumbnail.resolution == resolution) \
.filter(or_(ub.Thumbnail.expiration.is_(None), ub.Thumbnail.expiration > datetime.utcnow())) \
.first()
return (ub.session
.query(ub.Thumbnail)
.filter(ub.Thumbnail.type == THUMBNAIL_TYPE_COVER)
.filter(ub.Thumbnail.entity_id == book.id)
.filter(ub.Thumbnail.resolution == resolution)
.filter(or_(ub.Thumbnail.expiration.is_(None), ub.Thumbnail.expiration > datetime.now(timezone.utc)))
.first())
def get_series_thumbnail_on_failure(series_id, resolution):
book = calibre_db.session \
.query(db.Books) \
.join(db.books_series_link) \
.join(db.Series) \
.filter(db.Series.id == series_id) \
.filter(db.Books.has_cover == 1) \
.first()
return get_book_cover_internal(book, use_generic_cover_on_failure=True, resolution=resolution)
book = (calibre_db.session
.query(db.Books)
.join(db.books_series_link)
.join(db.Series)
.filter(db.Series.id == series_id)
.filter(db.Books.has_cover == 1)
.first())
return get_book_cover_internal(book, resolution=resolution)
def get_series_cover_thumbnail(series_id, resolution=None):
@@ -832,13 +812,13 @@ def get_series_cover_internal(series_id, resolution=None):
def get_series_thumbnail(series_id, resolution):
return ub.session \
.query(ub.Thumbnail) \
.filter(ub.Thumbnail.type == THUMBNAIL_TYPE_SERIES) \
.filter(ub.Thumbnail.entity_id == series_id) \
.filter(ub.Thumbnail.resolution == resolution) \
.filter(or_(ub.Thumbnail.expiration.is_(None), ub.Thumbnail.expiration > datetime.utcnow())) \
.first()
return (ub.session
.query(ub.Thumbnail)
.filter(ub.Thumbnail.type == THUMBNAIL_TYPE_SERIES)
.filter(ub.Thumbnail.entity_id == series_id)
.filter(ub.Thumbnail.resolution == resolution)
.filter(or_(ub.Thumbnail.expiration.is_(None), ub.Thumbnail.expiration > datetime.now(timezone.utc)))
.first())
# saves book cover from url
@@ -847,7 +827,7 @@ def save_cover_from_url(url, book_path):
if cli_param.allow_localhost:
img = requests.get(url, timeout=(10, 200), allow_redirects=False) # ToDo: Error Handling
elif use_advocate:
img = advocate.get(url, timeout=(10, 200), allow_redirects=False) # ToDo: Error Handling
img = cw_advocate.get(url, timeout=(10, 200), allow_redirects=False) # ToDo: Error Handling
else:
log.error("python module advocate is not installed but is needed")
return False, _("Python module 'advocate' is not installed but is needed for cover uploads")
@@ -878,7 +858,7 @@ def save_cover_from_filestorage(filepath, saved_filename, img):
log.error("Failed to create path for cover")
return False, _("Failed to create path for cover")
try:
# upload of jgp file without wand
# upload of jpg file without wand
if isinstance(img, requests.Response):
with open(os.path.join(filepath, saved_filename), 'wb') as f:
f.write(img.content)
@@ -911,7 +891,7 @@ def save_cover(img, book_path):
else:
imgc = Image(blob=io.BytesIO(img.content))
imgc.format = 'jpeg'
imgc.transform_colorspace("rgb")
imgc.transform_colorspace("srgb")
img = imgc
except (BlobError, MissingDelegateError):
log.error("Invalid cover file content")
@@ -922,10 +902,7 @@ def save_cover(img, book_path):
return False, _("Only jpg/jpeg files are supported as coverfile")
if config.config_use_google_drive:
tmp_dir = os.path.join(gettempdir(), 'calibre_web')
if not os.path.isdir(tmp_dir):
os.mkdir(tmp_dir)
tmp_dir = get_temp_dir()
ret, message = save_cover_from_filestorage(tmp_dir, "uploaded_cover.jpg", img)
if ret is True:
gd.uploadFileToEbooksFolder(os.path.join(book_path, 'cover.jpg').replace("\\", "/"),
@@ -935,33 +912,85 @@ def save_cover(img, book_path):
else:
return False, message
else:
return save_cover_from_filestorage(os.path.join(config.config_calibre_dir, book_path), "cover.jpg", img)
return save_cover_from_filestorage(os.path.join(config.get_book_path(), book_path), "cover.jpg", img)
def do_download_file(book, book_format, client, data, headers):
book_name = data.name
download_name = filename = None
if config.config_use_google_drive:
# startTime = time.time()
df = gd.getFileFromEbooksFolder(book.path, data.name + "." + book_format)
# log.debug('%s', time.time() - startTime)
if df:
return gd.do_gdrive_download(df, headers)
if config.config_embed_metadata and (
(book_format == "kepub" and config.config_kepubifypath) or
(book_format != "kepub" and config.config_binariesdir)):
output_path = os.path.join(config.config_calibre_dir, book.path)
if not os.path.exists(output_path):
os.makedirs(output_path)
output = os.path.join(config.config_calibre_dir, book.path, book_name + "." + book_format)
gd.downloadFile(book.path, book_name + "." + book_format, output)
if book_format == "kepub" and config.config_kepubifypath:
filename, download_name = do_kepubify_metadata_replace(book, output)
elif book_format != "kepub" and config.config_binariesdir:
filename, download_name = do_calibre_export(book.id, book_format)
else:
return gd.do_gdrive_download(df, headers)
else:
abort(404)
else:
filename = os.path.join(config.config_calibre_dir, book.path)
if not os.path.isfile(os.path.join(filename, data.name + "." + book_format)):
filename = os.path.join(config.get_book_path(), book.path)
if not os.path.isfile(os.path.join(filename, book_name + "." + book_format)):
# ToDo: improve error handling
log.error('File not found: %s', os.path.join(filename, data.name + "." + book_format))
log.error('File not found: %s', os.path.join(filename, book_name + "." + book_format))
if client == "kobo" and book_format == "kepub":
headers["Content-Disposition"] = headers["Content-Disposition"].replace(".kepub", ".kepub.epub")
response = make_response(send_from_directory(filename, data.name + "." + book_format))
# ToDo Check headers parameter
for element in headers:
response.headers[element[0]] = element[1]
log.info('Downloading file: {}'.format(os.path.join(filename, data.name + "." + book_format)))
return response
if book_format == "kepub" and config.config_kepubifypath and config.config_embed_metadata:
filename, download_name = do_kepubify_metadata_replace(book, os.path.join(filename,
book_name + "." + book_format))
elif book_format != "kepub" and config.config_binariesdir and config.config_embed_metadata:
filename, download_name = do_calibre_export(book.id, book_format)
else:
download_name = book_name
# Clean up staged copies in /tmp/calibre_web after the response is sent
# (kepubify / calibre-export branches) so the temp dir does not grow unbounded.
if filename == get_temp_dir():
_tmp_path = os.path.join(filename, download_name + "." + book_format)
@after_this_request
def _cleanup_staged_download(resp):
try:
os.remove(_tmp_path)
except OSError as ex:
log.warning('Failed to remove staged download %s: %s', _tmp_path, ex)
return resp
response = make_response(send_from_directory(filename, download_name + "." + book_format))
# ToDo Check headers parameter
for element in headers:
response.headers[element[0]] = element[1]
log.info('Downloading file: \'%s\' by %s - %s', format(os.path.join(filename, book_name + "." + book_format)),
current_user.name, request.headers.get('X-Forwarded-For', request.remote_addr))
return response
def do_kepubify_metadata_replace(book, file_path):
custom_columns = (calibre_db.session.query(db.CustomColumns)
.filter(db.CustomColumns.mark_for_delete == 0)
.filter(db.CustomColumns.datatype.notin_(db.cc_exceptions))
.order_by(db.CustomColumns.label).all())
tree, cf_name = get_content_opf(file_path)
package = create_new_metadata_backup(book, custom_columns, current_user.locale, _("Cover"), lang_type=2)
content = replace_metadata(tree, package)
tmp_dir = get_temp_dir()
temp_file_name = str(uuid4())
# open zipfile and replace metadata block in content.opf
updateEpub(file_path, os.path.join(tmp_dir, temp_file_name + ".kepub"), cf_name, content)
return tmp_dir, temp_file_name
##################################
@@ -971,20 +1000,61 @@ def check_unrar(unrar_location):
return
if not os.path.exists(unrar_location):
return _('Unrar binary file not found')
return _('UnRar binary file not found')
try:
unrar_location = [unrar_location]
value = process_wait(unrar_location, pattern='UNRAR (.*) freeware')
if value:
version = value.group(1)
log.debug("unrar version %s", version)
log.debug("UnRar version %s", version)
except (OSError, UnicodeDecodeError) as err:
log.error_or_exception(err)
return _('Error executing UnRar')
def check_calibre(calibre_location):
if not calibre_location:
return
if not os.path.exists(calibre_location):
return _('Could not find the specified directory')
if not os.path.isdir(calibre_location):
return _('Please specify a directory, not a file')
try:
supported_binary_paths = [os.path.join(calibre_location, binary)
for binary in SUPPORTED_CALIBRE_BINARIES.values()]
binaries_available = [os.path.isfile(binary_path) for binary_path in supported_binary_paths]
binaries_executable = [os.access(binary_path, os.X_OK) for binary_path in supported_binary_paths]
if all(binaries_available) and all(binaries_executable):
values = [process_wait([binary_path, "--version"], pattern=r'\(calibre (.*)\)')
for binary_path in supported_binary_paths]
if all(values):
version = values[0].group(1)
log.debug("calibre version %s", version)
else:
return _('Calibre binaries not viable')
else:
ret_val = []
missing_binaries = [path for path, available in
zip(SUPPORTED_CALIBRE_BINARIES.values(), binaries_available) if not available]
missing_perms = [path for path, available in
zip(SUPPORTED_CALIBRE_BINARIES.values(), binaries_executable) if not available]
if missing_binaries:
ret_val.append(_('Missing calibre binaries: %(missing)s', missing=", ".join(missing_binaries)))
if missing_perms:
ret_val.append(_('Missing executable permissions: %(missing)s', missing=", ".join(missing_perms)))
return ", ".join(ret_val)
except (OSError, UnicodeDecodeError) as err:
log.error_or_exception(err)
return _('Error executing Calibre')
def json_serial(obj):
"""JSON serializer for objects not serializable by default json code"""
@@ -1009,43 +1079,44 @@ def tags_filters():
# checks if domain is in database (including wildcards)
# example SELECT * FROM @TABLE WHERE 'abcdefg' LIKE Name;
# example SELECT * FROM @TABLE WHERE 'abcdefg' LIKE Name;
# from https://code.luasoftware.com/tutorials/flask/execute-raw-sql-in-flask-sqlalchemy/
# in all calls the email address is checked for validity
def check_valid_domain(domain_text):
sql = "SELECT * FROM registration WHERE (:domain LIKE domain and allow = 1);"
result = ub.session.query(ub.Registration).from_statement(text(sql)).params(domain=domain_text).all()
if not len(result):
if not len(ub.session.query(ub.Registration).from_statement(text(sql)).params(domain=domain_text).all()):
return False
sql = "SELECT * FROM registration WHERE (:domain LIKE domain and allow = 0);"
result = ub.session.query(ub.Registration).from_statement(text(sql)).params(domain=domain_text).all()
return not len(result)
return not len(ub.session.query(ub.Registration).from_statement(text(sql)).params(domain=domain_text).all())
def get_download_link(book_id, book_format, client):
book_format = book_format.split(".")[0]
book = calibre_db.get_filtered_book(book_id, allow_show_archived=True)
data1= ""
if book:
data1 = calibre_db.get_book_format(book.id, book_format.upper())
if data1:
# collect downloaded books only for registered user and not for anonymous user
if current_user.is_authenticated:
ub.update_download(book_id, int(current_user.id))
file_name = book.title
if len(book.authors) > 0:
file_name = file_name + ' - ' + book.authors[0].name
original_name = file_name
file_name = get_valid_filename(file_name, replace_whitespace=False, force_unidecode=True)
if client == "kindle":
quoted_file_name = file_name
else:
native_name = get_valid_filename(original_name, replace_whitespace=False, force_unidecode=False)
quoted_file_name = quote(native_name)
headers = Headers()
headers["Content-Type"] = mimetypes.types_map.get('.' + book_format, "application/octet-stream")
headers["Content-Disposition"] = ('attachment; filename="{}.{}"; filename*=UTF-8\'\'{}.{}').format(
file_name, book_format, quoted_file_name, book_format)
return do_download_file(book, book_format, client, data1, headers)
else:
log.error("Book id {} not found for downloading".format(book_id))
abort(404)
if data1:
# collect downloaded books only for registered user and not for anonymous user
if current_user.is_authenticated:
ub.update_download(book_id, int(current_user.id))
file_name = book.title
if len(book.authors) > 0:
file_name = file_name + ' - ' + book.authors[0].name
file_name = get_valid_filename(file_name, replace_whitespace=False)
headers = Headers()
headers["Content-Type"] = mimetypes.types_map.get('.' + book_format, "application/octet-stream")
headers["Content-Disposition"] = "attachment; filename=%s.%s; filename*=UTF-8''%s.%s" % (
quote(file_name.encode('utf-8')), book_format, quote(file_name.encode('utf-8')), book_format)
return do_download_file(book, book_format, client, data1, headers)
else:
abort(404)
abort(404)
def clear_cover_thumbnail_cache(book_id):
+31 -25
View File
@@ -15,24 +15,17 @@
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys
from .iso_language_names import LANGUAGE_NAMES as _LANGUAGE_NAMES
from . import logger
from .string_helper import strip_whitespaces
log = logger.create()
try:
from iso639 import languages, __version__
get = languages.get
except ImportError:
from pycountry import languages as pyc_languages
try:
import pkg_resources
__version__ = pkg_resources.get_distribution('pycountry').version + ' (PyCountry)'
del pkg_resources
except (ImportError, Exception):
__version__ = "? (PyCountry)"
def _copy_fields(l):
l.part1 = getattr(l, 'alpha_2', None)
@@ -46,35 +39,48 @@ except ImportError:
return _copy_fields(pyc_languages.get(alpha_2=part1))
if name is not None:
return _copy_fields(pyc_languages.get(name=name))
except ImportError as ex:
if sys.version_info >= (3, 12):
print("Python 3.12 isn't compatible with iso-639. Please install pycountry.")
from iso639 import languages
get = languages.get
def get_language_names(locale):
return _LANGUAGE_NAMES.get(str(locale))
names = _LANGUAGE_NAMES.get(str(locale))
if names is None:
names = _LANGUAGE_NAMES.get(locale.language)
return names
def get_language_name(locale, lang_code):
try:
return get_language_names(locale)[lang_code]
except KeyError:
log.error('Missing translation for language name: {}'.format(lang_code))
return "Unknown"
UNKNOWN_TRANSLATION = "Unknown"
names = get_language_names(locale)
if names is None:
log.error(f"Missing language names for locale: {str(locale)}/{locale.language}")
return UNKNOWN_TRANSLATION
name = names.get(lang_code, UNKNOWN_TRANSLATION)
if name == UNKNOWN_TRANSLATION:
log.error("Missing translation for language name: {}".format(lang_code))
return name
def get_language_codes(locale, language_names, remainder=None):
language_names = set(x.strip().lower() for x in language_names if x)
def get_language_code_from_name(locale, language_names, remainder=None):
language_names = set(strip_whitespaces(x).lower() for x in language_names if x)
lang = list()
for k, v in get_language_names(locale).items():
v = v.lower()
if v in language_names:
lang.append(k)
language_names.remove(v)
for key, val in get_language_names(locale).items():
val = val.lower()
if val in language_names:
lang.append(key)
language_names.remove(val)
if remainder is not None and language_names:
remainder.extend(language_names)
return lang
def get_valid_language_codes(locale, language_names, remainder=None):
def get_valid_language_codes_from_code(locale, language_names, remainder=None):
lang = list()
if "" in language_names:
language_names.remove("")
@@ -95,6 +101,6 @@ def get_lang3(lang):
ret_value = lang
else:
ret_value = ""
except KeyError:
except (KeyError, AttributeError):
ret_value = lang
return ret_value
File diff suppressed because it is too large Load Diff
+26 -18
View File
@@ -27,10 +27,10 @@ import datetime
import mimetypes
from uuid import uuid4
# from babel.dates import format_date
from flask import Blueprint, request, url_for
from flask import Blueprint, request, url_for, g
from flask_babel import format_date
from flask_login import current_user
from .cw_login import current_user
from .clean_html import clean_string as html_clean_string
from . import constants, logger
@@ -44,6 +44,8 @@ def url_for_other_page(page):
args = request.view_args.copy()
args['page'] = page
for get, val in request.args.items():
if get == "page":
continue
args[get] = val
return url_for(request.endpoint, **args)
@@ -112,21 +114,12 @@ def yesno(value, yes, no):
@jinjia.app_template_filter('formatfloat')
def formatfloat(value, decimals=1):
value = 0 if not value else value
return ('{0:.' + str(decimals) + 'f}').format(value).rstrip('0').rstrip('.')
@jinjia.app_template_filter('formatseriesindex')
def formatseriesindex_filter(series_index):
if series_index:
try:
if int(series_index) - series_index == 0:
return int(series_index)
else:
return series_index
except ValueError:
return series_index
return 0
if not value or (isinstance(value, str) and not value.is_numeric()):
return value
formated_value = ('{0:.' + str(decimals) + 'f}').format(value)
if formated_value.endswith('.' + "0" * decimals):
formated_value = formated_value.rstrip('0').rstrip('.')
return formated_value
@jinjia.app_template_filter('escapedlink')
@@ -180,3 +173,18 @@ def get_cover_srcset(series):
url = url_for('web.get_series_cover', series_id=series.id, resolution=shortname, c=cache_timestamp())
srcset.append(f'{url} {resolution}x')
return ', '.join(srcset)
@jinjia.app_template_filter('music')
def contains_music(book_formats):
result = False
for format in book_formats:
if format.format.lower() in g.constants.EXTENSIONS_AUDIO:
result = True
return result
@jinjia.app_template_filter('clean_string')
def clean_string(unsafe_text):
return html_clean_string(unsafe_text)
+230 -171
View File
@@ -18,13 +18,14 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import base64
import datetime
from datetime import datetime, timezone
import os
import uuid
import zipfile
from time import gmtime, strftime
import json
from urllib.parse import unquote
import requests
from flask import (
Blueprint,
@@ -36,19 +37,16 @@ from flask import (
redirect,
abort
)
from flask_login import current_user
from .cw_login import current_user
from werkzeug.datastructures import Headers
from sqlalchemy import func
from sqlalchemy.sql.expression import and_, or_
from sqlalchemy.exc import StatementError
from sqlalchemy.sql import select
import requests
from . import config, logger, kobo_auth, db, calibre_db, helper, shelf as shelf_lib, ub, csrf, kobo_sync_status
from . import isoLanguages
from . import isoLanguages, limiter
from .epub import get_epub_layout
from .constants import sqlalchemy_version2, COVER_THUMBNAIL_SMALL
from .constants import COVER_THUMBNAIL_SMALL, COVER_THUMBNAIL_MEDIUM, COVER_THUMBNAIL_LARGE, BASE_DIR
from .helper import get_download_link
from .services import SyncToken as SyncToken
from .web import download_required
@@ -56,7 +54,7 @@ from .kobo_auth import requires_kobo_auth, get_auth_token
KOBO_FORMATS = {"KEPUB": ["KEPUB"], "EPUB": ["EPUB3", "EPUB"]}
KOBO_STOREAPI_URL = "https://storeapi.kobo.com"
KOBO_IMAGEHOST_URL = "https://kbimages1-a.akamaihd.net"
KOBO_IMAGEHOST_URL = "https://cdn.kobo.com/book-images"
SYNC_ITEM_LIMIT = 100
@@ -107,24 +105,29 @@ def make_request_to_kobo_store(sync_token=None):
return store_response
def redirect_or_proxy_request():
def redirect_or_proxy_request(auth=False):
if config.config_kobo_proxy:
if request.method == "GET":
return redirect(get_store_url_for_current_request(), 307)
else:
# The Kobo device turns other request types into GET requests on redirects,
# so we instead proxy to the Kobo store ourselves.
store_response = make_request_to_kobo_store()
try:
if request.method == "GET":
alfa = redirect(get_store_url_for_current_request(), 307)
return alfa
else:
# The Kobo device turns other request types into GET requests on redirects,
# so we instead proxy to the Kobo store ourselves.
store_response = make_request_to_kobo_store()
response_headers = store_response.headers
for header_key in CONNECTION_SPECIFIC_HEADERS:
response_headers.pop(header_key, default=None)
response_headers = store_response.headers
for header_key in CONNECTION_SPECIFIC_HEADERS:
response_headers.pop(header_key, default=None)
return make_response(
store_response.content, store_response.status_code, response_headers.items()
)
else:
return make_response(jsonify({}))
return make_response(
store_response.content, store_response.status_code, response_headers.items()
)
except Exception as e:
log.error("Failed to receive or parse response from Kobo's endpoint: {}".format(e))
if auth:
return make_calibre_web_auth_response()
return make_response(jsonify({}))
def convert_to_kobo_timestamp_string(timestamp):
@@ -132,30 +135,33 @@ def convert_to_kobo_timestamp_string(timestamp):
return timestamp.strftime("%Y-%m-%dT%H:%M:%SZ")
except AttributeError as exc:
log.debug("Timestamp not valid: {}".format(exc))
return datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
@kobo.route("/v1/library/sync")
@requires_kobo_auth
@download_required
def HandleSyncRequest():
if not current_user.role_download():
log.info("Users need download permissions for syncing library to Kobo reader")
return abort(403)
sync_token = SyncToken.SyncToken.from_headers(request.headers)
log.info("Kobo library sync request received.")
log.info("Kobo library sync request received")
log.debug("SyncToken: {}".format(sync_token))
log.debug("Download link format {}".format(get_download_url_for_book('[bookid]', '[bookformat]')))
if not current_app.wsgi_app.is_proxied:
log.debug('Kobo: Received unproxied request, changed request port to external server port')
# if no books synced don't respect sync_token
if not ub.session.query(ub.KoboSyncedBooks).filter(ub.KoboSyncedBooks.user_id == current_user.id).count():
sync_token.books_last_modified = datetime.datetime.min
sync_token.books_last_created = datetime.datetime.min
sync_token.reading_state_last_modified = datetime.datetime.min
sync_token.books_last_modified = datetime.min
sync_token.books_last_created = datetime.min
sync_token.reading_state_last_modified = datetime.min
new_books_last_modified = sync_token.books_last_modified # needed for sync selected shelfs only
new_books_last_created = sync_token.books_last_created # needed to distinguish between new and changed entitlement
new_reading_state_last_modified = sync_token.reading_state_last_modified
new_archived_last_modified = datetime.datetime.min
new_archived_last_modified = datetime.min
sync_results = []
# We reload the book database so that the user gets a fresh view of the library
@@ -165,16 +171,10 @@ def HandleSyncRequest():
only_kobo_shelves = current_user.kobo_only_shelves_sync
if only_kobo_shelves:
if sqlalchemy_version2:
changed_entries = select(db.Books,
ub.ArchivedBook.last_modified,
ub.BookShelf.date_added,
ub.ArchivedBook.is_archived)
else:
changed_entries = calibre_db.session.query(db.Books,
ub.ArchivedBook.last_modified,
ub.BookShelf.date_added,
ub.ArchivedBook.is_archived)
changed_entries = calibre_db.session.query(db.Books,
ub.ArchivedBook.last_modified,
ub.BookShelf.date_added,
ub.ArchivedBook.is_archived)
changed_entries = (changed_entries
.join(db.Data).outerjoin(ub.ArchivedBook, and_(db.Books.id == ub.ArchivedBook.book_id,
ub.ArchivedBook.user_id == current_user.id))
@@ -191,12 +191,9 @@ def HandleSyncRequest():
.filter(ub.Shelf.kobo_sync)
.distinct())
else:
if sqlalchemy_version2:
changed_entries = select(db.Books, ub.ArchivedBook.last_modified, ub.ArchivedBook.is_archived)
else:
changed_entries = calibre_db.session.query(db.Books,
ub.ArchivedBook.last_modified,
ub.ArchivedBook.is_archived)
changed_entries = calibre_db.session.query(db.Books,
ub.ArchivedBook.last_modified,
ub.ArchivedBook.is_archived)
changed_entries = (changed_entries
.join(db.Data).outerjoin(ub.ArchivedBook, and_(db.Books.id == ub.ArchivedBook.book_id,
ub.ArchivedBook.user_id == current_user.id))
@@ -208,19 +205,16 @@ def HandleSyncRequest():
.order_by(db.Books.id))
reading_states_in_new_entitlements = []
if sqlalchemy_version2:
books = calibre_db.session.execute(changed_entries.limit(SYNC_ITEM_LIMIT))
else:
books = changed_entries.limit(SYNC_ITEM_LIMIT)
books = changed_entries.limit(SYNC_ITEM_LIMIT)
log.debug("Books to Sync: {}".format(len(books.all())))
for book in books:
formats = [data.format for data in book.Books.data]
if 'KEPUB' not in formats and config.config_kepubifypath and 'EPUB' in formats:
helper.convert_book_format(book.Books.id, config.config_calibre_dir, 'EPUB', 'KEPUB', current_user.name)
helper.convert_book_format(book.Books.id, config.get_book_path(), 'EPUB', 'KEPUB', current_user.name)
kobo_reading_state = get_or_create_reading_state(book.Books.id)
entitlement = {
"BookEntitlement": create_book_entitlement(book.Books, archived=(book.is_archived == True)),
"BookEntitlement": create_book_entitlement(book.Books, archived=(book.is_archived==True)),
"BookMetadata": get_metadata(book.Books),
}
@@ -229,7 +223,7 @@ def HandleSyncRequest():
new_reading_state_last_modified = max(new_reading_state_last_modified, kobo_reading_state.last_modified)
reading_states_in_new_entitlements.append(book.Books.id)
ts_created = book.Books.timestamp
ts_created = book.Books.timestamp.replace(tzinfo=None)
try:
ts_created = max(ts_created, book.date_added)
@@ -242,7 +236,7 @@ def HandleSyncRequest():
sync_results.append({"ChangedEntitlement": entitlement})
new_books_last_modified = max(
book.Books.last_modified, new_books_last_modified
book.Books.last_modified.replace(tzinfo=None), new_books_last_modified
)
try:
new_books_last_modified = max(
@@ -254,27 +248,16 @@ def HandleSyncRequest():
new_books_last_created = max(ts_created, new_books_last_created)
kobo_sync_status.add_synced_books(book.Books.id)
if sqlalchemy_version2:
max_change = calibre_db.session.execute(changed_entries
.filter(ub.ArchivedBook.is_archived)
.filter(ub.ArchivedBook.user_id == current_user.id)
.order_by(func.datetime(ub.ArchivedBook.last_modified).desc()))\
.columns(db.Books).first()
else:
max_change = changed_entries.from_self().filter(ub.ArchivedBook.is_archived)\
.filter(ub.ArchivedBook.user_id == current_user.id) \
.order_by(func.datetime(ub.ArchivedBook.last_modified).desc()).first()
max_change = changed_entries.filter(ub.ArchivedBook.is_archived)\
.filter(ub.ArchivedBook.user_id == current_user.id) \
.order_by(func.datetime(ub.ArchivedBook.last_modified).desc()).first()
max_change = max_change.last_modified if max_change else new_archived_last_modified
new_archived_last_modified = max(new_archived_last_modified, max_change)
# no. of books returned
if sqlalchemy_version2:
entries = calibre_db.session.execute(changed_entries).all()
book_count = len(entries)
else:
book_count = changed_entries.count()
book_count = changed_entries.count()
# last entry:
cont_sync = bool(book_count)
log.debug("Remaining books to Sync: {}".format(book_count))
@@ -337,13 +320,13 @@ def generate_sync_response(sync_token, sync_results, set_cont=False):
extra_headers["x-kobo-recent-reads"] = store_response.headers.get("x-kobo-recent-reads")
except Exception as ex:
log.error("Failed to receive or parse response from Kobo's sync endpoint: {}".format(ex))
log.error_or_exception("Failed to receive or parse response from Kobo's sync endpoint: {}".format(ex))
if set_cont:
extra_headers["x-kobo-sync"] = "continue"
sync_token.to_headers(extra_headers)
# log.debug("Kobo Sync Content: {}".format(sync_results))
# jsonify decodes the unicode string different to what kobo expects
# jsonify decodes the Unicode string different to what kobo expects
response = make_response(json.dumps(sync_results), extra_headers)
response.headers["Content-Type"] = "application/json; charset=utf-8"
return response
@@ -367,7 +350,7 @@ def HandleMetadataRequest(book_uuid):
return response
def get_download_url_for_book(book, book_format):
def get_download_url_for_book(book_id, book_format):
if not current_app.wsgi_app.is_proxied:
if ':' in request.host and not request.host.endswith(']'):
host = "".join(request.host.split(':')[:-1])
@@ -379,13 +362,13 @@ def get_download_url_for_book(book, book_format):
url_base=host,
url_port=config.config_external_port,
auth_token=get_auth_token(),
book_id=book.id,
book_id=book_id,
book_format=book_format.lower()
)
return url_for(
"kobo.download_book",
auth_token=kobo_auth.get_auth_token(),
book_id=book.id,
auth_token=get_auth_token(),
book_id=book_id,
book_format=book_format.lower(),
_external=True,
)
@@ -395,7 +378,7 @@ def create_book_entitlement(book, archived):
book_uuid = str(book.uuid)
return {
"Accessibility": "Full",
"ActivePeriod": {"From": convert_to_kobo_timestamp_string(datetime.datetime.utcnow())},
"ActivePeriod": {"From": convert_to_kobo_timestamp_string(datetime.now(timezone.utc))},
"Created": convert_to_kobo_timestamp_string(book.timestamp),
"CrossRevisionId": book_uuid,
"Id": book_uuid,
@@ -443,7 +426,7 @@ def get_series(book):
def get_seriesindex(book):
return book.series_index or 1
return book.series_index if isinstance(book.series_index, float) else 1
def get_language(book):
@@ -468,7 +451,7 @@ def get_metadata(book):
{
"Format": kobo_format,
"Size": book_data.uncompressed_size,
"Url": get_download_url_for_book(book, book_data.format),
"Url": get_download_url_for_book(book.id, book_data.format),
# The Kobo forma accepts platforms: (Generic, Android)
"Platform": "Generic",
# "DrmType": "None", # Not required
@@ -506,23 +489,26 @@ def get_metadata(book):
if get_series(book):
name = get_series(book)
metadata["Series"] = {
"Name": get_series(book),
"Number": get_seriesindex(book), # ToDo Check int() ?
"NumberFloat": float(get_seriesindex(book)),
# Get a deterministic id based on the series name.
"Id": str(uuid.uuid3(uuid.NAMESPACE_DNS, name)),
}
try:
metadata["Series"] = {
"Name": get_series(book),
"Number": get_seriesindex(book), # ToDo Check int() ?
"NumberFloat": float(get_seriesindex(book)),
# Get a deterministic id based on the series name.
"Id": str(uuid.uuid3(uuid.NAMESPACE_DNS, name)),
}
except Exception as e:
print(e)
return metadata
@csrf.exempt
@kobo.route("/v1/library/tags", methods=["POST", "DELETE"])
@requires_kobo_auth
# Creates a Shelf with the given items, and returns the shelf's uuid.
def HandleTagCreate():
# catch delete requests, otherwise the are handled in the book delete handler
# catch delete requests, otherwise they are handled in the book delete handler
if request.method == "DELETE":
abort(405)
name, items = None, None
@@ -716,20 +702,12 @@ def sync_shelves(sync_token, sync_results, only_kobo_shelves=False):
})
extra_filters.append(ub.Shelf.kobo_sync)
if sqlalchemy_version2:
shelflist = ub.session.execute(select(ub.Shelf).outerjoin(ub.BookShelf).filter(
or_(func.datetime(ub.Shelf.last_modified) > sync_token.tags_last_modified,
func.datetime(ub.BookShelf.date_added) > sync_token.tags_last_modified),
ub.Shelf.user_id == current_user.id,
*extra_filters
).distinct().order_by(func.datetime(ub.Shelf.last_modified).asc())).columns(ub.Shelf)
else:
shelflist = ub.session.query(ub.Shelf).outerjoin(ub.BookShelf).filter(
or_(func.datetime(ub.Shelf.last_modified) > sync_token.tags_last_modified,
func.datetime(ub.BookShelf.date_added) > sync_token.tags_last_modified),
ub.Shelf.user_id == current_user.id,
*extra_filters
).distinct().order_by(func.datetime(ub.Shelf.last_modified).asc())
shelflist = ub.session.query(ub.Shelf).outerjoin(ub.BookShelf).filter(
or_(func.datetime(ub.Shelf.last_modified) > sync_token.tags_last_modified,
func.datetime(ub.BookShelf.date_added) > sync_token.tags_last_modified),
ub.Shelf.user_id == current_user.id,
*extra_filters
).distinct().order_by(func.datetime(ub.Shelf.last_modified).asc())
for shelf in shelflist:
if not shelf_lib.check_shelf_view_permissions(shelf):
@@ -753,7 +731,7 @@ def sync_shelves(sync_token, sync_results, only_kobo_shelves=False):
ub.session_commit()
# Creates a Kobo "Tag" object from a ub.Shelf object
# Creates a Kobo "Tag" object from an ub.Shelf object
def create_kobo_tag(shelf):
tag = {
"Created": convert_to_kobo_timestamp_string(shelf.created),
@@ -823,7 +801,7 @@ def HandleStateRequest(book_uuid):
if new_book_read_status == ub.ReadBook.STATUS_IN_PROGRESS \
and new_book_read_status != book_read.read_status:
book_read.times_started_reading += 1
book_read.last_time_started_reading = datetime.datetime.utcnow()
book_read.last_time_started_reading = datetime.now(timezone.utc)
book_read.read_status = new_book_read_status
update_results_response["StatusInfoResult"] = {"Result": "Success"}
except (KeyError, TypeError, ValueError, StatementError):
@@ -833,6 +811,8 @@ def HandleStateRequest(book_uuid):
ub.session.merge(kobo_reading_state)
ub.session_commit()
update_results_response["LastModified"] = convert_to_kobo_timestamp_string(kobo_reading_state.last_modified)
update_results_response["PriorityTimestamp"] = convert_to_kobo_timestamp_string(kobo_reading_state.priority_timestamp)
return jsonify({
"RequestResult": "Success",
"UpdateResults": [update_results_response],
@@ -909,14 +889,21 @@ def get_statistics_response(statistics):
return resp
def _clean_progress(value):
"""Return progress as int if it's a whole number, preserving Kobo device expectations."""
if value is not None and value == int(value):
return int(value)
return value
def get_current_bookmark_response(current_bookmark):
resp = {
"LastModified": convert_to_kobo_timestamp_string(current_bookmark.last_modified),
}
if current_bookmark.progress_percent:
resp["ProgressPercent"] = current_bookmark.progress_percent
if current_bookmark.content_source_progress_percent:
resp["ContentSourceProgressPercent"] = current_bookmark.content_source_progress_percent
if current_bookmark.progress_percent is not None:
resp["ProgressPercent"] = _clean_progress(current_bookmark.progress_percent)
if current_bookmark.content_source_progress_percent is not None:
resp["ContentSourceProgressPercent"] = _clean_progress(current_bookmark.content_source_progress_percent)
if current_bookmark.location_value:
resp["Location"] = {
"Value": current_bookmark.location_value,
@@ -930,20 +917,31 @@ def get_current_bookmark_response(current_bookmark):
@kobo.route("/<book_uuid>/<width>/<height>/<Quality>/<isGreyscale>/image.jpg")
@requires_kobo_auth
def HandleCoverImageRequest(book_uuid, width, height, Quality, isGreyscale):
book_cover = helper.get_book_cover_with_uuid(book_uuid, resolution=COVER_THUMBNAIL_SMALL)
if not book_cover:
if config.config_kobo_proxy:
log.debug("Cover for unknown book: %s proxied to kobo" % book_uuid)
return redirect(KOBO_IMAGEHOST_URL +
"/{book_uuid}/{width}/{height}/false/image.jpg".format(book_uuid=book_uuid,
width=width,
height=height), 307)
try:
if int(height) > 1000:
resolution = COVER_THUMBNAIL_LARGE
elif int(height) > 500:
resolution = COVER_THUMBNAIL_MEDIUM
else:
log.debug("Cover for unknown book: %s requested" % book_uuid)
# additional proxy request make no sense, -> direct return
return make_response(jsonify({}))
log.debug("Cover request received for book %s" % book_uuid)
return book_cover
resolution = COVER_THUMBNAIL_SMALL
except ValueError:
log.error("Requested height %s of book %s is invalid" % (book_uuid, height))
resolution = COVER_THUMBNAIL_SMALL
book_cover = helper.get_book_cover_with_uuid(book_uuid, resolution=resolution)
if book_cover:
log.debug("Serving local cover image of book %s" % book_uuid)
return book_cover
if not config.config_kobo_proxy:
log.debug("Returning 404 for cover image of unknown book %s" % book_uuid)
# additional proxy request make no sense, -> direct return
return abort(404)
log.debug("Redirecting request for cover image of unknown book %s to Kobo" % book_uuid)
return redirect(KOBO_IMAGEHOST_URL +
"/{book_uuid}/{width}/{height}/false/image.jpg".format(book_uuid=book_uuid,
width=width,
height=height), 307)
@kobo.route("")
@@ -970,9 +968,12 @@ def HandleBookDeletionRequest(book_uuid):
# TODO: Implement the following routes
@csrf.exempt
@kobo.route("/v1/library/<dummy>", methods=["DELETE", "GET"])
@kobo.route("/v1/library/<dummy>", methods=["DELETE", "GET", "POST"])
@kobo.route("/v1/library/<dummy>/preview", methods=["POST"])
def HandleUnimplementedRequest(dummy=None):
log.debug("Unimplemented Library Request received: %s (request is forwarded to kobo if configured)", request.base_url)
[limiter.limiter.clear(limit.limit, *limit.request_args) for limit in limiter.current_limits]
log.debug("Unimplemented Library Request received: %s (request is forwarded to kobo if configured)",
request.base_url)
return redirect_or_proxy_request()
@@ -983,7 +984,11 @@ def HandleUnimplementedRequest(dummy=None):
@kobo.route("/v1/user/wishlist", methods=["GET", "POST"])
@kobo.route("/v1/user/recommendations", methods=["GET", "POST"])
@kobo.route("/v1/analytics/<dummy>", methods=["GET", "POST"])
@kobo.route("/v1/assets", methods=["GET"])
def HandleUserRequest(dummy=None):
[limiter.limiter.clear(limit.limit, *limit.request_args) for limit in limiter.current_limits]
log.error("Key: {}".format(limiter.current_limit.key))
log.error("Remaining: {}".format(limiter.current_limit.remaining))
log.debug("Unimplemented User Request received: %s (request is forwarded to kobo if configured)", request.base_url)
return redirect_or_proxy_request()
@@ -991,6 +996,7 @@ def HandleUserRequest(dummy=None):
@csrf.exempt
@kobo.route("/v1/user/loyalty/benefits", methods=["GET"])
def handle_benefits():
[limiter.limiter.clear(limit.limit, *limit.request_args) for limit in limiter.current_limits]
if config.config_kobo_proxy:
return redirect_or_proxy_request()
else:
@@ -1000,6 +1006,7 @@ def handle_benefits():
@csrf.exempt
@kobo.route("/v1/analytics/gettests", methods=["GET", "POST"])
def handle_getests():
[limiter.limiter.clear(limit.limit, *limit.request_args) for limit in limiter.current_limits]
if config.config_kobo_proxy:
return redirect_or_proxy_request()
else:
@@ -1021,10 +1028,14 @@ def handle_getests():
@kobo.route("/v1/products/dailydeal", methods=["GET", "POST"])
@kobo.route("/v1/products/deals", methods=["GET", "POST"])
@kobo.route("/v1/products", methods=["GET", "POST"])
@kobo.route("/v1/products/<path:dummy>", methods=["GET", "POST"])
@kobo.route("/v1/products/<path:dummy>/", methods=["GET", "POST"])
@kobo.route("/v1/affiliate", methods=["GET", "POST"])
@kobo.route("/v1/deals", methods=["GET", "POST"])
def HandleProductsRequest(dummy=None):
log.debug("Unimplemented Products Request received: %s (request is forwarded to kobo if configured)", request.base_url)
[limiter.limiter.clear(limit.limit, *limit.request_args) for limit in limiter.current_limits]
log.debug("Unimplemented Products Request received: %s (request is forwarded to kobo if configured)",
request.base_url)
return redirect_or_proxy_request()
@@ -1041,20 +1052,23 @@ def make_calibre_web_auth_response():
"RefreshToken": RefreshToken,
"TokenType": "Bearer",
"TrackingId": str(uuid.uuid4()),
"UserKey": content['UserKey'],
"UserKey": content.get('UserKey', ""),
}
)
)
@csrf.exempt
@kobo.route("/v1/auth/refresh", methods=["POST"])
@kobo.route("/v1/auth/device", methods=["POST"])
@requires_kobo_auth
def HandleAuthRequest():
log.error(limiter.current_limit)
log.error(limiter.current_limit)
log.debug('Kobo Auth request')
if config.config_kobo_proxy:
try:
return redirect_or_proxy_request()
return redirect_or_proxy_request(auth=True)
except Exception:
log.error("Failed to receive or parse response from Kobo's auth endpoint. Falling back to un-proxied mode.")
return make_calibre_web_auth_response()
@@ -1092,7 +1106,7 @@ def HandleInitRequest():
kobo_resources["image_host"] = calibre_web_url
kobo_resources["image_url_quality_template"] = unquote(calibre_web_url +
url_for("kobo.HandleCoverImageRequest",
auth_token=kobo_auth.get_auth_token(),
auth_token=get_auth_token(),
book_uuid="{ImageId}",
width="{width}",
height="{height}",
@@ -1100,15 +1114,17 @@ def HandleInitRequest():
isGreyscale='isGreyscale'))
kobo_resources["image_url_template"] = unquote(calibre_web_url +
url_for("kobo.HandleCoverImageRequest",
auth_token=kobo_auth.get_auth_token(),
auth_token=get_auth_token(),
book_uuid="{ImageId}",
width="{width}",
height="{height}",
isGreyscale='false'))
kobo_resources["library_sync"] = calibre_web_url + url_for("kobo.HandleSyncRequest",
auth_token=kobo_auth.get_auth_token())
else:
kobo_resources["image_host"] = url_for("web.index", _external=True).strip("/")
kobo_resources["image_url_quality_template"] = unquote(url_for("kobo.HandleCoverImageRequest",
auth_token=kobo_auth.get_auth_token(),
auth_token=get_auth_token(),
book_uuid="{ImageId}",
width="{width}",
height="{height}",
@@ -1116,12 +1132,15 @@ def HandleInitRequest():
isGreyscale='isGreyscale',
_external=True))
kobo_resources["image_url_template"] = unquote(url_for("kobo.HandleCoverImageRequest",
auth_token=kobo_auth.get_auth_token(),
auth_token=get_auth_token(),
book_uuid="{ImageId}",
width="{width}",
height="{height}",
isGreyscale='false',
_external=True))
kobo_resources["library_sync"] = url_for("kobo.HandleSyncRequest",
auth_token=kobo_auth.get_auth_token(),
_external=True)
response = make_response(jsonify({"Resources": kobo_resources}))
response.headers["x-kobo-apitoken"] = "e30="
@@ -1137,26 +1156,46 @@ def download_book(book_id, book_format):
def NATIVE_KOBO_RESOURCES():
kobo_file = os.path.join(BASE_DIR, "kobo_resources.txt")
try:
if os.path.isfile(kobo_file):
with open(kobo_file, "r") as f:
lines = f.read()
return json.loads(lines)
except Exception as e:
log.error(e)
return {
"account_page": "https://secure.kobobooks.com/profile",
"account_page": "https://www.kobo.com/account/settings",
"account_page_rakuten": "https://my.rakuten.co.jp/",
"add_device": "https://storeapi.kobo.com/v1/user/add-device",
"add_entitlement": "https://storeapi.kobo.com/v1/library/{RevisionIds}",
"affiliaterequest": "https://storeapi.kobo.com/v1/affiliate",
"assets": "https://storeapi.kobo.com/v1/assets",
"audiobook": "https://storeapi.kobo.com/v1/products/audiobooks/{ProductId}",
"audiobook_detail_page": "https://www.kobo.com/{region}/{language}/audiobook/{slug}",
"audiobook_landing_page": "https://www.kobo.com/{region}/{language}/audiobooks",
"audiobook_preview": "https://storeapi.kobo.com/v1/products/audiobooks/{Id}/preview",
"audiobook_purchase_withcredit": "https://storeapi.kobo.com/v1/store/audiobook/{Id}",
"audiobook_subscription_orange_deal_inclusion_url": "https://authorize.kobo.com/inclusion",
"authorproduct_recommendations": "https://storeapi.kobo.com/v1/products/books/authors/recommendations",
"autocomplete": "https://storeapi.kobo.com/v1/products/autocomplete",
"blackstone_header": {"key": "x-amz-request-payer", "value": "requester"},
"blackstone_header": {
"key": "x-amz-request-payer",
"value": "requester"
},
"book": "https://storeapi.kobo.com/v1/products/books/{ProductId}",
"book_detail_page": "https://store.kobobooks.com/{culture}/ebook/{slug}",
"book_detail_page_rakuten": "https://books.rakuten.co.jp/rk/{crossrevisionid}",
"book_landing_page": "https://store.kobobooks.com/ebooks",
"book_detail_page": "https://www.kobo.com/{region}/{language}/ebook/{slug}",
"book_detail_page_rakuten": "http://books.rakuten.co.jp/rk/{crossrevisionid}",
"book_landing_page": "https://www.kobo.com/ebooks",
"book_subscription": "https://storeapi.kobo.com/v1/products/books/subscriptions",
"browse_history": "https://storeapi.kobo.com/v1/user/browsehistory",
"categories": "https://storeapi.kobo.com/v1/categories",
"categories_page": "https://store.kobobooks.com/ebooks/categories",
"categories_page": "https://www.kobo.com/ebooks/categories",
"category": "https://storeapi.kobo.com/v1/categories/{CategoryId}",
"category_featured_lists": "https://storeapi.kobo.com/v1/categories/{CategoryId}/featured",
"category_products": "https://storeapi.kobo.com/v1/categories/{CategoryId}/products",
"checkout_borrowed_book": "https://storeapi.kobo.com/v1/library/borrow",
"client_authd_referral": "https://authorize.kobo.com/api/AuthenticatedReferral/client/v1/getLink",
"configuration_data": "https://storeapi.kobo.com/v1/configuration",
"content_access_book": "https://storeapi.kobo.com/v1/products/books/{ProductId}/access",
"customer_care_live_chat": "https://v2.zopim.com/widget/livechat.html?key=Y6gwUmnu4OATxN3Tli4Av9bYN319BTdO",
@@ -1167,92 +1206,112 @@ def NATIVE_KOBO_RESOURCES():
"delete_tag_items": "https://storeapi.kobo.com/v1/library/tags/{TagId}/items/delete",
"device_auth": "https://storeapi.kobo.com/v1/auth/device",
"device_refresh": "https://storeapi.kobo.com/v1/auth/refresh",
"dictionary_host": "https://kbdownload1-a.akamaihd.net",
"dictionary_host": "https://ereaderfiles.kobo.com",
"discovery_host": "https://discovery.kobobooks.com",
"ereaderdevices": "https://storeapi.kobo.com/v2/products/EReaderDeviceFeeds",
"eula_page": "https://www.kobo.com/termsofuse?style=onestore",
"exchange_auth": "https://storeapi.kobo.com/v1/auth/exchange",
"external_book": "https://storeapi.kobo.com/v1/products/books/external/{Ids}",
"facebook_sso_page":
"https://authorize.kobo.com/signin/provider/Facebook/login?returnUrl=http://store.kobobooks.com/",
"facebook_sso_page": "https://authorize.kobo.com/signin/provider/Facebook/login?returnUrl=http://kobo.com/",
"featured_list": "https://storeapi.kobo.com/v1/products/featured/{FeaturedListId}",
"featured_lists": "https://storeapi.kobo.com/v1/products/featured",
"free_books_page": {
"EN": "https://www.kobo.com/{region}/{language}/p/free-ebooks",
"FR": "https://www.kobo.com/{region}/{language}/p/livres-gratuits",
"IT": "https://www.kobo.com/{region}/{language}/p/libri-gratuiti",
"NL": "https://www.kobo.com/{region}/{language}/"
"List/bekijk-het-overzicht-van-gratis-ebooks/QpkkVWnUw8sxmgjSlCbJRg",
"PT": "https://www.kobo.com/{region}/{language}/p/livros-gratis",
"NL": "https://www.kobo.com/{region}/{language}/List/bekijk-het-overzicht-van-gratis-ebooks/QpkkVWnUw8sxmgjSlCbJRg",
"PT": "https://www.kobo.com/{region}/{language}/p/livros-gratis"
},
"fte_feedback": "https://storeapi.kobo.com/v1/products/ftefeedback",
"funnel_metrics": "https://storeapi.kobo.com/v1/funnelmetrics",
"get_download_keys": "https://storeapi.kobo.com/v1/library/downloadkeys",
"get_download_link": "https://storeapi.kobo.com/v1/library/downloadlink",
"get_tests_request": "https://storeapi.kobo.com/v1/analytics/gettests",
"giftcard_epd_redeem_url": "https://www.kobo.com/{storefront}/{language}/redeem-ereader",
"giftcard_redeem_url": "https://www.kobo.com/{storefront}/{language}/redeem",
"help_page": "https://www.kobo.com/help",
"kobo_audiobooks_enabled": "False",
"gpb_flow_enabled": "False",
"help_page": "http://www.kobo.com/help",
"image_host": "//cdn.kobo.com/book-images/",
"image_url_quality_template": "https://cdn.kobo.com/book-images/{ImageId}/{Width}/{Height}/{Quality}/{IsGreyscale}/image.jpg",
"image_url_template": "https://cdn.kobo.com/book-images/{ImageId}/{Width}/{Height}/false/image.jpg",
"instapaper_enabled": "True",
"instapaper_env_url": "https://www.instapaper.com/api/kobo",
"instapaper_link_account_start": "https://authorize.kobo.com/{region}/{language}/linkinstapaper",
"kobo_audiobooks_credit_redemption": "False",
"kobo_audiobooks_enabled": "True",
"kobo_audiobooks_orange_deal_enabled": "False",
"kobo_audiobooks_subscriptions_enabled": "False",
"kobo_nativeborrow_enabled": "True",
"kobo_display_price": "True",
"kobo_dropbox_link_account_enabled": "False",
"kobo_google_tax": "False",
"kobo_googledrive_link_account_enabled": "False",
"kobo_nativeborrow_enabled": "False",
"kobo_onedrive_link_account_enabled": "False",
"kobo_onestorelibrary_enabled": "False",
"kobo_privacyCentre_url": "https://www.kobo.com/privacy",
"kobo_redeem_enabled": "True",
"kobo_shelfie_enabled": "False",
"kobo_subscriptions_enabled": "False",
"kobo_superpoints_enabled": "False",
"kobo_subscriptions_enabled": "True",
"kobo_superpoints_enabled": "True",
"kobo_wishlist_enabled": "True",
"library_book": "https://storeapi.kobo.com/v1/user/library/books/{LibraryItemId}",
"library_items": "https://storeapi.kobo.com/v1/user/library",
"library_metadata": "https://storeapi.kobo.com/v1/library/{Ids}/metadata",
"library_prices": "https://storeapi.kobo.com/v1/user/library/previews/prices",
"library_stack": "https://storeapi.kobo.com/v1/user/library/stacks/{LibraryItemId}",
"library_search": "https://storeapi.kobo.com/v1/library/search",
"library_sync": "https://storeapi.kobo.com/v1/library/sync",
"love_dashboard_page": "https://store.kobobooks.com/{culture}/kobosuperpoints",
"love_points_redemption_page":
"https://store.kobobooks.com/{culture}/KoboSuperPointsRedemption?productId={ProductId}",
"magazine_landing_page": "https://store.kobobooks.com/emagazines",
"love_dashboard_page": "https://www.kobo.com/{region}/{language}/kobosuperpoints",
"love_points_redemption_page": "https://www.kobo.com/{region}/{language}/KoboSuperPointsRedemption?productId={ProductId}",
"magazine_landing_page": "https://www.kobo.com/emagazines",
"more_sign_in_options": "https://authorize.kobo.com/signin?returnUrl=http://kobo.com/#allProviders",
"notebooks": "https://storeapi.kobo.com/api/internal/notebooks",
"notifications_registration_issue": "https://storeapi.kobo.com/v1/notifications/registration",
"oauth_host": "https://oauth.kobo.com",
"overdrive_account": "https://auth.overdrive.com/account",
"overdrive_library": "https://{libraryKey}.auth.overdrive.com/library",
"overdrive_library_finder_host": "https://libraryfinder.api.overdrive.com",
"overdrive_thunder_host": "https://thunder.api.overdrive.com",
"password_retrieval_page": "https://www.kobobooks.com/passwordretrieval.html",
"password_retrieval_page": "https://www.kobo.com/passwordretrieval.html",
"personalizedrecommendations": "https://storeapi.kobo.com/v2/users/personalizedrecommendations",
"pocket_link_account_start": "https://authorize.kobo.com/{region}/{language}/linkpocket",
"post_analytics_event": "https://storeapi.kobo.com/v1/analytics/event",
"ppx_purchasing_url": "https://purchasing.kobo.com",
"privacy_page": "https://www.kobo.com/privacypolicy?style=onestore",
"product_nextread": "https://storeapi.kobo.com/v1/products/{ProductIds}/nextread",
"product_prices": "https://storeapi.kobo.com/v1/products/{ProductIds}/prices",
"product_recommendations": "https://storeapi.kobo.com/v1/products/{ProductId}/recommendations",
"product_reviews": "https://storeapi.kobo.com/v1/products/{ProductIds}/reviews",
"products": "https://storeapi.kobo.com/v1/products",
"provider_external_sign_in_page":
"https://authorize.kobo.com/ExternalSignIn/{providerName}?returnUrl=http://store.kobobooks.com/",
"purchase_buy": "https://www.kobo.com/checkout/createpurchase/",
"purchase_buy_templated": "https://www.kobo.com/{culture}/checkout/createpurchase/{ProductId}",
"productsv2": "https://storeapi.kobo.com/v2/products",
"provider_external_sign_in_page": "https://authorize.kobo.com/ExternalSignIn/{providerName}?returnUrl=http://kobo.com/",
"quickbuy_checkout": "https://storeapi.kobo.com/v1/store/quickbuy/{PurchaseId}/checkout",
"quickbuy_create": "https://storeapi.kobo.com/v1/store/quickbuy/purchase",
"rakuten_token_exchange": "https://storeapi.kobo.com/v1/auth/rakuten_token_exchange",
"rating": "https://storeapi.kobo.com/v1/products/{ProductId}/rating/{Rating}",
"reading_services_host": "https://readingservices.kobo.com",
"reading_state": "https://storeapi.kobo.com/v1/library/{Ids}/state",
"redeem_interstitial_page": "https://store.kobobooks.com",
"registration_page": "https://authorize.kobo.com/signup?returnUrl=http://store.kobobooks.com/",
"redeem_interstitial_page": "https://www.kobo.com",
"registration_page": "https://authorize.kobo.com/signup?returnUrl=http://kobo.com/",
"related_items": "https://storeapi.kobo.com/v1/products/{Id}/related",
"remaining_book_series": "https://storeapi.kobo.com/v1/products/books/series/{SeriesId}",
"rename_tag": "https://storeapi.kobo.com/v1/library/tags/{TagId}",
"review": "https://storeapi.kobo.com/v1/products/reviews/{ReviewId}",
"review_sentiment": "https://storeapi.kobo.com/v1/products/reviews/{ReviewId}/sentiment/{Sentiment}",
"shelfie_recommendations": "https://storeapi.kobo.com/v1/user/recommendations/shelfie",
"sign_in_page": "https://authorize.kobo.com/signin?returnUrl=http://store.kobobooks.com/",
"sign_in_page": "https://authorize.kobo.com/signin?returnUrl=http://kobo.com/",
"social_authorization_host": "https://social.kobobooks.com:8443",
"social_host": "https://social.kobobooks.com",
"stacks_host_productId": "https://store.kobobooks.com/collections/byproductid/",
"store_home": "www.kobo.com/{region}/{language}",
"store_host": "store.kobobooks.com",
"store_newreleases": "https://store.kobobooks.com/{culture}/List/new-releases/961XUjtsU0qxkFItWOutGA",
"store_search": "https://store.kobobooks.com/{culture}/Search?Query={query}",
"store_top50": "https://store.kobobooks.com/{culture}/ebooks/Top",
"store_host": "www.kobo.com",
"store_newreleases": "https://www.kobo.com/{region}/{language}/List/new-releases/961XUjtsU0qxkFItWOutGA",
"store_search": "https://www.kobo.com/{region}/{language}/Search?Query={query}",
"store_top50": "https://www.kobo.com/{region}/{language}/ebooks/Top",
"subs_landing_page": "https://www.kobo.com/{region}/{language}/plus",
"subs_management_page": "https://www.kobo.com/{region}/{language}/account/subscriptions",
"subs_plans_page": "https://www.kobo.com/{region}/{language}/plus/plans",
"subs_purchase_buy_templated": "https://www.kobo.com/{region}/{language}/Checkoutoption/{ProductId}/{TierId}",
"tag_items": "https://storeapi.kobo.com/v1/library/tags/{TagId}/Items",
"tags": "https://storeapi.kobo.com/v1/library/tags",
"taste_profile": "https://storeapi.kobo.com/v1/products/tasteprofile",
"terms_of_sale_page": "https://authorize.kobo.com/{region}/{language}/terms/termsofsale",
"update_accessibility_to_preview": "https://storeapi.kobo.com/v1/library/{EntitlementIds}/preview",
"use_one_store": "False",
"use_one_store": "True",
"user_loyalty_benefits": "https://storeapi.kobo.com/v1/user/loyalty/benefits",
"user_platform": "https://storeapi.kobo.com/v1/user/platform",
"user_profile": "https://storeapi.kobo.com/v1/user/profile",
@@ -1260,6 +1319,6 @@ def NATIVE_KOBO_RESOURCES():
"user_recommendations": "https://storeapi.kobo.com/v1/user/recommendations",
"user_reviews": "https://storeapi.kobo.com/v1/user/reviews",
"user_wishlist": "https://storeapi.kobo.com/v1/user/wishlist",
"userguide_host": "https://kbdownload1-a.akamaihd.net",
"wishlist_page": "https://store.kobobooks.com/{region}/{language}/account/wishlist",
"userguide_host": "https://ereaderfiles.kobo.com",
"wishlist_page": "https://www.kobo.com/{region}/{language}/account/wishlist"
}
+13 -12
View File
@@ -22,7 +22,7 @@
This module also includes research notes into the auth protocol used by Kobo devices.
Log-in:
When first booting a Kobo device the user must sign into a Kobo (or affiliate) account.
When first booting a Kobo device the user must log in to a Kobo (or affiliate) account.
Upon successful sign-in, the user is redirected to
https://auth.kobobooks.com/CrossDomainSignIn?id=<some id>
which serves the following response:
@@ -41,7 +41,7 @@ issue for a few years now https://www.mobileread.com/forums/showpost.php?p=34768
will still grant access given the userkey.)
Official Kobo Store Api authorization:
* For most of the endpoints we care about (sync, metadata, tags, etc), the userKey is
* For most of the endpoints we care about (sync, metadata, tags, etc.), the userKey is
passed in the x-kobo-userkey header, and is sufficient to authorize the API call.
* Some endpoints (e.g: AnnotationService) instead make use of Bearer tokens pass through
an authorization header. To get a BearerToken, the device makes a POST request to the
@@ -65,12 +65,13 @@ from os import urandom
from functools import wraps
from flask import g, Blueprint, abort, request
from flask_login import login_user, current_user, login_required
from .cw_login import login_user, current_user
from flask_babel import gettext as _
from flask_limiter import RateLimitExceeded
from . import logger, config, calibre_db, db, helper, ub, lm, limiter
from .render_template import render_title_template
from .usermanagement import user_login_required
log = logger.create()
@@ -78,8 +79,10 @@ kobo_auth = Blueprint("kobo_auth", __name__, url_prefix="/kobo_auth")
@kobo_auth.route("/generate_auth_token/<int:user_id>")
@login_required
@user_login_required
def generate_auth_token(user_id):
if current_user.id != user_id and not current_user.role_admin():
abort(403)
warning = False
host_list = request.host.rsplit(':')
if len(host_list) == 1:
@@ -115,13 +118,15 @@ def generate_auth_token(user_id):
"generate_kobo_auth_url.html",
title=_("Kobo Setup"),
auth_token=auth_token.auth_token,
warning = warning
warning=warning
)
@kobo_auth.route("/deleteauthtoken/<int:user_id>", methods=["POST"])
@login_required
@user_login_required
def delete_auth_token(user_id):
if current_user.id != user_id and not current_user.role_admin():
abort(403)
# Invalidate any previously generated Kobo Auth token for this user
ub.session.query(ub.RemoteAuthToken).filter(ub.RemoteAuthToken.user_id == user_id)\
.filter(ub.RemoteAuthToken.token_type==1).delete()
@@ -152,10 +157,6 @@ def requires_kobo_auth(f):
def inner(*args, **kwargs):
auth_token = get_auth_token()
if auth_token is not None:
try:
limiter.check()
except RateLimitExceeded:
return abort(429)
user = (
ub.session.query(ub.User)
.join(ub.RemoteAuthToken)
@@ -164,7 +165,7 @@ def requires_kobo_auth(f):
)
if user is not None:
login_user(user)
[limiter.limiter.storage.clear(k.key) for k in limiter.current_limits]
[limiter.limiter.clear(limit.limit, *limit.request_args) for limit in limiter.current_limits]
return f(*args, **kwargs)
log.debug("Received Kobo request without a recognizable auth token.")
return abort(401)
+10 -8
View File
@@ -17,11 +17,12 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from flask_login import current_user
from .cw_login import current_user
from . import ub
import datetime
from datetime import datetime, timezone
from sqlalchemy.sql.expression import or_, and_, true
from sqlalchemy import exc
# from sqlalchemy import exc
# Add the current book id to kobo_synced_books table for current user, if entry is already present,
# do nothing (safety precaution)
@@ -50,15 +51,16 @@ def remove_synced_book(book_id, all=False, session=None):
ub.session_commit(_session=session)
# If state == none, it will toggle the archive state of the passed book_id.
# state = true archives it, state = false unarchives it
def change_archived_books(book_id, state=None, message=None):
archived_book = ub.session.query(ub.ArchivedBook).filter(and_(ub.ArchivedBook.user_id == int(current_user.id),
ub.ArchivedBook.book_id == book_id)).first()
if not archived_book:
if not archived_book: # and (state == True or state == None):
archived_book = ub.ArchivedBook(user_id=current_user.id, book_id=book_id)
archived_book.is_archived = state if state else not archived_book.is_archived
archived_book.last_modified = datetime.datetime.utcnow() # toDo. Check utc timestamp
archived_book.is_archived = state if state != None else not archived_book.is_archived
archived_book.last_modified = datetime.now(timezone.utc) # toDo. Check utc timestamp
ub.session.merge(archived_book)
ub.session_commit(message)
@@ -71,7 +73,7 @@ def update_on_sync_shelfs(user_id):
books_to_archive = (ub.session.query(ub.KoboSyncedBooks)
.join(ub.BookShelf, ub.KoboSyncedBooks.book_id == ub.BookShelf.book_id, isouter=True)
.join(ub.Shelf, ub.Shelf.user_id == user_id, isouter=True)
.filter(or_(ub.Shelf.kobo_sync == 0, ub.Shelf.kobo_sync == None))
.filter(or_(ub.Shelf.kobo_sync == 0, ub.Shelf.kobo_sync==None))
.filter(ub.KoboSyncedBooks.user_id == user_id).all())
for b in books_to_archive:
change_archived_books(b.book_id, True)
+8 -13
View File
@@ -29,7 +29,7 @@ from .constants import CONFIG_DIR as _CONFIG_DIR
ACCESS_FORMATTER_GEVENT = Formatter("%(message)s")
ACCESS_FORMATTER_TORNADO = Formatter("[%(asctime)s] %(message)s")
FORMATTER = Formatter("[%(asctime)s] %(levelname)5s {%(name)s:%(lineno)d} %(message)s")
FORMATTER = Formatter("[%(asctime)s] %(levelname)5s {%(filename)s:%(lineno)d} %(message)s")
DEFAULT_LOG_LEVEL = logging.INFO
DEFAULT_LOG_FILE = os.path.join(_CONFIG_DIR, "calibre-web.log")
DEFAULT_ACCESS_LOG = os.path.join(_CONFIG_DIR, "access.log")
@@ -42,17 +42,12 @@ logging.addLevelName(logging.CRITICAL, "CRIT")
class _Logger(logging.Logger):
def error_or_exception(self, message, stacklevel=2, *args, **kwargs):
if sys.version_info > (3, 7):
if is_debug_enabled():
self.exception(message, stacklevel=stacklevel, *args, **kwargs)
else:
self.error(message, stacklevel=stacklevel, *args, **kwargs)
def error_or_exception(self, message, stacklevel=1, *args, **kwargs):
is_debug = self.getEffectiveLevel() <= logging.DEBUG
if not is_debug:
self.exception(message, stacklevel=stacklevel, *args, **kwargs)
else:
if is_debug_enabled():
self.exception(message, stack_info=True, *args, **kwargs)
else:
self.error(message, *args, **kwargs)
self.error(message, stacklevel=stacklevel, *args, **kwargs)
def debug_no_auth(self, message, *args, **kwargs):
message = message.strip("\r\n")
@@ -150,7 +145,7 @@ def setup(log_file, log_level=None):
else:
try:
file_handler = RotatingFileHandler(log_file, maxBytes=100000, backupCount=2, encoding='utf-8')
except IOError:
except (IOError, PermissionError):
if log_file == DEFAULT_LOG_FILE:
raise
file_handler = RotatingFileHandler(DEFAULT_LOG_FILE, maxBytes=100000, backupCount=2, encoding='utf-8')
@@ -177,7 +172,7 @@ def create_access_log(log_file, log_name, formatter):
access_log.setLevel(logging.INFO)
try:
file_handler = RotatingFileHandler(log_file, maxBytes=50000, backupCount=2, encoding='utf-8')
except IOError:
except (IOError, PermissionError):
if log_file == DEFAULT_ACCESS_LOG:
raise
file_handler = RotatingFileHandler(DEFAULT_ACCESS_LOG, maxBytes=50000, backupCount=2, encoding='utf-8')
+9 -4
View File
@@ -20,17 +20,18 @@ import sys
from . import create_app, limiter
from .jinjia import jinjia
from .remotelogin import remotelogin
from flask import request
def request_username():
return request.authorization.username
return request.authorization.username if request.authorization else ""
def main():
app = create_app()
from .web import web
from .basic import basic
from .opds import opds
from .admin import admi
from .gdrive import gdrive
@@ -41,6 +42,7 @@ def main():
from .shelf import shelf
from .tasks_status import tasks
from .error_handler import init_errorhandler
from .remotelogin import remotelogin
try:
from .kobo import kobo, get_kobo_activated
from .kobo_auth import kobo_auth
@@ -48,12 +50,14 @@ def main():
kobo_available = get_kobo_activated()
except (ImportError, AttributeError): # Catch also error for not installed flask-WTF (missing csrf decorator)
kobo_available = False
kobo = kobo_auth = get_remote_address = None
try:
from .oauth_bb import oauth
oauth_available = True
except ImportError:
oauth_available = False
oauth = None
from . import web_server
init_errorhandler()
@@ -61,8 +65,9 @@ def main():
app.register_blueprint(search)
app.register_blueprint(tasks)
app.register_blueprint(web)
app.register_blueprint(basic)
limiter.limit("3/minute", key_func=request_username)(opds)
app.register_blueprint(opds)
limiter.limit("3/minute",key_func=request_username)(opds)
app.register_blueprint(jinjia)
app.register_blueprint(about)
app.register_blueprint(shelf)
@@ -72,9 +77,9 @@ def main():
app.register_blueprint(gdrive)
app.register_blueprint(editbook)
if kobo_available:
limiter.limit("3/minute", key_func=get_remote_address)(kobo)
app.register_blueprint(kobo)
app.register_blueprint(kobo_auth)
limiter.limit("3/minute", key_func=get_remote_address)(kobo)
if oauth_available:
app.register_blueprint(oauth)
success = web_server.start()
+20 -21
View File
@@ -25,7 +25,7 @@ try:
import cchardet #optional for better speed
except ImportError:
pass
from cps import logger
from cps.services.Metadata import MetaRecord, MetaSourceInfo, Metadata
import cps.logger as logger
@@ -33,21 +33,21 @@ import cps.logger as logger
from operator import itemgetter
log = logger.create()
log = logger.create()
class Amazon(Metadata):
__name__ = "Amazon"
__id__ = "amazon"
headers = {'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36',
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'sec-gpc': '1',
'sec-fetch-site': 'none',
'sec-fetch-mode': 'navigate',
'sec-fetch-user': '?1',
'sec-fetch-dest': 'document',
'accept-encoding': 'gzip, deflate, br',
'user-agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:130.0) Gecko/20100101 Firefox/130.0',
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/png,image/svg+xml,*/*;q=0.8',
'Sec-Fetch-Site': 'same-origin',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-User': '?1',
'Sec-Fetch-Dest': 'document',
'Upgrade-Insecure-Requests': '1',
'Alt-Used' : 'www.amazon.com',
'Priority' : 'u=0, i',
'accept-encoding': 'gzip, deflate, br, zstd',
'accept-language': 'en-US,en;q=0.9'}
session = requests.Session()
session.headers=headers
@@ -55,7 +55,6 @@ class Amazon(Metadata):
def search(
self, query: str, generic_cover: str = "", locale: str = "en"
) -> Optional[List[MetaRecord]]:
#timer=time()
def inner(link, index) -> [dict, int]:
with self.session as session:
try:
@@ -63,11 +62,11 @@ class Amazon(Metadata):
r.raise_for_status()
except Exception as ex:
log.warning(ex)
return None
return []
long_soup = BS(r.text, "lxml") #~4sec :/
soup2 = long_soup.find("div", attrs={"cel_widget_id": "dpx-books-ppd_csm_instrumentation_wrapper"})
soup2 = long_soup.find("div", attrs={"cel_widget_id": "dpx-ppd_csm_instrumentation_wrapper"})
if soup2 is None:
return None
return []
try:
match = MetaRecord(
title = "",
@@ -90,7 +89,7 @@ class Amazon(Metadata):
soup2.find("div", attrs={"data-feature-name": "bookDescription"}).stripped_strings)\
.replace("\xa0"," ")[:-9].strip().strip("\n")
except (AttributeError, TypeError):
return None # if there is no description it is not a book and therefore should be ignored
return [] # if there is no description it is not a book and therefore should be ignored
try:
match.title = soup2.find("span", attrs={"id": "productTitle"}).text
except (AttributeError, TypeError):
@@ -98,7 +97,7 @@ class Amazon(Metadata):
try:
match.authors = [next(
filter(lambda i: i != " " and i != "\n" and not i.startswith("{"),
x.findAll(text=True))).strip()
x.findAll(string=True))).strip()
for x in soup2.findAll("span", attrs={"class": "author"})]
except (AttributeError, TypeError, StopIteration):
match.authors = ""
@@ -109,13 +108,13 @@ class Amazon(Metadata):
except (AttributeError, ValueError):
match.rating = 0
try:
match.cover = soup2.find("img", attrs={"class": "a-dynamic-image frontImage"})["src"]
match.cover = soup2.find("img", attrs={"class": "a-dynamic-image"})["src"]
except (AttributeError, TypeError):
match.cover = ""
return match, index
except Exception as e:
log.error_or_exception(e)
return None
return []
val = list()
if self.active:
@@ -135,7 +134,7 @@ class Amazon(Metadata):
links_list = [next(filter(lambda i: "digital-text" in i["href"], x.findAll("a")))["href"] for x in
soup.findAll("div", attrs={"data-component-type": "s-search-result"})]
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
fut = {executor.submit(inner, link, index) for index, link in enumerate(links_list[:5])}
val = list(map(lambda x : x.result() ,concurrent.futures.as_completed(fut)))
fut = {executor.submit(inner, link, index) for index, link in enumerate(links_list[:3])}
val = list(map(lambda x : x.result(), concurrent.futures.as_completed(fut)))
result = list(filter(lambda x: x, val))
return [x[0] for x in sorted(result, key=itemgetter(1))] #sort by amazons listing order for best relevance
+1 -1
View File
@@ -57,7 +57,7 @@ class ComicVine(Metadata):
result.raise_for_status()
except Exception as e:
log.warning(e)
return None
return []
for result in result.json()["results"]:
match = self._parse_search_result(
result=result, generic_cover=generic_cover, locale=locale
+6 -4
View File
@@ -155,7 +155,7 @@ class Douban(Metadata):
r.raise_for_status()
except Exception as e:
log.warning(e)
return None
return []
match = MetaRecord(
id=id,
@@ -169,7 +169,8 @@ class Douban(Metadata):
),
)
html = etree.HTML(r.content.decode("utf8"))
decode_content = r.content.decode("utf8")
html = etree.HTML(decode_content)
match.title = html.xpath(self.TITTLE_XPATH)[0].text
match.cover = html.xpath(
@@ -184,7 +185,7 @@ class Douban(Metadata):
if len(tag_elements):
match.tags = [tag_element.text for tag_element in tag_elements]
else:
match.tags = self._get_tags(html.text)
match.tags = self._get_tags(decode_content)
description_element = html.xpath(self.DESCRIPTION_XPATH)
if len(description_element):
@@ -216,7 +217,8 @@ class Douban(Metadata):
return match
def _clean_date(self, date: str) -> str:
@staticmethod
def _clean_date(date: str) -> str:
"""
Clean up the date string to be in the format YYYY-MM-DD
+5 -4
View File
@@ -23,7 +23,7 @@ from datetime import datetime
import requests
from cps import logger
from cps import logger, config
from cps.isoLanguages import get_lang3, get_language_name
from cps.services.Metadata import MetaRecord, MetaSourceInfo, Metadata
@@ -31,13 +31,14 @@ log = logger.create()
class Google(Metadata):
__name__ = "Google"
__name__ = "Google Books"
__id__ = "google"
DESCRIPTION = "Google Books"
META_URL = "https://books.google.com/"
BOOK_URL = "https://books.google.com/books?id="
SEARCH_URL = "https://www.googleapis.com/books/v1/volumes?q="
ISBN_TYPE = "ISBN_13"
API_KEY = "&key=" + config.config_googlebooks_api_key
def search(
self, query: str, generic_cover: str = "", locale: str = "en"
@@ -50,11 +51,11 @@ class Google(Metadata):
tokens = [quote(t.encode("utf-8")) for t in title_tokens]
query = "+".join(tokens)
try:
results = requests.get(Google.SEARCH_URL + query)
results = requests.get(Google.SEARCH_URL + query + Google.API_KEY)
results.raise_for_status()
except Exception as e:
log.warning(e)
return None
return []
for result in results.json().get("items", []):
val.append(
self._parse_search_result(
+16 -7
View File
@@ -97,12 +97,14 @@ class LubimyCzytac(Metadata):
LANGUAGES = f"{CONTAINER}//dt[contains(text(),'Język:')]{SIBLINGS}/text()"
DESCRIPTION = f"{CONTAINER}//div[@class='collapse-content']"
SERIES = f"{CONTAINER}//span/a[contains(@href,'/cykl/')]/text()"
TRANSLATOR = f"{CONTAINER}//dt[contains(text(),'Tłumacz:')]{SIBLINGS}/a/text()"
DETAILS = "//div[@id='book-details']"
PUBLISH_DATE = "//dt[contains(@title,'Data pierwszego wydania"
FIRST_PUBLISH_DATE = f"{DETAILS}{PUBLISH_DATE} oryginalnego')]{SIBLINGS}[1]/text()"
FIRST_PUBLISH_DATE_PL = f"{DETAILS}{PUBLISH_DATE} polskiego')]{SIBLINGS}[1]/text()"
TAGS = "//nav[@aria-label='breadcrumb']//a[contains(@href,'/ksiazki/k/')]/text()"
TAGS = "//a[contains(@href,'/ksiazki/t/')]/text()" # "//nav[@aria-label='breadcrumbs']//a[contains(@href,'/ksiazki/k/')]/span/text()"
RATING = "//meta[@property='books:rating:value']/@content"
COVER = "//meta[@property='og:image']/@content"
@@ -135,7 +137,7 @@ class LubimyCzytac(Metadata):
def _prepare_query(self, title: str) -> str:
query = ""
characters_to_remove = "\?()\/"
characters_to_remove = r"\?()\/"
pattern = "[" + characters_to_remove + "]"
title = re.sub(pattern, "", title)
title = title.replace("_", " ")
@@ -158,6 +160,7 @@ class LubimyCzytac(Metadata):
class LubimyCzytacParser:
PAGES_TEMPLATE = "<p id='strony'>Książka ma {0} stron(y).</p>"
TRANSLATOR_TEMPLATE = "<p id='translator'>Tłumacz: {0}</p>"
PUBLISH_DATE_TEMPLATE = "<p id='pierwsze_wydanie'>Data pierwszego wydania: {0}</p>"
PUBLISH_DATE_PL_TEMPLATE = (
"<p id='pierwsze_wydanie'>Data pierwszego wydania w Polsce: {0}</p>"
@@ -282,11 +285,13 @@ class LubimyCzytacParser:
def _parse_tags(self) -> List[str]:
tags = self._parse_xpath_node(xpath=LubimyCzytac.TAGS, take_first=False)
return [
strip_accents(w.replace(", itd.", " itd."))
for w in tags
if isinstance(w, str)
]
if tags:
return [
strip_accents(w.replace(", itd.", " itd."))
for w in tags
if isinstance(w, str)
]
return None
def _parse_from_summary(self, attribute_name: str) -> Optional[str]:
value = None
@@ -346,5 +351,9 @@ class LubimyCzytacParser:
description += LubimyCzytacParser.PUBLISH_DATE_PL_TEMPLATE.format(
first_publish_date_pl.strftime("%d.%m.%Y")
)
translator = self._parse_xpath_node(xpath=LubimyCzytac.TRANSLATOR)
if translator:
description += LubimyCzytacParser.TRANSLATOR_TEMPLATE.format(translator)
return description
+1 -1
View File
@@ -32,7 +32,7 @@ class OAuthBackend(SQLAlchemyBackend):
Stores and retrieves OAuth tokens using a relational database through
the `SQLAlchemy`_ ORM.
.. _SQLAlchemy: https://www.sqlalchemy.org/
_SQLAlchemy: https://www.sqlalchemy.org/
"""
def __init__(self, model, session, provider_id,
user=None, user_id=None, user_required=None, anon_user=None,
+15 -4
View File
@@ -30,8 +30,9 @@ from flask_dance.consumer import oauth_authorized, oauth_error
from flask_dance.contrib.github import make_github_blueprint, github
from flask_dance.contrib.google import make_google_blueprint, google
from oauthlib.oauth2 import TokenExpiredError, InvalidGrantError
from flask_login import login_user, current_user, login_required
from .cw_login import login_user, current_user
from sqlalchemy.orm.exc import NoResultFound
from .usermanagement import user_login_required
from . import constants, logger, config, app, ub
@@ -133,9 +134,17 @@ def bind_oauth_or_register(provider_id, provider_user_id, redirect_url, provider
oauth_entry = query.first()
# already bind with user, just login
if oauth_entry.user:
# If a user is already logged in and it's a different account, reject the link
# to prevent account takeover via shared OAuth identities
if current_user and current_user.is_authenticated and oauth_entry.user_id != current_user.id:
flash(_("This %(oauth)s account is already linked to a different user",
oauth=provider_name), category="error")
log.warning("User %s tried to link OAuth account already bound to user %s",
current_user.id, oauth_entry.user_id)
return redirect(url_for('web.profile'))
login_user(oauth_entry.user)
log.debug("You are now logged in as: '%s'", oauth_entry.user.name)
flash(_("Success! You are now logged in as: %(nickname)s", nickname= oauth_entry.user.name),
flash(_("Success! You are now logged in as: %(nickname)s", nickname=oauth_entry.user.name),
category="success")
return redirect(url_for('web.index'))
else:
@@ -205,6 +214,7 @@ def unlink_oauth(provider):
flash(_("Not Linked to %(oauth)s", oauth=provider), category="error")
return redirect(url_for('web.profile'))
def generate_oauth_blueprints():
if not ub.session.query(ub.OAuthProvider).count():
for provider in ("github", "google"):
@@ -291,6 +301,7 @@ if ub.oauth_support:
return oauth_update_token(str(oauthblueprints[1]['id']), token, google_user_id)
# notify on OAuth provider error
@oauth_error.connect_via(oauthblueprints[0]['blueprint'])
def github_error(blueprint, error, error_description=None, error_uri=None):
@@ -338,7 +349,7 @@ def github_login():
@oauth.route('/unlink/github', methods=["GET"])
@login_required
@user_login_required
def github_login_unlink():
return unlink_oauth(oauthblueprints[0]['id'])
@@ -362,6 +373,6 @@ def google_login():
@oauth.route('/unlink/google', methods=["GET"])
@login_required
@user_login_required
def google_login_unlink():
return unlink_oauth(oauthblueprints[1]['id'])
+109 -42
View File
@@ -23,15 +23,16 @@
import datetime
from urllib.parse import unquote_plus
from flask import Blueprint, request, render_template, make_response, abort
from flask_login import current_user
from flask import Blueprint, request, render_template, make_response, abort, g, jsonify
from flask_babel import get_locale
from flask_babel import gettext as _
from sqlalchemy.sql.expression import func, text, or_, and_, true
from sqlalchemy.exc import InvalidRequestError, OperationalError
from . import logger, config, db, calibre_db, ub, isoLanguages
from .usermanagement import requires_basic_auth_if_no_ano
from . import logger, config, db, calibre_db, ub, isoLanguages, constants
from .usermanagement import requires_basic_auth_if_no_ano, auth
from .helper import get_download_link, get_book_cover
from .pagination import Pagination
from .web import render_read_books
@@ -55,7 +56,7 @@ def feed_osd():
return render_xml_template('osd.xml', lang='en-EN')
@opds.route("/opds/search", defaults={'query': ""})
# @opds.route("/opds/search", defaults={'query': ""})
@opds.route("/opds/search/<path:query>")
@requires_basic_auth_if_no_ano
def feed_cc_search(query):
@@ -86,43 +87,54 @@ def feed_letter_books(book_id):
letter,
[db.Books.sort],
True, config.config_read_column)
return render_xml_template('feed.xml', entries=entries, pagination=pagination)
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
return render_xml_template('feed.xml', entries=entries, pagination=pagination, cc=cc)
@opds.route("/opds/new")
@requires_basic_auth_if_no_ano
def feed_new():
if not auth.current_user().check_visibility(constants.SIDEBAR_RECENT):
abort(404)
off = request.args.get("offset") or 0
entries, __, pagination = calibre_db.fill_indexpage((int(off) / (int(config.config_books_per_page)) + 1), 0,
db.Books, True, [db.Books.timestamp.desc()],
True, config.config_read_column)
return render_xml_template('feed.xml', entries=entries, pagination=pagination)
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
return render_xml_template('feed.xml', entries=entries, pagination=pagination, cc=cc)
@opds.route("/opds/discover")
@requires_basic_auth_if_no_ano
def feed_discover():
if not auth.current_user().check_visibility(constants.SIDEBAR_RANDOM):
abort(404)
query = calibre_db.generate_linked_query(config.config_read_column, db.Books)
entries = query.filter(calibre_db.common_filters()).order_by(func.random()).limit(config.config_books_per_page)
pagination = Pagination(1, config.config_books_per_page, int(config.config_books_per_page))
return render_xml_template('feed.xml', entries=entries, pagination=pagination)
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
return render_xml_template('feed.xml', entries=entries, pagination=pagination, cc=cc)
@opds.route("/opds/rated")
@requires_basic_auth_if_no_ano
def feed_best_rated():
if not auth.current_user().check_visibility(constants.SIDEBAR_BEST_RATED):
abort(404)
off = request.args.get("offset") or 0
entries, __, pagination = calibre_db.fill_indexpage((int(off) / (int(config.config_books_per_page)) + 1), 0,
db.Books, db.Books.ratings.any(db.Ratings.rating > 9),
[db.Books.timestamp.desc()],
True, config.config_read_column)
return render_xml_template('feed.xml', entries=entries, pagination=pagination)
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
return render_xml_template('feed.xml', entries=entries, pagination=pagination, cc=cc)
@opds.route("/opds/hot")
@requires_basic_auth_if_no_ano
def feed_hot():
if not auth.current_user().check_visibility(constants.SIDEBAR_HOT):
abort(404)
off = request.args.get("offset") or 0
all_books = ub.session.query(ub.Downloads, func.count(ub.Downloads.book_id)).order_by(
func.count(ub.Downloads.book_id).desc()).group_by(ub.Downloads.book_id)
@@ -139,18 +151,23 @@ def feed_hot():
num_books = entries.__len__()
pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1),
config.config_books_per_page, num_books)
return render_xml_template('feed.xml', entries=entries, pagination=pagination)
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
return render_xml_template('feed.xml', entries=entries, pagination=pagination, cc=cc)
@opds.route("/opds/author")
@requires_basic_auth_if_no_ano
def feed_authorindex():
if not auth.current_user().check_visibility(constants.SIDEBAR_AUTHOR):
abort(404)
return render_element_index(db.Authors.sort, db.books_authors_link, 'opds.feed_letter_author')
@opds.route("/opds/author/letter/<book_id>")
@requires_basic_auth_if_no_ano
def feed_letter_author(book_id):
if not auth.current_user().check_visibility(constants.SIDEBAR_AUTHOR):
abort(404)
off = request.args.get("offset") or 0
letter = true() if book_id == "00" else func.upper(db.Authors.sort).startswith(book_id)
entries = calibre_db.session.query(db.Authors).join(db.books_authors_link).join(db.Books)\
@@ -160,7 +177,8 @@ def feed_letter_author(book_id):
pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page,
entries.count())
entries = entries.limit(config.config_books_per_page).offset(off).all()
return render_xml_template('feed.xml', listelements=entries, folder='opds.feed_author', pagination=pagination)
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
return render_xml_template('feed.xml', listelements=entries, folder='opds.feed_author', pagination=pagination, cc=cc)
@opds.route("/opds/author/<int:book_id>")
@@ -172,6 +190,8 @@ def feed_author(book_id):
@opds.route("/opds/publisher")
@requires_basic_auth_if_no_ano
def feed_publisherindex():
if not auth.current_user().check_visibility(constants.SIDEBAR_PUBLISHER):
abort(404)
off = request.args.get("offset") or 0
entries = calibre_db.session.query(db.Publishers)\
.join(db.books_publishers_link)\
@@ -181,7 +201,8 @@ def feed_publisherindex():
.limit(config.config_books_per_page).offset(off)
pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page,
len(calibre_db.session.query(db.Publishers).all()))
return render_xml_template('feed.xml', listelements=entries, folder='opds.feed_publisher', pagination=pagination)
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
return render_xml_template('feed.xml', listelements=entries, folder='opds.feed_publisher', pagination=pagination, cc=cc)
@opds.route("/opds/publisher/<int:book_id>")
@@ -193,12 +214,16 @@ def feed_publisher(book_id):
@opds.route("/opds/category")
@requires_basic_auth_if_no_ano
def feed_categoryindex():
if not auth.current_user().check_visibility(constants.SIDEBAR_CATEGORY):
abort(404)
return render_element_index(db.Tags.name, db.books_tags_link, 'opds.feed_letter_category')
@opds.route("/opds/category/letter/<book_id>")
@requires_basic_auth_if_no_ano
def feed_letter_category(book_id):
if not auth.current_user().check_visibility(constants.SIDEBAR_CATEGORY):
abort(404)
off = request.args.get("offset") or 0
letter = true() if book_id == "00" else func.upper(db.Tags.name).startswith(book_id)
entries = calibre_db.session.query(db.Tags)\
@@ -210,7 +235,8 @@ def feed_letter_category(book_id):
pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page,
entries.count())
entries = entries.offset(off).limit(config.config_books_per_page).all()
return render_xml_template('feed.xml', listelements=entries, folder='opds.feed_category', pagination=pagination)
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
return render_xml_template('feed.xml', listelements=entries, folder='opds.feed_category', pagination=pagination, cc=cc)
@opds.route("/opds/category/<int:book_id>")
@@ -222,12 +248,16 @@ def feed_category(book_id):
@opds.route("/opds/series")
@requires_basic_auth_if_no_ano
def feed_seriesindex():
if not auth.current_user().check_visibility(constants.SIDEBAR_SERIES):
abort(404)
return render_element_index(db.Series.sort, db.books_series_link, 'opds.feed_letter_series')
@opds.route("/opds/series/letter/<book_id>")
@requires_basic_auth_if_no_ano
def feed_letter_series(book_id):
if not auth.current_user().check_visibility(constants.SIDEBAR_SERIES):
abort(404)
off = request.args.get("offset") or 0
letter = true() if book_id == "00" else func.upper(db.Series.sort).startswith(book_id)
entries = calibre_db.session.query(db.Series)\
@@ -239,7 +269,8 @@ def feed_letter_series(book_id):
pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page,
entries.count())
entries = entries.offset(off).limit(config.config_books_per_page).all()
return render_xml_template('feed.xml', listelements=entries, folder='opds.feed_series', pagination=pagination)
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
return render_xml_template('feed.xml', listelements=entries, folder='opds.feed_series', pagination=pagination, cc=cc)
@opds.route("/opds/series/<int:book_id>")
@@ -251,12 +282,15 @@ def feed_series(book_id):
db.Books.series.any(db.Series.id == book_id),
[db.Books.series_index],
True, config.config_read_column)
return render_xml_template('feed.xml', entries=entries, pagination=pagination)
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
return render_xml_template('feed.xml', entries=entries, pagination=pagination, cc=cc)
@opds.route("/opds/ratings")
@requires_basic_auth_if_no_ano
def feed_ratingindex():
if not auth.current_user().check_visibility(constants.SIDEBAR_RATING):
abort(404)
off = request.args.get("offset") or 0
entries = calibre_db.session.query(db.Ratings, func.count('books_ratings_link.book').label('count'),
(db.Ratings.rating / 2).label('name')) \
@@ -271,7 +305,8 @@ def feed_ratingindex():
element = list()
for entry in entries:
element.append(FeedObject(entry[0].id, _("{} Stars").format(entry.name)))
return render_xml_template('feed.xml', listelements=element, folder='opds.feed_ratings', pagination=pagination)
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
return render_xml_template('feed.xml', listelements=element, folder='opds.feed_ratings', pagination=pagination, cc=cc)
@opds.route("/opds/ratings/<book_id>")
@@ -283,6 +318,8 @@ def feed_ratings(book_id):
@opds.route("/opds/formats")
@requires_basic_auth_if_no_ano
def feed_formatindex():
if not auth.current_user().check_visibility(constants.SIDEBAR_FORMAT):
abort(404)
off = request.args.get("offset") or 0
entries = calibre_db.session.query(db.Data).join(db.Books)\
.filter(calibre_db.common_filters()) \
@@ -290,11 +327,11 @@ def feed_formatindex():
.order_by(db.Data.format).all()
pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page,
len(entries))
element = list()
for entry in entries:
element.append(FeedObject(entry.format, entry.format))
return render_xml_template('feed.xml', listelements=element, folder='opds.feed_format', pagination=pagination)
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
return render_xml_template('feed.xml', listelements=element, folder='opds.feed_format', pagination=pagination, cc=cc)
@opds.route("/opds/formats/<book_id>")
@@ -306,23 +343,27 @@ def feed_format(book_id):
db.Books.data.any(db.Data.format == book_id.upper()),
[db.Books.timestamp.desc()],
True, config.config_read_column)
return render_xml_template('feed.xml', entries=entries, pagination=pagination)
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
return render_xml_template('feed.xml', entries=entries, pagination=pagination, cc=cc)
@opds.route("/opds/language")
@opds.route("/opds/language/")
@requires_basic_auth_if_no_ano
def feed_languagesindex():
if not auth.current_user().check_visibility(constants.SIDEBAR_LANGUAGE):
abort(404)
off = request.args.get("offset") or 0
if current_user.filter_language() == "all":
if auth.current_user().filter_language() == "all":
languages = calibre_db.speaking_language()
else:
languages = calibre_db.session.query(db.Languages).filter(
db.Languages.lang_code == current_user.filter_language()).all()
db.Languages.lang_code == auth.current_user().filter_language()).all()
languages[0].name = isoLanguages.get_language_name(get_locale(), languages[0].lang_code)
pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page,
len(languages))
return render_xml_template('feed.xml', listelements=languages, folder='opds.feed_languages', pagination=pagination)
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
return render_xml_template('feed.xml', listelements=languages, folder='opds.feed_languages', pagination=pagination, cc=cc)
@opds.route("/opds/language/<int:book_id>")
@@ -334,34 +375,41 @@ def feed_languages(book_id):
db.Books.languages.any(db.Languages.id == book_id),
[db.Books.timestamp.desc()],
True, config.config_read_column)
return render_xml_template('feed.xml', entries=entries, pagination=pagination)
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
return render_xml_template('feed.xml', entries=entries, pagination=pagination, cc=cc)
@opds.route("/opds/shelfindex")
@requires_basic_auth_if_no_ano
def feed_shelfindex():
if not (auth.current_user().is_authenticated or g.allow_anonymous):
abort(404)
off = request.args.get("offset") or 0
shelf = ub.session.query(ub.Shelf).filter(
or_(ub.Shelf.is_public == 1, ub.Shelf.user_id == current_user.id)).order_by(ub.Shelf.name).all()
or_(ub.Shelf.is_public == 1, ub.Shelf.user_id == auth.current_user().id)).order_by(ub.Shelf.name).all()
number = len(shelf)
pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page,
number)
return render_xml_template('feed.xml', listelements=shelf, folder='opds.feed_shelf', pagination=pagination)
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
return render_xml_template('feed.xml', listelements=shelf, folder='opds.feed_shelf', pagination=pagination, cc=cc)
@opds.route("/opds/shelf/<int:book_id>")
@requires_basic_auth_if_no_ano
def feed_shelf(book_id):
if not (auth.current_user().is_authenticated or g.allow_anonymous):
abort(404)
off = request.args.get("offset") or 0
if current_user.is_anonymous:
if auth.current_user().is_anonymous:
shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.is_public == 1,
ub.Shelf.id == book_id).first()
else:
shelf = ub.session.query(ub.Shelf).filter(or_(and_(ub.Shelf.user_id == int(current_user.id),
shelf = ub.session.query(ub.Shelf).filter(or_(and_(ub.Shelf.user_id == int(auth.current_user().id),
ub.Shelf.id == book_id),
and_(ub.Shelf.is_public == 1,
ub.Shelf.id == book_id))).first()
result = list()
pagination = list()
# user is allowed to access shelf
if shelf:
result, __, pagination = calibre_db.fill_indexpage((int(off) / (int(config.config_books_per_page)) + 1),
@@ -383,18 +431,16 @@ def feed_shelf(book_id):
except (OperationalError, InvalidRequestError) as e:
ub.session.rollback()
log.error_or_exception("Settings Database error: {}".format(e))
return render_xml_template('feed.xml', entries=result, pagination=pagination)
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
return render_xml_template('feed.xml', entries=result, pagination=pagination, cc=cc)
@opds.route("/opds/download/<book_id>/<book_format>/")
@requires_basic_auth_if_no_ano
def opds_download_link(book_id, book_format):
if not current_user.role_download():
return abort(403)
if "Kobo" in request.headers.get('User-Agent'):
client = "kobo"
else:
client = ""
if not auth.current_user().role_download():
return abort(401)
client = "kobo" if "Kobo" in request.headers.get('User-Agent') else ""
return get_download_link(book_id, book_format.lower(), client)
@@ -412,6 +458,17 @@ def get_metadata_calibre_companion(uuid, library):
return ""
@opds.route("/opds/stats")
@requires_basic_auth_if_no_ano
def get_database_stats():
stat = dict()
stat['books'] = calibre_db.session.query(db.Books).count()
stat['authors'] = calibre_db.session.query(db.Authors).count()
stat['categories'] = calibre_db.session.query(db.Tags).count()
stat['series'] = calibre_db.session.query(db.Series).count()
return make_response(jsonify(stat))
@opds.route("/opds/thumb_240_240/<book_id>")
@opds.route("/opds/cover_240_240/<book_id>")
@opds.route("/opds/cover_90_90/<book_id>")
@@ -424,17 +481,23 @@ def feed_get_cover(book_id):
@opds.route("/opds/readbooks")
@requires_basic_auth_if_no_ano
def feed_read_books():
if not (auth.current_user().check_visibility(constants.SIDEBAR_READ_AND_UNREAD) and not auth.current_user().is_anonymous):
return abort(403)
off = request.args.get("offset") or 0
result, pagination = render_read_books(int(off) / (int(config.config_books_per_page)) + 1, True, True)
return render_xml_template('feed.xml', entries=result, pagination=pagination)
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
return render_xml_template('feed.xml', entries=result, pagination=pagination, cc=cc)
@opds.route("/opds/unreadbooks")
@requires_basic_auth_if_no_ano
def feed_unread_books():
if not (auth.current_user().check_visibility(constants.SIDEBAR_READ_AND_UNREAD) and not auth.current_user().is_anonymous):
return abort(403)
off = request.args.get("offset") or 0
result, pagination = render_read_books(int(off) / (int(config.config_books_per_page)) + 1, False, True)
return render_xml_template('feed.xml', entries=result, pagination=pagination)
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
return render_xml_template('feed.xml', entries=result, pagination=pagination, cc=cc)
class FeedObject:
@@ -456,7 +519,8 @@ def feed_search(term):
entries, __, ___ = calibre_db.get_search_results(term, config=config)
entries_count = len(entries) if len(entries) > 0 else 1
pagination = Pagination(1, entries_count, entries_count)
return render_xml_template('feed.xml', searchterm=term, entries=entries, pagination=pagination)
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
return render_xml_template('feed.xml', searchterm=term, entries=entries, pagination=pagination, cc=cc)
else:
return render_xml_template('feed.xml', searchterm="")
@@ -465,7 +529,7 @@ def feed_search(term):
def render_xml_template(*args, **kwargs):
# ToDo: return time in current timezone similar to %z
currtime = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S+00:00")
xml = render_template(current_time=currtime, instance=config.config_calibre_web_title, *args, **kwargs)
xml = render_template(current_time=currtime, instance=config.config_calibre_web_title, constants=constants.sidebar_settings, *args, **kwargs)
response = make_response(xml)
response.headers["Content-Type"] = "application/atom+xml; charset=utf-8"
return response
@@ -478,7 +542,8 @@ def render_xml_dataset(data_table, book_id):
getattr(db.Books, data_table.__tablename__).any(data_table.id == book_id),
[db.Books.timestamp.desc()],
True, config.config_read_column)
return render_xml_template('feed.xml', entries=entries, pagination=pagination)
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
return render_xml_template('feed.xml', entries=entries, pagination=pagination, cc=cc)
def render_element_index(database_column, linked_table, folder):
@@ -490,7 +555,7 @@ def render_element_index(database_column, linked_table, folder):
entries = entries.join(linked_table).join(db.Books)
entries = entries.filter(calibre_db.common_filters()).group_by(func.upper(func.substr(database_column, 1, 1))).all()
elements = []
if off == 0:
if off == 0 and entries:
elements.append({'id': "00", 'name': _("All")})
shift = 1
for entry in entries[
@@ -499,7 +564,9 @@ def render_element_index(database_column, linked_table, folder):
elements.append({'id': entry.id, 'name': entry.id})
pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page,
len(entries) + 1)
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
return render_xml_template('feed.xml',
letterelements=elements,
folder=folder,
pagination=pagination)
pagination=pagination,
cc=cc)
+10 -11
View File
@@ -29,7 +29,7 @@
from urllib.parse import urlparse, urljoin
from flask import request, url_for, redirect
from flask import request, url_for, current_app
def is_safe_url(target):
@@ -38,16 +38,15 @@ def is_safe_url(target):
return test_url.scheme in ('http', 'https') and ref_url.netloc == test_url.netloc
def get_redirect_target():
for target in request.values.get('next'), request.referrer:
if not target:
continue
if is_safe_url(target):
return target
def remove_prefix(text, prefix):
if text.startswith(prefix):
return text[len(prefix):]
return ""
def redirect_back(endpoint, **values):
target = request.form['next']
if not target or not is_safe_url(target):
def get_redirect_location(next, endpoint, **values):
target = next or url_for(endpoint, **values)
adapter = current_app.url_map.bind(urlparse(request.host_url).netloc)
if not len(adapter.allowed_methods(remove_prefix(target, request.environ.get('HTTP_X_SCRIPT_NAME',"")))):
target = url_for(endpoint, **values)
return redirect(target)
return target
+3 -2
View File
@@ -25,12 +25,13 @@ from datetime import datetime
from functools import wraps
from flask import Blueprint, request, make_response, abort, url_for, flash, redirect
from flask_login import login_required, current_user, login_user
from .cw_login import login_user, current_user
from flask_babel import gettext as _
from sqlalchemy.sql.expression import true
from . import config, logger, ub
from .render_template import render_title_template
from .usermanagement import user_login_required
remotelogin = Blueprint('remotelogin', __name__)
@@ -65,7 +66,7 @@ def remote_login():
@remotelogin.route('/verify/<token>')
@remote_login_required
@login_required
@user_login_required
def verify_token(token):
auth_token = ub.session.query(ub.RemoteAuthToken).filter(ub.RemoteAuthToken.auth_token == token).first()
+13 -14
View File
@@ -19,14 +19,13 @@
from flask import render_template, g, abort, request
from flask_babel import gettext as _
from werkzeug.local import LocalProxy
from flask_login import current_user
from .cw_login import current_user
from sqlalchemy.sql.expression import or_
from . import config, constants, logger, ub
from .ub import User
log = logger.create()
def get_sidebar_config(kwargs=None):
@@ -48,7 +47,7 @@ def get_sidebar_config(kwargs=None):
if current_user.role_admin():
sidebar.append({"glyph": "glyphicon-download", "text": _('Downloaded Books'), "link": 'web.download_list',
"id": "download", "visibility": constants.SIDEBAR_DOWNLOAD, 'public': (not current_user.is_anonymous),
"page": "download", "show_text": _('Show Downloaded Books'),
"page": "download", "show_text": _('Show Downloaded Books'), "no_param":True,
"config_show": content})
else:
sidebar.append({"glyph": "glyphicon-download", "text": _('Downloaded Books'), "link": 'web.books_list',
@@ -70,37 +69,37 @@ def get_sidebar_config(kwargs=None):
"visibility": constants.SIDEBAR_RANDOM, 'public': True, "page": "discover",
"show_text": _('Show Random Books'), "config_show": True})
sidebar.append({"glyph": "glyphicon-inbox", "text": _('Categories'), "link": 'web.category_list', "id": "cat",
"visibility": constants.SIDEBAR_CATEGORY, 'public': True, "page": "category",
"visibility": constants.SIDEBAR_CATEGORY, 'public': True, "page": "category", "no_param":True,
"show_text": _('Show Category Section'), "config_show": True})
sidebar.append({"glyph": "glyphicon-bookmark", "text": _('Series'), "link": 'web.series_list', "id": "serie",
"visibility": constants.SIDEBAR_SERIES, 'public': True, "page": "series",
"visibility": constants.SIDEBAR_SERIES, 'public': True, "page": "series", "no_param":True,
"show_text": _('Show Series Section'), "config_show": True})
sidebar.append({"glyph": "glyphicon-user", "text": _('Authors'), "link": 'web.author_list', "id": "author",
"visibility": constants.SIDEBAR_AUTHOR, 'public': True, "page": "author",
"visibility": constants.SIDEBAR_AUTHOR, 'public': True, "page": "author", "no_param":True,
"show_text": _('Show Author Section'), "config_show": True})
sidebar.append(
{"glyph": "glyphicon-text-size", "text": _('Publishers'), "link": 'web.publisher_list', "id": "publisher",
"visibility": constants.SIDEBAR_PUBLISHER, 'public': True, "page": "publisher",
"visibility": constants.SIDEBAR_PUBLISHER, 'public': True, "page": "publisher", "no_param":True,
"show_text": _('Show Publisher Section'), "config_show":True})
sidebar.append({"glyph": "glyphicon-flag", "text": _('Languages'), "link": 'web.language_overview', "id": "lang",
"visibility": constants.SIDEBAR_LANGUAGE, 'public': (current_user.filter_language() == 'all'),
"page": "language",
"page": "language", "no_param":True,
"show_text": _('Show Language Section'), "config_show": True})
sidebar.append({"glyph": "glyphicon-star-empty", "text": _('Ratings'), "link": 'web.ratings_list', "id": "rate",
"visibility": constants.SIDEBAR_RATING, 'public': True,
"visibility": constants.SIDEBAR_RATING, 'public': True, "no_param":True,
"page": "rating", "show_text": _('Show Ratings Section'), "config_show": True})
sidebar.append({"glyph": "glyphicon-file", "text": _('File formats'), "link": 'web.formats_list', "id": "format",
"visibility": constants.SIDEBAR_FORMAT, 'public': True,
"visibility": constants.SIDEBAR_FORMAT, 'public': True, "no_param":True,
"page": "format", "show_text": _('Show File Formats Section'), "config_show": True})
sidebar.append(
{"glyph": "glyphicon-trash", "text": _('Archived Books'), "link": 'web.books_list', "id": "archived",
{"glyph": "glyphicon-folder-open", "text": _('Archived Books'), "link": 'web.books_list', "id": "archived",
"visibility": constants.SIDEBAR_ARCHIVED, 'public': (not current_user.is_anonymous), "page": "archived",
"show_text": _('Show Archived Books'), "config_show": content})
if not simple:
sidebar.append(
{"glyph": "glyphicon-th-list", "text": _('Books List'), "link": 'web.books_table', "id": "list",
"visibility": constants.SIDEBAR_LIST, 'public': (not current_user.is_anonymous), "page": "list",
"show_text": _('Show Books List'), "config_show": content})
"visibility": constants.SIDEBAR_LIST, 'public': (not current_user.is_anonymous),
"show_text": _('Show Books List'), "config_show": content, "no_param":True})
g.shelves_access = ub.session.query(ub.Shelf).filter(
or_(ub.Shelf.is_public == 1, ub.Shelf.user_id == current_user.id)).order_by(ub.Shelf.name).all()
@@ -112,7 +111,7 @@ def render_title_template(*args, **kwargs):
sidebar, simple = get_sidebar_config(kwargs)
try:
return render_template(instance=config.config_calibre_web_title, sidebar=sidebar, simple=simple,
accept=constants.EXTENSIONS_UPLOAD,
accept=config.config_upload_formats.split(','),
*args, **kwargs)
except PermissionError:
log.error("No permission to access {} file.".format(args[0]))
+4 -2
View File
@@ -41,9 +41,9 @@ class ReverseProxied(object):
"""Wrap the application in this middleware and configure the
front-end server to add these headers, to let you quietly bind
this to a URL other than / and to an HTTP scheme that is
different than what is used locally.
different from what is used locally.
Code courtesy of: http://flask.pocoo.org/snippets/35/
Code courtesy of: https://flask.pocoo.org/snippets/35/
In nginx:
location /myprefix {
@@ -61,11 +61,13 @@ class ReverseProxied(object):
def __call__(self, environ, start_response):
self.proxied = False
self.script_name = "/"
script_name = environ.get('HTTP_X_SCRIPT_NAME', '')
if script_name:
self.proxied = True
environ['SCRIPT_NAME'] = script_name
path_info = environ.get('PATH_INFO', '')
self.script_name = script_name
if path_info and path_info.startswith(script_name):
environ['PATH_INFO'] = path_info[len(script_name):]
+11 -2
View File
@@ -21,6 +21,7 @@ import datetime
from . import config, constants
from .services.background_scheduler import BackgroundScheduler, CronTrigger, use_APScheduler
from .tasks.database import TaskReconnectDatabase
from .tasks.clean import TaskClean
from .tasks.thumbnail import TaskGenerateCoverThumbnails, TaskGenerateSeriesThumbnails, TaskClearCoverThumbnailCache
from .services.worker import WorkerThread
from .tasks.metadata_backup import TaskBackupMetadata
@@ -31,6 +32,9 @@ def get_scheduled_tasks(reconnect=True):
if reconnect:
tasks.append([lambda: TaskReconnectDatabase(), 'reconnect', False])
# Delete temp folder
tasks.append([lambda: TaskClean(), 'delete temp', True])
# Generate metadata.opf file for each changed book
if config.schedule_metadata_backup:
tasks.append([lambda: TaskBackupMetadata("en"), 'backup metadata', False])
@@ -65,9 +69,12 @@ def register_scheduled_tasks(reconnect=True):
duration = config.schedule_duration
# Register scheduled tasks
scheduler.schedule_tasks(tasks=get_scheduled_tasks(reconnect), trigger=CronTrigger(hour=start))
timezone_info = datetime.datetime.now(datetime.timezone.utc).astimezone().tzinfo
scheduler.schedule_tasks(tasks=get_scheduled_tasks(reconnect), trigger=CronTrigger(hour=start,
timezone=timezone_info))
end_time = calclulate_end_time(start, duration)
scheduler.schedule(func=end_scheduled_tasks, trigger=CronTrigger(hour=end_time.hour, minute=end_time.minute),
scheduler.schedule(func=end_scheduled_tasks, trigger=CronTrigger(hour=end_time.hour, minute=end_time.minute,
timezone=timezone_info),
name="end scheduled task")
# Kick-off tasks, if they should currently be running
@@ -86,6 +93,8 @@ def register_startup_tasks():
# Ignore tasks that should currently be running, as these will be added when registering scheduled tasks
if constants.APP_MODE in ['development', 'test'] and not should_task_be_running(start, duration):
scheduler.schedule_tasks_immediately(tasks=get_scheduled_tasks(False))
else:
scheduler.schedule_tasks_immediately(tasks=[[lambda: TaskClean(), 'delete temp', True]])
def should_task_be_running(start, duration):
+86 -39
View File
@@ -19,29 +19,30 @@ from datetime import datetime
from flask import Blueprint, request, redirect, url_for, flash
from flask import session as flask_session
from flask_login import current_user
from .cw_login import current_user
from flask_babel import format_date
from flask_babel import gettext as _
from sqlalchemy.sql.expression import func, not_, and_, or_, text, true
from sqlalchemy.sql.functions import coalesce
from . import logger, db, calibre_db, config, ub
from .string_helper import strip_whitespaces
from .usermanagement import login_required_if_no_ano
from .render_template import render_title_template
from .pagination import Pagination
search = Blueprint('search', __name__)
log = logger.create()
@search.route("/search", methods=["POST"])
@search.route("/search", methods=["GET"])
@login_required_if_no_ano
def simple_search():
term = dict(request.form).get("query")
term = request.args.get("query")
if term:
flask_session['query'] = json.dumps(term.strip())
return redirect(url_for('web.books_list', data="search", sort_param='stored', query="")) # term.strip()
return redirect(url_for('web.books_list', data="search", sort_param='stored', query=term.strip()))
else:
return render_title_template('search.html',
searchterm="",
@@ -81,16 +82,27 @@ def adv_search_custom_columns(cc, term, q):
if custom_end:
q = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any(
func.datetime(db.cc_classes[c.id].value) <= func.datetime(custom_end)))
elif c.datatype in ["int", "float"]:
custom_low = term.get('custom_column_' + str(c.id) + '_low')
custom_high = term.get('custom_column_' + str(c.id) + '_high')
if custom_low:
q = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any(
db.cc_classes[c.id].value >= custom_low))
if custom_high:
q = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any(
db.cc_classes[c.id].value <= custom_high))
else:
custom_query = term.get('custom_column_' + str(c.id))
if custom_query != '' and custom_query is not None:
if c.datatype == 'bool':
q = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any(
db.cc_classes[c.id].value == (custom_query == "True")))
elif c.datatype == 'int' or c.datatype == 'float':
q = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any(
db.cc_classes[c.id].value == custom_query))
elif c.datatype == 'rating':
if c.datatype == 'bool':
if custom_query != "Any":
if custom_query == "":
q = q.filter(~getattr(db.Books, 'custom_column_' + str(c.id)).
any(db.cc_classes[c.id].value >= 0))
else:
q = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any(
db.cc_classes[c.id].value == bool(custom_query == "True")))
elif custom_query != '' and custom_query is not None:
if c.datatype == 'rating':
q = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any(
db.cc_classes[c.id].value == int(float(custom_query) * 2)))
else:
@@ -129,10 +141,10 @@ def adv_search_read_status(read_status):
db_filter = coalesce(ub.ReadBook.read_status, 0) != ub.ReadBook.STATUS_FINISHED
else:
try:
if read_status == "True":
db_filter = db.cc_classes[config.config_read_column].value == True
if read_status == "":
db_filter = coalesce(db.cc_classes[config.config_read_column].value, 2) == 2
else:
db_filter = coalesce(db.cc_classes[config.config_read_column].value, False) != True
db_filter = db.cc_classes[config.config_read_column].value == bool(read_status == "True")
except (KeyError, AttributeError, IndexError):
log.error("Custom Column No.{} does not exist in calibre database".format(config.config_read_column))
flash(_("Custom Column No.%(column)d does not exist in calibre database",
@@ -165,11 +177,24 @@ def adv_search_serie(q, include_series_inputs, exclude_series_inputs):
q = q.filter(not_(db.Books.series.any(db.Series.id == serie)))
return q
def adv_search_shelf(q, include_shelf_inputs, exclude_shelf_inputs):
q = q.outerjoin(ub.BookShelf, db.Books.id == ub.BookShelf.book_id)\
.filter(or_(ub.BookShelf.shelf == None, ub.BookShelf.shelf.notin_(exclude_shelf_inputs)))
if len(include_shelf_inputs) > 0:
q = q.filter(ub.BookShelf.shelf.in_(include_shelf_inputs))
if len(include_shelf_inputs):
in_shelf = (
calibre_db.session.query(ub.BookShelf.id)
.filter(ub.BookShelf.book_id == db.Books.id)
.filter(ub.BookShelf.shelf.in_(include_shelf_inputs))
.exists()
)
q = q.filter(in_shelf)
if len(exclude_shelf_inputs):
ex_shelf = (
calibre_db.session.query(ub.BookShelf.id)
.filter(ub.BookShelf.book_id == db.Books.id)
.filter(ub.BookShelf.shelf.in_(exclude_shelf_inputs))
.exists()
)
q = q.filter(~ex_shelf)
return q
def extend_search_term(searchterm,
@@ -218,8 +243,8 @@ def extend_search_term(searchterm,
searchterm.extend([_("Rating <= %(rating)s", rating=rating_high)])
if rating_low:
searchterm.extend([_("Rating >= %(rating)s", rating=rating_low)])
if read_status:
searchterm.extend([_("Read Status = %(status)s", status=read_status)])
if read_status != "Any":
searchterm.extend([_("Read Status = '%(status)s'", status=read_status)])
searchterm.extend(ext for ext in tags['include_extension'])
searchterm.extend(ext for ext in tags['exclude_extension'])
# handle custom columns
@@ -232,7 +257,7 @@ def render_adv_search_results(term, offset=None, order=None, limit=None):
pagination = None
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
calibre_db.session.connection().connection.connection.create_function("lower", 1, db.lcase)
calibre_db.create_functions()
query = calibre_db.generate_linked_query(config.config_read_column, db.Books)
q = query.outerjoin(db.books_series_link, db.Books.id == db.books_series_link.c.book)\
.outerjoin(db.Series)\
@@ -245,21 +270,21 @@ def render_adv_search_results(term, offset=None, order=None, limit=None):
tags['include_' + element] = term.get('include_' + element)
tags['exclude_' + element] = term.get('exclude_' + element)
author_name = term.get("author_name")
book_title = term.get("book_title")
author_name = term.get("authors")
book_title = term.get("title")
publisher = term.get("publisher")
pub_start = term.get("publishstart")
pub_end = term.get("publishend")
rating_low = term.get("ratinghigh")
rating_high = term.get("ratinglow")
description = term.get("comment")
description = term.get("comments")
read_status = term.get("read_status")
if author_name:
author_name = author_name.strip().lower().replace(',', '|')
author_name = strip_whitespaces(author_name).lower().replace(',', '|')
if book_title:
book_title = book_title.strip().lower()
book_title = strip_whitespaces(book_title).lower()
if publisher:
publisher = publisher.strip().lower()
publisher = strip_whitespaces(publisher).lower()
search_term = []
cc_present = False
@@ -275,16 +300,29 @@ def render_adv_search_results(term, offset=None, order=None, limit=None):
cc_present = True
if column_end:
search_term.extend(["{} <= {}".format(c.name,
format_date(datetime.strptime(column_end, "%Y-%m-%d").date(),
format_date(datetime.strptime(column_end, "%Y-%m-%d").date(),
format='medium')
)])
cc_present = True
if c.datatype in ["int", "float"]:
column_low = term.get('custom_column_' + str(c.id) + '_low')
column_high = term.get('custom_column_' + str(c.id) + '_high')
if column_low:
search_term.extend(["{} >= {}".format(c.name, column_low)])
cc_present = True
if column_high:
search_term.extend(["{} <= {}".format(c.name,column_high)])
cc_present = True
elif c.datatype == "bool":
if term.get('custom_column_' + str(c.id)) != "Any":
search_term.extend([("{}: {}".format(c.name, term.get('custom_column_' + str(c.id))))])
cc_present = True
elif term.get('custom_column_' + str(c.id)):
search_term.extend([("{}: {}".format(c.name, term.get('custom_column_' + str(c.id))))])
cc_present = True
if any(tags.values()) or author_name or book_title or publisher or pub_start or pub_end or rating_low \
or rating_high or description or cc_present or read_status:
or rating_high or description or cc_present or read_status != "Any":
search_term, pub_start, pub_end = extend_search_term(search_term,
author_name,
book_title,
@@ -303,7 +341,8 @@ def render_adv_search_results(term, offset=None, order=None, limit=None):
q = q.filter(func.datetime(db.Books.pubdate) > func.datetime(pub_start))
if pub_end:
q = q.filter(func.datetime(db.Books.pubdate) < func.datetime(pub_end))
q = q.filter(adv_search_read_status(read_status))
if read_status != "Any":
q = q.filter(adv_search_read_status(read_status))
if publisher:
q = q.filter(db.Books.publishers.any(func.lower(db.Publishers.name).ilike("%" + publisher + "%")))
q = adv_search_tag(q, tags['include_tag'], tags['exclude_tag'])
@@ -314,10 +353,12 @@ def render_adv_search_results(term, offset=None, order=None, limit=None):
q = adv_search_ratings(q, rating_high, rating_low)
if description:
pass
q = q.filter(db.Books.comments.any(func.lower(db.Comments.text).ilike("%" + description + "%")))
# search custom columns
try:
pass
q = adv_search_custom_columns(cc, term, q)
except AttributeError as ex:
log.debug_or_exception(ex)
@@ -376,13 +417,19 @@ def render_prepare_search_form(cc):
def render_search_results(term, offset=None, order=None, limit=None):
join = db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series
entries, result_count, pagination = calibre_db.get_search_results(term,
config,
offset,
order,
limit,
*join)
if term:
join = db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series
entries, result_count, pagination = calibre_db.get_search_results(term,
config,
offset,
order,
limit,
*join)
else:
entries = list()
order = [None, None]
pagination = result_count = None
return render_title_template('search.html',
searchterm=term,
pagination=pagination,
+11 -15
View File
@@ -23,17 +23,16 @@ import json
import os
import sys
from flask import Blueprint, Response, request, url_for
from flask_login import current_user
from flask_login import login_required
from flask import Blueprint, request, url_for, make_response, jsonify
from .cw_login import current_user
from flask_babel import get_locale
from sqlalchemy.exc import InvalidRequestError, OperationalError
from sqlalchemy.orm.attributes import flag_modified
from cps.services.Metadata import Metadata
from . import constants, logger, ub, web_server
from .usermanagement import user_login_required
# current_milli_time = lambda: int(round(time() * 1000))
meta = Blueprint("metadata", __name__)
@@ -81,7 +80,7 @@ cl = list_classes(new_list)
@meta.route("/metadata/provider")
@login_required
@user_login_required
def metadata_provider():
active = current_user.view_settings.get("metadata", {})
provider = list()
@@ -90,12 +89,12 @@ def metadata_provider():
provider.append(
{"name": c.__name__, "active": ac, "initial": ac, "id": c.__id__}
)
return Response(json.dumps(provider), mimetype="application/json")
return make_response(jsonify(provider))
@meta.route("/metadata/provider", methods=["POST"])
@meta.route("/metadata/provider/<prov_name>", methods=["POST"])
@login_required
@user_login_required
def metadata_change_active_provider(prov_name):
new_state = request.get_json()
active = current_user.view_settings.get("metadata", {})
@@ -115,14 +114,12 @@ def metadata_change_active_provider(prov_name):
provider = next((c for c in cl if c.__id__ == prov_name), None)
if provider is not None:
data = provider.search(new_state.get("query", ""))
return Response(
json.dumps([asdict(x) for x in data]), mimetype="application/json"
)
return make_response(jsonify([asdict(x) for x in data]))
return ""
@meta.route("/metadata/search", methods=["POST"])
@login_required
@user_login_required
def metadata_search():
query = request.form.to_dict().get("query")
data = list()
@@ -130,7 +127,7 @@ def metadata_search():
locale = get_locale()
if query:
static_cover = url_for("static", filename="generic_cover.jpg")
# start = current_milli_time()
# ret = cl[0].search(query, static_cover, locale)
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
meta = {
executor.submit(c.search, query, static_cover, locale): c
@@ -138,6 +135,5 @@ def metadata_search():
if active.get(c.__id__, True)
}
for future in concurrent.futures.as_completed(meta):
data.extend([asdict(x) for x in future.result() if x])
# log.info({'Time elapsed {}'.format(current_milli_time()-start)})
return Response(json.dumps(data), mimetype="application/json")
data.extend([asdict(x) for x in (future.result() or []) if x])
return make_response(jsonify(data))
+85 -32
View File
@@ -21,12 +21,12 @@ import os
import errno
import signal
import socket
import subprocess # nosec
try:
from gevent.pywsgi import WSGIServer
from .gevent_wsgi import MyWSGIHandler
from gevent.pool import Pool
from gevent.socket import socket as GeventSocket
from gevent import __version__ as _version
from greenlet import GreenletExit
import ssl
@@ -36,11 +36,12 @@ except ImportError:
from .tornado_wsgi import MyWSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado import netutil
from tornado import version as _version
VERSION = 'Tornado ' + _version
_GEVENT = False
from . import logger
from . import logger, constants
log = logger.create()
@@ -95,7 +96,13 @@ class WebServer(object):
log.warning('Cert path: %s', certfile_path)
log.warning('Key path: %s', keyfile_path)
def _make_gevent_unix_socket(self, socket_file):
@staticmethod
def _make_gevent_socket_activated():
# Reuse an already open socket on fd=SD_LISTEN_FDS_START
SD_LISTEN_FDS_START = 3
return GeventSocket(fileno=SD_LISTEN_FDS_START)
def _prepare_unix_socket(self, socket_file):
# the socket file must not exist prior to bind()
if os.path.exists(socket_file):
# avoid nuking regular files and symbolic links (could be a mistype or security issue)
@@ -103,35 +110,41 @@ class WebServer(object):
raise OSError(errno.EEXIST, os.strerror(errno.EEXIST), socket_file)
os.remove(socket_file)
unix_sock = WSGIServer.get_listener(socket_file, family=socket.AF_UNIX)
self.unix_socket_file = socket_file
# ensure current user and group have r/w permissions, no permissions for other users
# this way the socket can be shared in a semi-secure manner
# between the user running calibre-web and the user running the fronting webserver
os.chmod(socket_file, 0o660)
return unix_sock
def _make_gevent_socket(self):
def _make_gevent_listener(self):
if os.name != 'nt':
socket_activated = os.environ.get("LISTEN_FDS")
if socket_activated:
sock = self._make_gevent_socket_activated()
sock_info = sock.getsockname()
return sock, "systemd-socket:" + _readable_listen_address(sock_info[0], sock_info[1])
unix_socket_file = os.environ.get("CALIBRE_UNIX_SOCKET")
if unix_socket_file:
return self._make_gevent_unix_socket(unix_socket_file), "unix:" + unix_socket_file
self._prepare_unix_socket(unix_socket_file)
unix_sock = WSGIServer.get_listener(unix_socket_file, family=socket.AF_UNIX)
# ensure current user and group have r/w permissions, no permissions for other users
# this way the socket can be shared in a semi-secure manner
# between the user running calibre-web and the user running the fronting webserver
os.chmod(unix_socket_file, 0o660)
return unix_sock, "unix:" + unix_socket_file
if self.listen_address:
return (self.listen_address, self.listen_port), None
return ((self.listen_address, self.listen_port),
_readable_listen_address(self.listen_address, self.listen_port))
if os.name == 'nt':
self.listen_address = '0.0.0.0'
return (self.listen_address, self.listen_port), None
return ((self.listen_address, self.listen_port),
_readable_listen_address(self.listen_address, self.listen_port))
address = ('::', self.listen_port)
try:
address = ('::', self.listen_port)
sock = WSGIServer.get_listener(address, family=socket.AF_INET6)
except socket.error as ex:
log.error('%s', ex)
log.warning('Unable to listen on "", trying on IPv4 only...')
log.warning('Unable to listen on {}, trying on IPv4 only...'.format(address))
address = ('', self.listen_port)
sock = WSGIServer.get_listener(address, family=socket.AF_INET)
@@ -201,10 +214,15 @@ class WebServer(object):
ssl_args = self.ssl_args or {}
try:
sock, output = self._make_gevent_socket()
if output is None:
output = _readable_listen_address(self.listen_address, self.listen_port)
sock, output = self._make_gevent_listener()
log.info('Starting Gevent server on %s', output)
try:
# Also print to stdout so interactive terminals show a clear success message
if constants.APP_MODE not in ['development', 'test']:
print(f"Calibre-Web: server started on {output}")
except Exception:
print(f"Calibre-Web: error {output}")
pass
self.wsgiserver = WSGIServer(sock, self.app, log=self.access_logger, handler_class=MyWSGIHandler,
error_log=log,
spawn=Pool(), **ssl_args)
@@ -228,17 +246,49 @@ class WebServer(object):
if os.name == 'nt' and sys.version_info > (3, 7):
import asyncio
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
log.info('Starting Tornado server on %s', _readable_listen_address(self.listen_address, self.listen_port))
try:
# Max Buffersize set to 200MB
http_server = HTTPServer(MyWSGIContainer(self.app),
max_buffer_size=209700000,
ssl_options=self.ssl_args)
# Max Buffersize set to 200MB
http_server = HTTPServer(MyWSGIContainer(self.app),
max_buffer_size=209700000,
ssl_options=self.ssl_args)
http_server.listen(self.listen_port, self.listen_address)
self.wsgiserver = IOLoop.current()
self.wsgiserver.start()
# wait for stop signal
self.wsgiserver.close(True)
unix_socket_file = os.environ.get("CALIBRE_UNIX_SOCKET")
if os.environ.get("LISTEN_FDS") and os.name != 'nt':
SD_LISTEN_FDS_START = 3
sock = socket.socket(fileno=SD_LISTEN_FDS_START)
http_server.add_socket(sock)
sock.setblocking(0)
socket_name =sock.getsockname()
output = "systemd-socket:" + _readable_listen_address(socket_name[0], socket_name[1])
elif unix_socket_file and os.name != 'nt':
self._prepare_unix_socket(unix_socket_file)
output = "unix:" + unix_socket_file
unix_socket = netutil.bind_unix_socket(self.unix_socket_file)
http_server.add_socket(unix_socket)
# ensure current user and group have r/w permissions, no permissions for other users
# this way the socket can be shared in a semi-secure manner
# between the user running calibre-web and the user running the fronting webserver
os.chmod(self.unix_socket_file, 0o660)
else:
output = _readable_listen_address(self.listen_address, self.listen_port)
http_server.listen(self.listen_port, self.listen_address)
log.info('Starting Tornado server on %s', output)
# Also print to stdout so interactive terminals show a clear success message
try:
if constants.APP_MODE not in ['development', 'test']:
print(f"Calibre-Web: server started on {output}")
except Exception:
print(f"Calibre-Web: error {output}")
pass
self.wsgiserver = IOLoop.current()
self.wsgiserver.start()
# wait for stop signal
self.wsgiserver.close(True)
finally:
if self.unix_socket_file:
os.remove(self.unix_socket_file)
self.unix_socket_file = None
def start(self):
try:
@@ -265,7 +315,6 @@ class WebServer(object):
log.info("Performing restart of Calibre-Web")
args = self._get_args_for_reloading()
os.execv(args[0].lstrip('"').rstrip('"'), args)
return True
@staticmethod
def shutdown_scheduler():
@@ -288,4 +337,8 @@ class WebServer(object):
if _GEVENT:
self.wsgiserver.close()
else:
self.wsgiserver.add_callback_from_signal(self.wsgiserver.stop)
if restart:
self.wsgiserver.call_later(1.0, self.wsgiserver.stop)
else:
self.wsgiserver.asyncio_loop.call_soon_threadsafe(self.wsgiserver.stop)
+9 -11
View File
@@ -19,11 +19,9 @@
import sys
from base64 import b64decode, b64encode
from jsonschema import validate, exceptions, __version__
from jsonschema import validate, exceptions
from datetime import datetime
from urllib.parse import unquote
from flask import json
from .. import logger
@@ -32,10 +30,10 @@ log = logger.create()
def b64encode_json(json_data):
return b64encode(json.dumps(json_data).encode())
return b64encode(json.dumps(json_data).encode()).decode("utf-8")
# Python3 has a timestamp() method we could be calling, however it's not avaiable in python2.
# Python3 has a timestamp() method we could be calling, however it's not available in python2.
def to_epoch_timestamp(datetime_object):
return (datetime_object - datetime(1970, 1, 1)).total_seconds()
@@ -49,7 +47,7 @@ def get_datetime_from_json(json_object, field_name):
class SyncToken:
""" The SyncToken is used to persist state accross requests.
""" The SyncToken is used to persist state across requests.
When serialized over the response headers, the Kobo device will propagate the token onto following
requests to the service. As an example use-case, the SyncToken is used to detect books that have been added
to the library since the last time the device synced to the server.
@@ -175,8 +173,8 @@ class SyncToken:
def __str__(self):
return "{},{},{},{},{},{}".format(self.books_last_created,
self.books_last_modified,
self.archive_last_modified,
self.reading_state_last_modified,
self.tags_last_modified,
self.raw_kobo_store_token)
self.books_last_modified,
self.archive_last_modified,
self.reading_state_last_modified,
self.tags_last_modified,
self.raw_kobo_store_token)
+1
View File
@@ -42,6 +42,7 @@ class BackgroundScheduler:
if cls._instance is None:
cls._instance = super(BackgroundScheduler, cls).__new__(cls)
cls.log = logger.create()
logger.logging.getLogger('tzlocal').setLevel(logger.logging.WARNING)
cls.scheduler = BScheduler()
cls.scheduler.start()
+2 -1
View File
@@ -36,6 +36,7 @@ SCOPES = ['openid', 'https://www.googleapis.com/auth/gmail.send', 'https://www.g
def setup_gmail(token):
# If there are no (valid) credentials available, let the user log in.
creds = None
user_info = None
if "token" in token:
creds = Credentials(
token=token['token'],
@@ -91,7 +92,7 @@ def send_messsage(token, msg):
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
service = build('gmail', 'v1', credentials=creds)
message_as_bytes = msg.as_bytes() # the message should converted from string to bytes.
message_as_bytes = msg.as_bytes() # the message should be converted from string to bytes.
message_as_base64 = base64.urlsafe_b64encode(message_as_bytes) # encode in base64 (printable letters coding)
raw = message_as_base64.decode() # convert to something JSON serializable
body = {'raw': raw}
+83 -11
View File
@@ -18,16 +18,86 @@
import time
from functools import reduce
import requests
from goodreads.client import GoodreadsClient
from goodreads.request import GoodreadsRequest
from lxml import etree
try:
from goodreads.client import GoodreadsClient
import Levenshtein
except ImportError:
from betterreads.client import GoodreadsClient
try: import Levenshtein
except ImportError: Levenshtein = False
Levenshtein = False
from .. import logger
from ..clean_html import clean_string
def etree_to_dict(t):
"""
Convert lxml ElementTree to a nested dict (similar to xmltodict).
"""
d = {t.tag: {} if t.attrib else None}
children = list(t)
if children:
dd = {}
for dc in map(etree_to_dict, children):
for k, v in dc.items():
if k in dd:
if not isinstance(dd[k], list):
dd[k] = [dd[k]]
dd[k].append(v)
else:
dd[k] = v
d = {t.tag: dd}
if t.attrib:
d[t.tag].update(('@' + k, v) for k, v in t.attrib.items())
text = (t.text or '').strip()
if text:
if children or t.attrib:
d[t.tag]['#text'] = text
else:
d[t.tag] = text
return d
class my_GoodreadsClient(GoodreadsClient):
def request(self, *args, **kwargs):
"""Create a GoodreadsRequest object and make that request"""
req = my_GoodreadsRequest(self, *args, **kwargs)
return req.request()
class GoodreadsRequestException(Exception):
def __init__(self, error_msg, url):
self.error_msg = error_msg
self.url = url
def __str__(self):
return self.url, ':', self.error_msg
class my_GoodreadsRequest(GoodreadsRequest):
def request(self):
resp = requests.get(self.host+self.path, params=self.params,
headers={"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:125.0) "
"Gecko/20100101 Firefox/125.0"})
if resp.status_code != 200:
raise GoodreadsRequestException(resp.reason, self.path)
if self.req_format == 'xml':
root = etree.fromstring(resp.content, parser=etree.XMLParser(resolve_entities=False, no_network=True))
data_dict = etree_to_dict(root)
return data_dict['GoodreadsResponse']
else:
raise Exception("Invalid format")
log = logger.create()
@@ -38,20 +108,20 @@ _CACHE_TIMEOUT = 23 * 60 * 60 # 23 hours (in seconds)
_AUTHORS_CACHE = {}
def connect(key=None, secret=None, enabled=True):
def connect(key=None, enabled=True):
global _client
if not enabled or not key or not secret:
if not enabled or not key:
_client = None
return
if _client:
# make sure the configuration has not changed since last we used the client
if _client.client_key != key or _client.client_secret != secret:
if _client.client_key != key:
_client = None
if not _client:
_client = GoodreadsClient(key, secret)
_client = my_GoodreadsClient(key, None)
def get_author_info(author_name):
@@ -76,12 +146,13 @@ def get_author_info(author_name):
if author_info:
author_info._timestamp = now
author_info.safe_about = clean_string(author_info.about)
_AUTHORS_CACHE[author_name] = author_info
return author_info
def get_other_books(author_info, library_books=None):
# Get all identifiers (ISBN, Goodreads, etc) and filter author's books by that list so we show fewer duplicates
# Get all identifiers (ISBN, Goodreads, etc.) and filter author's books by that list so we show fewer duplicates
# Note: Not all images will be shown, even though they're available on Goodreads.com.
# See https://www.goodreads.com/topic/show/18213769-goodreads-book-images
@@ -91,7 +162,8 @@ def get_other_books(author_info, library_books=None):
identifiers = []
library_titles = []
if library_books:
identifiers = list(reduce(lambda acc, book: acc + [i.val for i in book.identifiers if i.val], library_books, []))
identifiers = list(
reduce(lambda acc, book: acc + [i.val for i in book.identifiers if i.val], library_books, []))
library_titles = [book.title for book in library_books]
for book in author_info.books:
+19 -4
View File
@@ -30,9 +30,21 @@ except ImportError:
log = logger.create()
def _escape_ldap_filter(s):
"""Escape special characters for safe use in LDAP filter strings (RFC 4515)."""
s = s.replace('\\', '\\5c')
s = s.replace('*', '\\2a')
s = s.replace('(', '\\28')
s = s.replace(')', '\\29')
s = s.replace('\x00', '\\00')
return s
class LDAPLogger(object):
def write(self, message):
@staticmethod
def write(message):
try:
log.debug(message.strip("\n").replace("\n", ""))
except Exception:
@@ -71,6 +83,7 @@ class mySimpleLDap(LDAP):
_ldap = mySimpleLDap()
def init_app(app, config):
if config.config_login_type != constants.LOGIN_LDAP:
return
@@ -124,7 +137,7 @@ def init_app(app, config):
log.error(e)
def get_object_details(user=None,query_filter=None):
def get_object_details(user=None, query_filter=None):
return _ldap.get_object_details(user, query_filter=query_filter)
@@ -145,9 +158,11 @@ def bind_user(username, password):
:returns: True if login succeeded, False if login failed, None if server unavailable.
'''
# Escape LDAP special characters to prevent LDAP injection in search filters
safe_username = _escape_ldap_filter(username)
try:
if _ldap.get_object_details(username):
result = _ldap.bind_user(username, password)
if _ldap.get_object_details(safe_username):
result = _ldap.bind_user(safe_username, password)
log.debug("LDAP login '%s': %r", username, result)
return result is not None, None
return None, None # User not found
+4 -1
View File
@@ -199,7 +199,7 @@ class CalibreTask:
self.run(*args)
except Exception as ex:
self._handleError(str(ex))
log.error_or_exception(ex)
log.exception(ex)
self.end_time = datetime.now()
@@ -266,3 +266,6 @@ class CalibreTask:
def _handleSuccess(self):
self.stat = STAT_FINISH_SUCCESS
self.progress = 1
def __str__(self):
return self.name
+113 -45
View File
@@ -21,17 +21,17 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys
from datetime import datetime
from datetime import datetime, timezone
from flask import Blueprint, flash, redirect, request, url_for, abort
from flask_babel import gettext as _
from flask_login import current_user, login_required
from .cw_login import current_user
from sqlalchemy.exc import InvalidRequestError, OperationalError
from sqlalchemy.sql.expression import func, true
from . import calibre_db, config, db, logger, ub
from .render_template import render_title_template
from .usermanagement import login_required_if_no_ano
from .usermanagement import login_required_if_no_ano, user_login_required
log = logger.create()
@@ -39,7 +39,7 @@ shelf = Blueprint('shelf', __name__)
@shelf.route("/shelf/add/<int:shelf_id>/<int:book_id>", methods=["POST"])
@login_required
@user_login_required
def add_to_shelf(shelf_id, book_id):
xhr = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.id == shelf_id).first()
@@ -71,8 +71,16 @@ def add_to_shelf(shelf_id, book_id):
else:
maxOrder = maxOrder[0]
if not calibre_db.session.query(db.Books).filter(db.Books.id == book_id).one_or_none():
log.error("Invalid Book Id: %s. Could not be added to shelf %s", book_id, shelf.name)
if not xhr:
flash(_("%(book_id)s is a invalid Book Id. Could not be added to Shelf", book_id=book_id),
category="error")
return redirect(url_for('web.index'))
return "%s is a invalid Book Id. Could not be added to Shelf" % book_id, 400
shelf.books.append(ub.BookShelf(shelf=shelf.id, book_id=book_id, order=maxOrder + 1))
shelf.last_modified = datetime.utcnow()
shelf.last_modified = datetime.now(timezone.utc)
try:
ub.session.merge(shelf)
ub.session.commit()
@@ -94,8 +102,54 @@ def add_to_shelf(shelf_id, book_id):
return "", 204
@shelf.route("/shelf/massremove/<int:shelf_id>", methods=["POST"])
@user_login_required
def search_from_shelf(shelf_id):
shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.id == shelf_id).first()
if shelf is None:
log.error("Invalid shelf specified: {}".format(shelf_id))
flash(_("Invalid shelf specified"), category="error")
return redirect(url_for('web.index'))
if not check_shelf_edit_permissions(shelf):
log.warning("You are not allowed to remove a book from the shelf".format(shelf.name))
flash(_("You are not allowed to remove a book from the shelf"), category="error")
return redirect(url_for('web.index'))
if current_user.id in ub.searched_ids and ub.searched_ids[current_user.id]:
books_from_shelf = list()
books_in_shelf = ub.session.query(ub.BookShelf).filter(ub.BookShelf.shelf == shelf_id).all()
if books_in_shelf:
book_ids = [book_id.book_id for book_id in books_in_shelf]
for searchid in ub.searched_ids[current_user.id]:
if searchid in book_ids:
books_from_shelf.append(searchid)
else:
log.error("No Books are part of {}".format(shelf.name))
flash(_("No Books are part of the shelf: %(name)s", name=shelf.name), category="error")
return redirect(url_for('web.index'))
# maxOrder = ub.session.query(func.max(ub.BookShelf.order)).filter(ub.BookShelf.shelf == shelf_id).first()[0] or 0
for book in books_from_shelf:
ub.session.delete(ub.session.query(ub.BookShelf).filter(ub.BookShelf.shelf == shelf_id).filter(
ub.BookShelf.book_id == book).first())
shelf.last_modified = datetime.now(timezone.utc)
try:
ub.session.commit()
flash(_("Books have been removed from shelf: %(sname)s", sname=shelf.name), category="success")
except (OperationalError, InvalidRequestError) as e:
ub.session.rollback()
log.error_or_exception("Settings Database error: {}".format(e))
flash(_("Oops! Database Error: %(error)s.", error=e.orig), category="error")
else:
log.error("Could not remove books from shelf: {}".format(shelf.name))
flash(_("Could not remove books from shelf: %(sname)s", sname=shelf.name), category="error")
return redirect(url_for('web.index'))
@shelf.route("/shelf/massadd/<int:shelf_id>", methods=["POST"])
@login_required
@user_login_required
def search_to_shelf(shelf_id):
shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.id == shelf_id).first()
if shelf is None:
@@ -112,9 +166,7 @@ def search_to_shelf(shelf_id):
books_for_shelf = list()
books_in_shelf = ub.session.query(ub.BookShelf).filter(ub.BookShelf.shelf == shelf_id).all()
if books_in_shelf:
book_ids = list()
for book_id in books_in_shelf:
book_ids.append(book_id.book_id)
book_ids = [book_id.book_id for book_id in books_in_shelf]
for searchid in ub.searched_ids[current_user.id]:
if searchid not in book_ids:
books_for_shelf.append(searchid)
@@ -131,7 +183,7 @@ def search_to_shelf(shelf_id):
for book in books_for_shelf:
maxOrder += 1
shelf.books.append(ub.BookShelf(shelf=shelf.id, book_id=book, order=maxOrder))
shelf.last_modified = datetime.utcnow()
shelf.last_modified = datetime.now(timezone.utc)
try:
ub.session.merge(shelf)
ub.session.commit()
@@ -147,7 +199,7 @@ def search_to_shelf(shelf_id):
@shelf.route("/shelf/remove/<int:shelf_id>/<int:book_id>", methods=["POST"])
@login_required
@user_login_required
def remove_from_shelf(shelf_id, book_id):
xhr = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.id == shelf_id).first()
@@ -177,7 +229,7 @@ def remove_from_shelf(shelf_id, book_id):
try:
ub.session.delete(book_shelf)
shelf.last_modified = datetime.utcnow()
shelf.last_modified = datetime.now(timezone.utc)
ub.session.commit()
except (OperationalError, InvalidRequestError) as e:
ub.session.rollback()
@@ -204,14 +256,14 @@ def remove_from_shelf(shelf_id, book_id):
@shelf.route("/shelf/create", methods=["GET", "POST"])
@login_required
@user_login_required
def create_shelf():
shelf = ub.Shelf()
return create_edit_shelf(shelf, page_title=_("Create a Shelf"), page="shelfcreate")
@shelf.route("/shelf/edit/<int:shelf_id>", methods=["GET", "POST"])
@login_required
@user_login_required
def edit_shelf(shelf_id):
shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.id == shelf_id).first()
if not check_shelf_edit_permissions(shelf):
@@ -221,7 +273,7 @@ def edit_shelf(shelf_id):
@shelf.route("/shelf/delete/<int:shelf_id>", methods=["POST"])
@login_required
@user_login_required
def delete_shelf(shelf_id):
cur_shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.id == shelf_id).first()
try:
@@ -242,7 +294,7 @@ def show_simpleshelf(shelf_id):
return render_show_shelf(2, shelf_id, 1, None)
@shelf.route("/shelf/<int:shelf_id>", defaults={"sort_param": "order", 'page': 1})
@shelf.route("/shelf/<int:shelf_id>", defaults={"sort_param": "stored", 'page': 1})
@shelf.route("/shelf/<int:shelf_id>/<sort_param>", defaults={'page': 1})
@shelf.route("/shelf/<int:shelf_id>/<sort_param>/<int:page>")
@login_required_if_no_ano
@@ -251,11 +303,14 @@ def show_shelf(shelf_id, sort_param, page):
@shelf.route("/shelf/order/<int:shelf_id>", methods=["GET", "POST"])
@login_required
@user_login_required
def order_shelf(shelf_id):
shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.id == shelf_id).first()
if shelf and check_shelf_view_permissions(shelf):
if request.method == "POST":
if not check_shelf_edit_permissions(shelf):
flash(_("Sorry you are not allowed to edit this shelf"), category="error")
return redirect(url_for('web.index'))
to_save = request.form.to_dict()
books_in_shelf = ub.session.query(ub.BookShelf).filter(ub.BookShelf.shelf == shelf_id).order_by(
ub.BookShelf.order.asc()).all()
@@ -263,7 +318,7 @@ def order_shelf(shelf_id):
for book in books_in_shelf:
setattr(book, 'order', to_save[str(book.book_id)])
counter += 1
# if order different from before -> shelf.last_modified = datetime.utcnow()
# if order different from before -> shelf.last_modified = datetime.now(timezone.utc)
try:
ub.session.commit()
except (OperationalError, InvalidRequestError) as e:
@@ -295,11 +350,14 @@ def check_shelf_edit_permissions(cur_shelf):
def check_shelf_view_permissions(cur_shelf):
if cur_shelf.is_public:
return True
if current_user.is_anonymous or cur_shelf.user_id != current_user.id:
log.error("User is unauthorized to view non-public shelf: {}".format(cur_shelf.name))
return False
try:
if cur_shelf.is_public:
return True
if current_user.is_anonymous or cur_shelf.user_id != current_user.id:
log.error("User is unauthorized to view non-public shelf: {}".format(cur_shelf.name))
return False
except Exception as e:
log.error(e)
return True
@@ -407,29 +465,37 @@ def change_shelf_order(shelf_id, order):
def render_show_shelf(shelf_type, shelf_id, page_no, sort_param):
shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.id == shelf_id).first()
status = current_user.get_view_property("shelf", 'man')
# check user is allowed to access shelf
if shelf and check_shelf_view_permissions(shelf):
if shelf_type == 1:
# order = [ub.BookShelf.order.asc()]
if sort_param == 'pubnew':
change_shelf_order(shelf_id, [db.Books.pubdate.desc()])
if sort_param == 'pubold':
change_shelf_order(shelf_id, [db.Books.pubdate])
if sort_param == 'abc':
change_shelf_order(shelf_id, [db.Books.sort])
if sort_param == 'zyx':
change_shelf_order(shelf_id, [db.Books.sort.desc()])
if sort_param == 'new':
change_shelf_order(shelf_id, [db.Books.timestamp.desc()])
if sort_param == 'old':
change_shelf_order(shelf_id, [db.Books.timestamp])
if sort_param == 'authaz':
change_shelf_order(shelf_id, [db.Books.author_sort.asc(), db.Series.name, db.Books.series_index])
if sort_param == 'authza':
change_shelf_order(shelf_id, [db.Books.author_sort.desc(),
db.Series.name.desc(),
db.Books.series_index.desc()])
if status != 'on':
if sort_param == 'stored':
sort_param = current_user.get_view_property("shelf", 'stored')
else:
current_user.set_view_property("shelf", 'stored', sort_param)
if sort_param == 'pubnew':
change_shelf_order(shelf_id, [db.Books.pubdate.desc()])
if sort_param == 'pubold':
change_shelf_order(shelf_id, [db.Books.pubdate])
if sort_param == 'shelfnew':
change_shelf_order(shelf_id, [ub.BookShelf.date_added.desc()])
if sort_param == 'shelfold':
change_shelf_order(shelf_id, [ub.BookShelf.date_added])
if sort_param == 'abc':
change_shelf_order(shelf_id, [db.Books.sort])
if sort_param == 'zyx':
change_shelf_order(shelf_id, [db.Books.sort.desc()])
if sort_param == 'new':
change_shelf_order(shelf_id, [db.Books.timestamp.desc()])
if sort_param == 'old':
change_shelf_order(shelf_id, [db.Books.timestamp])
if sort_param == 'authaz':
change_shelf_order(shelf_id, [db.Books.author_sort.asc(), db.Series.name, db.Books.series_index])
if sort_param == 'authza':
change_shelf_order(shelf_id, [db.Books.author_sort.desc(),
db.Series.name.desc(),
db.Books.series_index.desc()])
page = "shelf.html"
pagesize = 0
else:
@@ -442,7 +508,7 @@ def render_show_shelf(shelf_type, shelf_id, page_no, sort_param):
[ub.BookShelf.order.asc()],
True, config.config_read_column,
ub.BookShelf, ub.BookShelf.book_id == db.Books.id)
# delete chelf entries where book is not existent anymore, can happen if book is deleted outside calibre-web
# delete shelf entries where book is not existent anymore, can happen if book is deleted outside calibre-web
wrong_entries = calibre_db.session.query(ub.BookShelf) \
.join(db.Books, ub.BookShelf.book_id == db.Books.id, isouter=True) \
.filter(db.Books.id == None).all()
@@ -461,7 +527,9 @@ def render_show_shelf(shelf_type, shelf_id, page_no, sort_param):
pagination=pagination,
title=_("Shelf: '%(name)s'", name=shelf.name),
shelf=shelf,
page="shelf")
page="shelf",
status=status,
order=sort_param)
else:
flash(_("Error opening shelf. Shelf does not exist or is not accessible"), category="error")
return redirect(url_for("web.index"))
+108
View File
@@ -0,0 +1,108 @@
body {
margin: 0;
}
nav {
height: 75px;
padding: 5px 20px;
width: 100%;
display: table;
box-sizing: border-box;
border-bottom: 1px solid black;
}
nav > * {
display: inline-block;
display: table-cell;
vertical-align: middle;
float: none;
text-align: center;
width: auto;
}
nav > *:first-child {
text-align: left;
width: 1%;
}
.theme{
text-align: center;
margin: 10px;
}
nav > *:last-child {
text-align: right;
width: 1%;
}
nav > a {
color: black;
margin: 0 20px;
}
.search {
margin: auto auto;
}
form > input {
width: 18ch;
padding-left: 4px;
}
form > * {
height: 50px;
background-color: white;
border-radius: 0;
border: 1px solid #ccc;
padding: 0;
margin: 0;
display: inline-block;
vertical-align: top;
}
form > span {
margin-left: -5px;
}
button {
border: none;
padding: 0 10px;
margin: 0;
width: 160px;
height: 100%;
background-color: white;
}
.body {
padding: 5px 20px;
}
a {
color: black;
}
img {
width: 150px;
height: 250px;
object-fit: cover;
}
.listing {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
margin-right: 20px;
}
.pagination {
padding: 10px 0;
height: 20px;
font-weight: 700;
}
.pagination > div {
float: left;
}
.pagination > div:last-child {
float: right;
}
+115 -57
View File
@@ -2018,7 +2018,7 @@ body > div.container-fluid > div > div.col-sm-10 > div.pagination > .page-previo
display: none
}
body.authorlist > div.container-fluid > div > div.col-sm-10 > div.container > div.col-xs-12, body.catlist > div.container-fluid > div > div.col-sm-10 > div.container > div.col-xs-12, body.langlist > div.container-fluid > div > div.col-sm-10 > div.container > div.col-sm-6, body.serieslist > div.container-fluid > div > div.col-sm-10 > div.container > div.col-sm-6 {
body.authorlist > div.container-fluid > div > div.col-sm-10 > div.container1 > div.col-xs-12, body.downloadlist > div.container-fluid > div > div.col-sm-10 > div.container1 > div.col-xs-12, body.catlist > div.container-fluid > div > div.col-sm-10 > div.container1 > div.col-xs-12, body.langlist > div.container-fluid > div > div.col-sm-10 > div.container1 > div.col-sm-6, body.serieslist > div.container-fluid > div > div.col-sm-10 > div.container1 > div.col-sm-6 {
width: 100%
}
@@ -2042,7 +2042,7 @@ body.serieslist > div.container-fluid > div > div.col-sm-10:before {
}
}
body > div.container-fluid > div > div.col-sm-10 > div.container {
body > div.container-fluid > div > div.col-sm-10 > div.container1 {
width: calc(80% - 30px);
margin: 120px 0 30px 20%;
border-top: 2px solid rgba(0, 0, 0, .3);
@@ -2051,19 +2051,19 @@ body > div.container-fluid > div > div.col-sm-10 > div.container {
max-width: calc(80% - 30px)
}
body > div.container-fluid > div > div.col-sm-10 > div.container > div {
body > div.container-fluid > div > div.col-sm-10 > div.container1 > div {
padding: 0
}
body > div.container-fluid > div > div.col-sm-10 > div.container > div > .row {
body > div.container-fluid > div > div.col-sm-10 > div.container1 > div > .row {
padding: 4px 0
}
body > div.container-fluid > div > div.col-sm-10 > div.container > div > .row:nth-of-type(even) {
body > div.container-fluid > div > div.col-sm-10 > div.container1 > div > .row:nth-of-type(even) {
background: hsla(0, 0%, 100%, .02)
}
body > div.container-fluid > div > div.col-sm-10 > div.container > div > .row > .col-xs-6 {
body > div.container-fluid > div > div.col-sm-10 > div.container1 > div > .row > .col-xs-6 {
width: calc(91.666% - 30px);
overflow: hidden;
-o-text-overflow: ellipsis;
@@ -2072,7 +2072,7 @@ body > div.container-fluid > div > div.col-sm-10 > div.container > div > .row >
padding-left: 60px
}
body > div.container-fluid > div > div.col-sm-10 > div.container > div > .row > .col-xs-6 > a {
body > div.container-fluid > div > div.col-sm-10 > div.container1 > div > .row > .col-xs-6 > a {
-o-text-overflow: ellipsis;
text-overflow: ellipsis;
white-space: nowrap;
@@ -2082,7 +2082,7 @@ body > div.container-fluid > div > div.col-sm-10 > div.container > div > .row >
}
body > div.container-fluid > div > div.col-sm-10 > div.discover > div.container {
body > div.container-fluid > div > div.col-sm-10 > div.discover > div.container1 {
width: calc(80% - 30px);
margin: 120px 0 30px 20%;
border-top: 2px solid rgba(0, 0, 0, .3);
@@ -2091,19 +2091,19 @@ body > div.container-fluid > div > div.col-sm-10 > div.discover > div.container
max-width: calc(80% - 30px)
}
body > div.container-fluid > div > div.col-sm-10 > div.discover > div.container > div {
body > div.container-fluid > div > div.col-sm-10 > div.discover > div.container1 > div {
padding: 0
}
body > div.container-fluid > div > div.col-sm-10 > div.discover > div.container > div > .row {
body > div.container-fluid > div > div.col-sm-10 > div.discover > div.container1 > div > .row {
padding: 4px 0
}
body > div.container-fluid > div > div.col-sm-10 > div.discover > div.container > div > .row:nth-of-type(even) {
body > div.container-fluid > div > div.col-sm-10 > div.discover > div.container1 > div > .row:nth-of-type(even) {
background: hsla(0, 0%, 100%, .02)
}
body > div.container-fluid > div > div.col-sm-10 > div.discover > div.container > div > .row > .col-xs-6 {
body > div.container-fluid > div > div.col-sm-10 > div.discover > div.container1 > div > .row > .col-xs-6 {
width: calc(91.666% - 30px);
overflow: hidden;
-o-text-overflow: ellipsis;
@@ -2112,7 +2112,7 @@ body > div.container-fluid > div > div.col-sm-10 > div.discover > div.container
padding-left: 60px
}
body > div.container-fluid > div > div.col-sm-10 > div.discover > div.container > div > .row > .col-xs-6 > a {
body > div.container-fluid > div > div.col-sm-10 > div.discover > div.container1 > div > .row > .col-xs-6 > a {
-o-text-overflow: ellipsis;
text-overflow: ellipsis;
white-space: nowrap;
@@ -2146,7 +2146,6 @@ body.catlist > div.container-fluid > div.row-fluid > div.col-sm-10:before {
}
}
body.authorlist > div.container-fluid > div.row-fluid > div.col-sm-10:before, body.langlist > div.container-fluid > div > div.col-sm-10:before {
font-family: 'Glyphicons Halflings', serif;
font-style: normal;
@@ -2172,10 +2171,12 @@ body.authorlist > div.container-fluid > div.row-fluid > div.col-sm-10:before {
}
body.langlist > div.container-fluid > div > div.col-sm-10:before {
content: "\e034"
content: "\e034";
top: 240px;
}
body.authorlist > div.container-fluid > div > div.col-sm-10 > div.container:before, body.catlist > div.container-fluid > div > div.col-sm-10 > div.container:before, body.langlist > div.container-fluid > div > div.col-sm-10 > div.container:before, body.me > div.container-fluid > div > div.col-sm-10 > div.discover:before, body.serieslist > div.container-fluid > div > div.col-sm-10 > div.container:before {
body.authorlist > div.container-fluid > div > div.col-sm-10 > div.container1:before, body.downloadlist > div.container-fluid > div > div.col-sm-10 > div.container1:before, body.catlist > div.container-fluid > div > div.col-sm-10 > div.container1:before, body.langlist > div.container-fluid > div > div.col-sm-10 > div.container1:before, body.me > div.container-fluid > div > div.col-sm-10 > div.discover:before, body.serieslist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
top: 60px;
font-size: 24px;
color: #eee;
@@ -2186,63 +2187,104 @@ body.authorlist > div.container-fluid > div > div.col-sm-10 > div.container:befo
font-weight: 400
}
body.authorlist > div.container-fluid > div > div.col-sm-10 > div.container:before {
body.authorlist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
content: "Authors";
top: 115px;
display: table;
}
@media screen and (max-width: 992px) {
body.authorlist > div.container-fluid > div > div.col-sm-10 > div.container:before {
body.authorlist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
top: 60px;
}
}
body.catlist > div.container-fluid > div > div.col-sm-10 > div.container:before {
@media screen and (max-width: 992px) {
body.downloadlist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
top: 60px;
}
}
body.downloadlist > div.container-fluid > div.row-fluid > div.col-sm-10:before {
font-family: Glyphicons Halflings, serif;
content: "\E026";
font-style: normal;
font-weight: 400;
line-height: 1;
font-size: 6vw;
position: fixed;
left: 240px;
top: 240px;
width: calc(20% - 55px);
text-align: center
}
@media screen and (max-width: 992px) {
body.downloadlist > div.container-fluid > div.row-fluid > div.col-sm-10:before {
top: 180px;
}
}
body.downloadlist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
content: "Downloads";
top: 115px;
display: table;
}
body.catlist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
content: "Categories";
top: 115px;
display: table;
}
@media screen and (max-width: 992px) {
body.catlist > div.container-fluid > div > div.col-sm-10 > div.container:before {
body.catlist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
top: 60px;
}
}
body.serieslist > div.container-fluid > div > div.col-sm-10 > div.container:before {
body.serieslist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
content: "Series";
top: 115px;
display: table;
}
@media screen and (max-width: 992px) {
body.serieslist > div.container-fluid > div > div.col-sm-10 > div.container:before {
body.serieslist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
top: 60px;
}
}
body.ratingslist > div.container-fluid > div > div.col-sm-10 > div.container:before {
body.ratingslist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
content: "File formats";
top: 115px;
display: table;
}
@media screen and (max-width: 992px) {
body.ratingslist > div.container-fluid > div > div.col-sm-10 > div.container:before {
body.ratingslist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
top: 60px;
}
}
body.formatslist > div.container-fluid > div > div.col-sm-10 > div.container:before {
body.formatslist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
content: "File formats";
top: 115px;
display: table;
}
@media screen and (max-width: 992px) {
body.formatslist > div.container-fluid > div > div.col-sm-10 > div.container:before {
body.formatslist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
top: 60px;
}
}
body.langlist > div.container-fluid > div > div.col-sm-10 > div.container:before {
content: "Languages"
body.langlist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
content: "Languages";
top: 115px;
display: table;
}
body.advsearch > div.container-fluid > div > div.col-sm-10 > div.col-md-10.col-lg-6 {
@@ -3268,6 +3310,10 @@ div.btn-group[role=group][aria-label="Download, send to Kindle, reading"] > div.
left: auto !important
}
ul.dropdown-menu.offscreen {
margin: 2px -160px 0
}
div.btn-group[role=group][aria-label="Download, send to Kindle, reading"] .dropdown-menu.offscreen {
position: fixed;
top: 120px;
@@ -3296,6 +3342,7 @@ div.btn-group[role=group][aria-label="Download, send to Kindle, reading"] .dropd
left: 0 !important;
}
#add-to-shelves {
min-height: 48px;
max-height: calc(100% - 120px);
overflow-y: auto;
}
@@ -4332,6 +4379,7 @@ body.advanced_search > div.container-fluid > div.row-fluid > div.col-sm-10 > div
.navbar-right > li > ul.dropdown-menu.offscreen {
right: -10px
}
.login .plexBack, body.login > div.container-fluid > div.row-fluid > div.col-sm-2, body.login > div.navbar.navbar-default.navbar-static-top > div > form {
@@ -4812,8 +4860,14 @@ body.advsearch:not(.blur) > div.container-fluid > div.row-fluid > div.col-sm-10
z-index: 999999999999999999999999999999999999
}
.search #shelf-actions, body.login .home-btn {
display: none
body.search #shelf-actions button#add-to-shelf {
height: 40px;
}
@media screen and (max-width: 767px) {
body.search .discover, body.advsearch .discover {
display: flex;
flex-direction: column;
}
}
body.read:not(.blur) a[href*=readbooks] {
@@ -5134,7 +5188,7 @@ body.login > div.navbar.navbar-default.navbar-static-top > div > div.navbar-head
right: 5px
}
#shelf-actions > .btn-group.open, .downloadBtn.open, .profileDrop[aria-expanded=true] {
body:not(.search) #shelf-actions > .btn-group.open, .downloadBtn.open, .profileDrop[aria-expanded=true] {
pointer-events: none
}
@@ -5151,7 +5205,7 @@ body.login > div.navbar.navbar-default.navbar-static-top > div > div.navbar-head
color: var(--color-primary)
}
#shelf-actions, #shelf-actions > .btn-group, #shelf-actions > .btn-group > .empty-ul {
body:not(.search) #shelf-actions, body:not(.search) #shelf-actions > .btn-group, body:not(.search) #shelf-actions > .btn-group > .empty-ul {
pointer-events: none
}
@@ -6409,7 +6463,7 @@ body.edituser.admin > div.container-fluid > div.row-fluid > div.col-sm-10 > div.
display: none !important
}
.shelforder > .container-fluid > .row-fluid > .col-sm-10 > div.col-sm-6.col-lg-6.col-xs-6 > h2:before, body.advsearch > div.container-fluid > div > div.col-sm-10:before, body.authorlist > div.container-fluid > div > div.col-sm-10 > div.container:before, body.catlist > div.container-fluid > div > div.col-sm-10 > div.container:before, body.langlist > div.container-fluid > div > div.col-sm-10 > div.container:before, body.login .navbar > .container-fluid > .navbar-header > button.navbar-toggle, body.serieslist > div.container-fluid > div > div.col-sm-10 > div.container:before {
.shelforder > .container-fluid > .row-fluid > .col-sm-10 > div.col-sm-6.col-lg-6.col-xs-6 > h2:before, body.advsearch > div.container-fluid > div > div.col-sm-10:before, body.authorlist > div.container-fluid > div > div.col-sm-10 > div.container1:before, body.catlist > div.container-fluid > div > div.col-sm-10 > div.container1:before, body.langlist > div.container-fluid > div > div.col-sm-10 > div.container1:before, body.downloadlist > div.container-fluid > div > div.col-sm-10 > div.container1:before, body.login .navbar > .container-fluid > .navbar-header > button.navbar-toggle, body.serieslist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
display: none
}
@@ -6515,7 +6569,7 @@ body.edituser.admin > div.container-fluid > div.row-fluid > div.col-sm-10 > div.
background-size: 30px
}
body.advanced_search > div.container-fluid > div > div.col-sm-10 > div.col-sm-8:before, body.author:not(.authorlist) .undefined-img:before, body.authorlist > div.container-fluid > div.row-fluid > div.col-sm-10:before, body.catlist > div.container-fluid > div.row-fluid > div.col-sm-10:before, body.langlist > div.container-fluid > div > div.col-sm-10:before, body.ratingslist > div.container-fluid > div > div.col-sm-10:before, body.serieslist > div.container-fluid > div > div.col-sm-10:before, body.shelforder > div.container-fluid > div.row-fluid > div.col-sm-10:before {
body.advanced_search > div.container-fluid > div > div.col-sm-10 > div.col-sm-8:before, body.author:not(.authorlist) .undefined-img:before, body.authorlist > div.container-fluid > div.row-fluid > div.col-sm-10:before, body.catlist > div.container-fluid > div.row-fluid > div.col-sm-10:before, body.downloadlist > div.container-fluid > div.row-fluid > div.col-sm-10:before, body.langlist > div.container-fluid > div > div.col-sm-10:before, body.ratingslist > div.container-fluid > div > div.col-sm-10:before, body.serieslist > div.container-fluid > div > div.col-sm-10:before, body.shelforder > div.container-fluid > div.row-fluid > div.col-sm-10:before {
position: fixed;
top: 62px;
right: 23px;
@@ -6535,7 +6589,7 @@ body.edituser.admin > div.container-fluid > div.row-fluid > div.col-sm-10 > div.
border-top: 1px solid hsla(0, 0%, 78%, .15)
}
body > div.container-fluid > div > div.col-sm-10 > div.container {
body > div.container-fluid > div > div.col-sm-10 > div.container1 {
left: 0;
width: auto;
margin: 0 !important;
@@ -6662,7 +6716,7 @@ body.edituser.admin > div.container-fluid > div.row-fluid > div.col-sm-10 > div.
margin-bottom: 5px
}
body > div.container-fluid > div > div.col-sm-10 > div.container > div > .row {
body > div.container-fluid > div > div.col-sm-10 > div.container1 > div > .row {
padding: 0
}
@@ -7141,12 +7195,11 @@ body.edituser.admin > div.container-fluid > div.row-fluid > div.col-sm-10 > div.
}
body.editbook > div.container-fluid > div.row-fluid > div.col-sm-10 > div.col-sm-3, body.upload > div.container-fluid > div.row-fluid > div.col-sm-10 > div.col-sm-3 {
max-width: 130px;
width: 130px;
height: 180px;
margin: 0;
position: relative;
max-width: unset;
width: 100%;
height: unset;
padding: 15px;
position: absolute
}
body.editbook > div.container-fluid > div.row-fluid > div.col-sm-10 > form > div.col-sm-9, body.upload > div.container-fluid > div.row-fluid > div.col-sm-10 > form > div.col-sm-9 {
@@ -7155,10 +7208,6 @@ body.edituser.admin > div.container-fluid > div.row-fluid > div.col-sm-10 > div.
width: 100%
}
body.editbook > div.container-fluid > div.row-fluid > div.col-sm-10 > form > div.col-sm-9 > .form-group:nth-child(1), body.editbook > div.container-fluid > div.row-fluid > div.col-sm-10 > form > div.col-sm-9 > .form-group:nth-child(2), body.upload > div.container-fluid > div.row-fluid > div.col-sm-10 > form > div.col-sm-9 > .form-group:nth-child(1), body.upload > div.container-fluid > div.row-fluid > div.col-sm-10 > form > div.col-sm-9 > .form-group:nth-child(2) {
padding-left: 120px
}
#deleteButton, body.editbook > div.container-fluid > div.row-fluid > div.col-sm-10 > div.col-sm-3 > div.text-center > #delete, body.upload > div.container-fluid > div.row-fluid > div.col-sm-10 > div.col-sm-3 > div.text-center > #delete {
top: 48px;
height: 42px
@@ -7279,6 +7328,11 @@ body.edituser.admin > div.container-fluid > div.row-fluid > div.col-sm-10 > div.
float: right
}
body.blur #main-nav + #scnd-nav .create-shelf, body.blur #main-nav + .col-sm-2 #scnd-nav .create-shelf {
float: none;
margin: 5px 0 10px -10px;
}
#main-nav + #scnd-nav .nav-head.hidden-xs {
display: list-item !important;
width: 225px
@@ -7429,11 +7483,11 @@ body.edituser.admin > div.container-fluid > div.row-fluid > div.col-sm-10 > div.
text-decoration: none
}
body > div.container-fluid > div > div.col-sm-10 > div.container > div > .row:nth-of-type(even) {
body > div.container-fluid > div > div.col-sm-10 > div.container1 > div > .row:nth-of-type(even) {
background: 0 0
}
body > div.container-fluid > div > div.col-sm-10 > div.container > div > .row {
body > div.container-fluid > div > div.col-sm-10 > div.container1 > div > .row {
border-bottom: 1px solid hsla(0, 0%, 78%, .15)
}
@@ -7588,7 +7642,7 @@ body.formatslist > div.container-fluid > div > div.col-sm-10:before {
}
}
body.publisherlist > div.container-fluid > div > div.col-sm-10 > div.container:before {
body.publisherlist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
content: "Publishers";
top: 115px;
font-size: 24px;
@@ -7596,17 +7650,18 @@ body.publisherlist > div.container-fluid > div > div.col-sm-10 > div.container:b
line-height: 1;
padding-left: 15px;
position: absolute;
display: table;
font-family: Open Sans Bold, Helvetica Neue, Helvetica, Arial, sans-serif;
font-weight: 400
}
@media screen and (max-width: 992px) {
body.publisherlist > div.container-fluid > div > div.col-sm-10 > div.container:before {
body.publisherlist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
top: 60px;
}
}
body.ratingslist > div.container-fluid > div > div.col-sm-10 > div.container:before {
body.ratingslist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
content: "Ratings";
top: 115px;
font-size: 24px;
@@ -7614,23 +7669,24 @@ body.ratingslist > div.container-fluid > div > div.col-sm-10 > div.container:bef
line-height: 1;
padding-left: 15px;
position: absolute;
display: table;
font-family: Open Sans Bold, Helvetica Neue, Helvetica, Arial, sans-serif;
font-weight: 400
}
@media screen and (max-width: 992px) {
body.ratingslist > div.container-fluid > div > div.col-sm-10 > div.container:before {
body.ratingslist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
top: 60px;
}
}
@media screen and (max-width: 768px) {
body.ratingslist > div.container-fluid > div > div.col-sm-10 > div.container:before {
body.ratingslist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
display: none;
}
}
body.formatslist > div.container-fluid > div > div.col-sm-10 > div.container:before {
body.formatslist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
content: "File formats";
top: 115px;
font-size: 24px;
@@ -7643,18 +7699,18 @@ body.formatslist > div.container-fluid > div > div.col-sm-10 > div.container:bef
}
@media screen and (max-width: 992px) {
body.formatslist > div.container-fluid > div > div.col-sm-10 > div.container:before {
body.formatslist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
top: 60px;
}
}
@media screen and (max-width: 768px) {
body.formatslist > div.container-fluid > div > div.col-sm-10 > div.container:before {
body.formatslist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
display: none;
}
}
body.publisherlist > div.container-fluid > div > div.col-sm-10 > div.container > div.col-sm-6 {
body.publisherlist > div.container-fluid > div > div.col-sm-10 > div.container1 > div.col-sm-6 {
width: 100%
}
@@ -7693,7 +7749,7 @@ body.publisherlist > div.container-fluid > div > div.col-sm-10 > div.container >
color: hsla(0, 0%, 100%, .7)
}
body.publisherlist > div.container-fluid > div > div.col-sm-10 > div.container:before {
body.publisherlist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
display: none !important
}
}
@@ -7939,3 +7995,5 @@ div.comments[data-readmore] {
transition: height 300ms;
overflow: hidden
}
.dropdown-menu > .offscreen
+11
View File
@@ -26,3 +26,14 @@ body.serieslist.grid-view div.container-fluid > div > div.col-sm-10::before {
input.datepicker {color: transparent}
input.datepicker:focus {color: transparent}
input.datepicker:focus + input {color: #555}
.col-sm-3.col-lg-2.col-xs-6.book.session {
margin-left: 0;
margin-right: 0;
}
@media only screen and (max-width: 767px) {
.row-fluid > .col-sm-2 {
visibility: hidden;
}
}
+6 -1
View File
@@ -13,7 +13,12 @@
color: #000;
}
.amberTheme {
background: #e8bf5e;
color: #000;
}
.blackTheme {
background: #000;
color: #fff
color: #fff;
}
@@ -0,0 +1,3 @@
<svg width="12" height="13" viewBox="0 0 12 13" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M5.375 7.625V11.875C5.375 12.0408 5.44085 12.1997 5.55806 12.3169C5.67527 12.4342 5.83424 12.5 6 12.5C6.16576 12.5 6.32473 12.4342 6.44194 12.3169C6.55915 12.1997 6.625 12.0408 6.625 11.875V7.625L7.125 7.125H11.375C11.5408 7.125 11.6997 7.05915 11.8169 6.94194C11.9342 6.82473 12 6.66576 12 6.5C12 6.33424 11.9342 6.17527 11.8169 6.05806C11.6997 5.94085 11.5408 5.875 11.375 5.875H7.125L6.625 5.375V1.125C6.625 0.95924 6.55915 0.800269 6.44194 0.683058C6.32473 0.565848 6.16576 0.5 6 0.5C5.83424 0.5 5.67527 0.565848 5.55806 0.683058C5.44085 0.800269 5.375 0.95924 5.375 1.125V5.375L4.875 5.875H0.625C0.45924 5.875 0.300269 5.94085 0.183058 6.05806C0.065848 6.17527 0 6.33424 0 6.5C0 6.66576 0.065848 6.82473 0.183058 6.94194C0.300269 7.05915 0.45924 7.125 0.625 7.125H4.762L5.375 7.625Z" fill="black"/>
</svg>

After

Width:  |  Height:  |  Size: 920 B

@@ -0,0 +1,3 @@
<svg width="12" height="13" viewBox="0 0 12 13" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M6 0.5C5.21207 0.5 4.43185 0.655195 3.7039 0.956723C2.97595 1.25825 2.31451 1.70021 1.75736 2.25736C1.20021 2.81451 0.758251 3.47595 0.456723 4.2039C0.155195 4.93185 0 5.71207 0 6.5C0 7.28793 0.155195 8.06815 0.456723 8.7961C0.758251 9.52405 1.20021 10.1855 1.75736 10.7426C2.31451 11.2998 2.97595 11.7417 3.7039 12.0433C4.43185 12.3448 5.21207 12.5 6 12.5C7.5913 12.5 9.11742 11.8679 10.2426 10.7426C11.3679 9.61742 12 8.0913 12 6.5C12 4.9087 11.3679 3.38258 10.2426 2.25736C9.11742 1.13214 7.5913 0.5 6 0.5ZM5.06 8.9L2.9464 6.7856C2.85273 6.69171 2.80018 6.56446 2.80033 6.43183C2.80048 6.29921 2.85331 6.17207 2.9472 6.0784C3.04109 5.98473 3.16834 5.93218 3.30097 5.93233C3.43359 5.93248 3.56073 5.98531 3.6544 6.0792L5.3112 7.7368L8.3464 4.7008C8.44109 4.6109 8.56715 4.56153 8.69771 4.56322C8.82827 4.56492 8.95301 4.61754 9.04534 4.70986C9.13766 4.80219 9.19028 4.92693 9.19198 5.05749C9.19367 5.18805 9.1443 5.31411 9.0544 5.4088L5.5624 8.9H5.06Z" fill="#FBFBFE"/>
</svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

@@ -0,0 +1,6 @@
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" height="40" width="40">
<path d="M9 3.5a1.5 1.5 0 0 0-3-.001v7.95C6 12.83 7.12 14 8.5 14s2.5-1.17 2.5-2.55V5.5a.5.5 0 0 1 1 0v6.03C11.955 13.427 10.405 15 8.5 15S5.044 13.426 5 11.53V3.5a2.5 2.5 0 0 1 5 0v7.003a1.5 1.5 0 0 1-3-.003v-5a.5.5 0 0 1 1 0v5a.5.5 0 0 0 1 0Z"/>
</svg>

After

Width:  |  Height:  |  Size: 552 B

@@ -0,0 +1,7 @@
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" height="40" width="40">
<path d="M8.156 12.5a.99.99 0 0 0 .707-.294l.523-2.574L10.5 8.499l1.058-1.04 2.65-.601a.996.996 0 0 0 0-1.414l-3.657-3.658a.996.996 0 0 0-1.414 0l-.523 2.576L7.5 5.499 6.442 6.535l-2.65.6a.996.996 0 0 0 0 1.413l3.657 3.658a.999.999 0 0 0 .707.295z"/>
<path d="M9.842.996c-.386 0-.77.146-1.06.44a.5.5 0 0 0-.136.251l-.492 2.43-1.008 1.03-.953.933-2.511.566a.5.5 0 0 0-.243.133 1.505 1.505 0 0 0-.002 2.123l1.477 1.477-2.768 2.767a.5.5 0 0 0 0 .707.5.5 0 0 0 .708 0l2.767-2.767 1.475 1.474a1.494 1.494 0 0 0 2.123-.002.5.5 0 0 0 .135-.254l.492-2.427 1.008-1.024.953-.937 2.511-.57a.5.5 0 0 0 .243-.132c.586-.58.583-1.543.002-2.125l-3.659-3.656A1.501 1.501 0 0 0 9.842.996Zm.05 1.025a.394.394 0 0 1 .305.12l3.658 3.657c.18.18.141.432.002.627l-2.41.545a.5.5 0 0 0-.24.131L10.15 8.142a.5.5 0 0 0-.007.006L9.029 9.283a.5.5 0 0 0-.133.25l-.48 2.36c-.082.053-.165.109-.26.109a.492.492 0 0 1-.353-.149L4.145 8.195c-.18-.18-.141-.432-.002-.627l2.41-.545a.5.5 0 0 0 .238-.13L7.85 5.857a.5.5 0 0 0 .007-.008l1.114-1.138a.5.5 0 0 0 .133-.25l.472-2.323a.619.619 0 0 1 .317-.117Z"/>
</svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

@@ -0,0 +1,6 @@
<svg width="18" height="19" viewBox="0 0 18 19" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M12.2 3.09C12.28 3.01 12.43 3 12.43 3C12.48 3 12.58 3.02 12.66 3.1L14.45 4.89C14.58 5.02 14.58 5.22 14.45 5.35L11.7713 8.02872L9.51628 5.77372L12.2 3.09ZM13.2658 5.12L11.7713 6.6145L10.9305 5.77372L12.425 4.27921L13.2658 5.12Z" fill="#FBFBFE"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M5.98 9.32L8.23 11.57L10.7106 9.08938L8.45562 6.83438L5.98 9.31V9.32ZM8.23 10.1558L9.29641 9.08938L8.45562 8.24859L7.38921 9.315L8.23 10.1558Z" fill="#FBFBFE"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M10.1526 13.1816L16.2125 7.1217C16.7576 6.58919 17.05 5.8707 17.05 5.12C17.05 4.36931 16.7576 3.65084 16.2126 3.11834L14.4317 1.33747C13.8992 0.79242 13.1807 0.5 12.43 0.5C11.6643 0.5 10.9529 0.812929 10.4329 1.33289L3.68289 8.08289C3.04127 8.72452 3.00459 9.75075 3.57288 10.4363L1.29187 12.7239C1.09186 12.9245 0.990263 13.1957 1.0007 13.4685L1 14.5C0.447715 14.5 0 14.9477 0 15.5V17.5C0 18.0523 0.447715 18.5 1 18.5H16C16.5523 18.5 17 18.0523 17 17.5V15.5C17 14.9477 16.5523 14.5 16 14.5H10.2325C9.83594 14.5 9.39953 13.9347 10.1526 13.1816ZM4.39 9.85L4.9807 10.4407L2.39762 13.0312H6.63877L7.10501 12.565L7.57125 13.0312H8.88875L15.51 6.41C15.86 6.07 16.05 5.61 16.05 5.12C16.05 4.63 15.86 4.17 15.51 3.83L13.72 2.04C13.38 1.69 12.92 1.5 12.43 1.5C11.94 1.5 11.48 1.7 11.14 2.04L4.39 8.79C4.1 9.08 4.1 9.56 4.39 9.85ZM16 17.5V15.5H1V17.5H16Z" fill="#FBFBFE"/>
<path d="M15.1616 6.05136L15.1616 6.05132L15.1564 6.05645L8.40645 12.8064C8.35915 12.8537 8.29589 12.88 8.23 12.88C8.16411 12.88 8.10085 12.8537 8.05355 12.8064L7.45857 12.2115L7.10501 11.8579L6.75146 12.2115L6.03289 12.93H3.20465L5.33477 10.7937L5.6873 10.4402L5.33426 10.0871L4.74355 9.49645C4.64882 9.40171 4.64882 9.23829 4.74355 9.14355L11.4936 2.39355C11.7436 2.14354 12.0779 2 12.43 2C12.7883 2 13.1179 2.13776 13.3614 2.38839L13.3613 2.38843L13.3664 2.39355L15.1564 4.18355L15.1564 4.18359L15.1616 4.18864C15.4122 4.43211 15.55 4.76166 15.55 5.12C15.55 5.47834 15.4122 5.80789 15.1616 6.05136ZM7.87645 11.9236L8.23 12.2771L8.58355 11.9236L11.0642 9.44293L11.4177 9.08938L11.0642 8.73582L8.80918 6.48082L8.45562 6.12727L8.10207 6.48082L5.62645 8.95645L5.48 9.10289V9.31V9.32V9.52711L5.62645 9.67355L7.87645 11.9236ZM11.4177 8.38227L11.7713 8.73582L12.1248 8.38227L14.8036 5.70355C15.1288 5.37829 15.1288 4.86171 14.8036 4.53645L13.0136 2.74645C12.8186 2.55146 12.5792 2.5 12.43 2.5H12.4134L12.3967 2.50111L12.43 3C12.3967 2.50111 12.3966 2.50112 12.3965 2.50112L12.3963 2.50114L12.3957 2.50117L12.3947 2.50125L12.3924 2.50142L12.387 2.50184L12.3732 2.50311C12.3628 2.50416 12.3498 2.50567 12.3346 2.50784C12.3049 2.51208 12.2642 2.51925 12.2178 2.53146C12.1396 2.55202 11.9797 2.60317 11.8464 2.73645L9.16273 5.42016L8.80918 5.77372L9.16273 6.12727L11.4177 8.38227ZM1.5 16H15.5V17H1.5V16Z" stroke="#15141A"/>
</svg>

After

Width:  |  Height:  |  Size: 2.9 KiB

@@ -0,0 +1,3 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M12 2.75H12.5V2.25V1V0.5H12H10.358C9.91165 0.5 9.47731 0.625661 9.09989 0.860442L9.09886 0.861087L8 1.54837L6.89997 0.860979L6.89911 0.860443C6.5218 0.625734 6.08748 0.5 5.642 0.5H4H3.5V1V2.25V2.75H4H5.642C5.66478 2.75 5.6885 2.75641 5.71008 2.76968C5.71023 2.76977 5.71038 2.76986 5.71053 2.76995L6.817 3.461C6.81704 3.46103 6.81709 3.46105 6.81713 3.46108C6.81713 3.46108 6.81713 3.46108 6.81714 3.46109C6.8552 3.48494 6.876 3.52285 6.876 3.567V8V12.433C6.876 12.4771 6.85523 12.515 6.81722 12.5389C6.81715 12.5389 6.81707 12.539 6.817 12.539L5.70953 13.23C5.70941 13.2301 5.70929 13.2302 5.70917 13.2303C5.68723 13.2438 5.6644 13.25 5.641 13.25H4H3.5V13.75V15V15.5H4H5.642C6.08835 15.5 6.52269 15.3743 6.90011 15.1396L6.90086 15.1391L8 14.4526L9.10003 15.14L9.10089 15.1406C9.47831 15.3753 9.91265 15.501 10.359 15.501H12H12.5V15.001V13.751V13.251H12H10.358C10.3352 13.251 10.3115 13.2446 10.2899 13.2313C10.2897 13.2312 10.2896 13.2311 10.2895 13.231L9.183 12.54C9.18298 12.54 9.18295 12.54 9.18293 12.54C9.18291 12.5399 9.18288 12.5399 9.18286 12.5399C9.14615 12.5169 9.125 12.4797 9.125 12.434V8V3.567C9.125 3.52266 9.14603 3.48441 9.18364 3.4606C9.18377 3.46052 9.1839 3.46043 9.18404 3.46035L10.2895 2.76995C10.2896 2.76985 10.2898 2.76975 10.2899 2.76966C10.3119 2.75619 10.3346 2.75 10.358 2.75H12Z" fill="black" stroke="white"/>
</svg>

After

Width:  |  Height:  |  Size: 1.4 KiB

@@ -0,0 +1,4 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M0.0189877 13.6645L0.612989 10.4635C0.687989 10.0545 0.884989 9.6805 1.18099 9.3825L9.98199 0.5805C10.756 -0.1925 12.015 -0.1945 12.792 0.5805L14.42 2.2085C15.194 2.9835 15.194 4.2435 14.42 5.0185L5.61599 13.8215C5.31999 14.1165 4.94599 14.3125 4.53799 14.3875L1.33599 14.9815C1.26599 14.9935 1.19799 15.0005 1.12999 15.0005C0.832989 15.0005 0.544988 14.8835 0.330988 14.6695C0.0679874 14.4055 -0.0490122 14.0305 0.0189877 13.6645Z" fill="white"/>
<path d="M0.0189877 13.6645L0.612989 10.4635C0.687989 10.0545 0.884989 9.6805 1.18099 9.3825L9.98199 0.5805C10.756 -0.1925 12.015 -0.1945 12.792 0.5805L14.42 2.2085C15.194 2.9835 15.194 4.2435 14.42 5.0185L5.61599 13.8215C5.31999 14.1165 4.94599 14.3125 4.53799 14.3875L1.33599 14.9815C1.26599 14.9935 1.19799 15.0005 1.12999 15.0005C0.832989 15.0005 0.544988 14.8835 0.330988 14.6695C0.0679874 14.4055 -0.0490122 14.0305 0.0189877 13.6645ZM12.472 5.1965L13.632 4.0365L13.631 3.1885L11.811 1.3675L10.963 1.3685L9.80299 2.5285L12.472 5.1965ZM4.31099 13.1585C4.47099 13.1285 4.61799 13.0515 4.73399 12.9345L11.587 6.0815L8.91899 3.4135L2.06599 10.2655C1.94899 10.3835 1.87199 10.5305 1.84099 10.6915L1.36699 13.2485L1.75199 13.6335L4.31099 13.1585Z" fill="black"/>
</svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

@@ -0,0 +1,8 @@
<svg width="29" height="32" viewBox="0 0 29 32" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M28 16.75C28.2761 16.75 28.5 16.5261 28.5 16.25V15C28.5 14.7239 28.2761 14.5 28 14.5H26.358C25.9117 14.5 25.4773 14.6257 25.0999 14.8604L25.0989 14.8611L24 15.5484L22.9 14.861L22.8991 14.8604C22.5218 14.6257 22.0875 14.5 21.642 14.5H20C19.7239 14.5 19.5 14.7239 19.5 15V16.25C19.5 16.5261 19.7239 16.75 20 16.75H21.642C21.6648 16.75 21.6885 16.7564 21.7101 16.7697C21.7102 16.7698 21.7104 16.7699 21.7105 16.77L22.817 17.461C22.817 17.461 22.8171 17.4611 22.8171 17.4611C22.8171 17.4611 22.8171 17.4611 22.8171 17.4611C22.8552 17.4849 22.876 17.5229 22.876 17.567V22.625V27.683C22.876 27.7271 22.8552 27.765 22.8172 27.7889C22.8171 27.7889 22.8171 27.789 22.817 27.789L21.7095 28.48C21.7094 28.4801 21.7093 28.4802 21.7092 28.4803C21.6872 28.4938 21.6644 28.5 21.641 28.5H20C19.7239 28.5 19.5 28.7239 19.5 29V30.25C19.5 30.5261 19.7239 30.75 20 30.75H21.642C22.0883 30.75 22.5227 30.6243 22.9001 30.3896L22.9009 30.3891L24 29.7026L25.1 30.39L25.1009 30.3906C25.4783 30.6253 25.9127 30.751 26.359 30.751H28C28.2761 30.751 28.5 30.5271 28.5 30.251V29.001C28.5 28.7249 28.2761 28.501 28 28.501H26.358C26.3352 28.501 26.3115 28.4946 26.2899 28.4813C26.2897 28.4812 26.2896 28.4811 26.2895 28.481L25.183 27.79C25.183 27.79 25.183 27.79 25.1829 27.79C25.1829 27.7899 25.1829 27.7899 25.1829 27.7899C25.1462 27.7669 25.125 27.7297 25.125 27.684V22.625V17.567C25.125 17.5227 25.146 17.4844 25.1836 17.4606C25.1838 17.4605 25.1839 17.4604 25.184 17.4603L26.2895 16.77C26.2896 16.7699 26.2898 16.7698 26.2899 16.7697C26.3119 16.7562 26.3346 16.75 26.358 16.75H28Z" fill="black" stroke="#FBFBFE" stroke-linejoin="round"/>
<path d="M24.625 17.567C24.625 17.35 24.735 17.152 24.918 17.037L26.026 16.345C26.126 16.283 26.24 16.25 26.358 16.25H28V15H26.358C26.006 15 25.663 15.099 25.364 15.285L24.256 15.978C24.161 16.037 24.081 16.113 24 16.187C23.918 16.113 23.839 16.037 23.744 15.978L22.635 15.285C22.336 15.099 21.993 15 21.642 15H20V16.25H21.642C21.759 16.25 21.874 16.283 21.974 16.345L23.082 17.037C23.266 17.152 23.376 17.35 23.376 17.567V22.625V27.683C23.376 27.9 23.266 28.098 23.082 28.213L21.973 28.905C21.873 28.967 21.759 29 21.641 29H20V30.25H21.642C21.994 30.25 22.337 30.151 22.636 29.965L23.744 29.273C23.84 29.213 23.919 29.137 24 29.064C24.081 29.137 24.161 29.213 24.256 29.273L25.365 29.966C25.664 30.152 26.007 30.251 26.359 30.251H28V29.001H26.358C26.241 29.001 26.126 28.968 26.026 28.906L24.918 28.214C24.734 28.099 24.625 27.901 24.625 27.684V22.625V17.567Z" fill="black"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M12.2 2.59C12.28 2.51 12.43 2.5 12.43 2.5C12.48 2.5 12.58 2.52 12.66 2.6L14.45 4.39C14.58 4.52 14.58 4.72 14.45 4.85L11.7713 7.52872L9.51628 5.27372L12.2 2.59ZM13.2658 4.62L11.7713 6.1145L10.9305 5.27372L12.425 3.77921L13.2658 4.62Z" fill="#FBFBFE"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M5.98 8.82L8.23 11.07L10.7106 8.58938L8.45562 6.33438L5.98 8.81V8.82ZM8.23 9.65579L9.29641 8.58938L8.45562 7.74859L7.38921 8.815L8.23 9.65579Z" fill="#FBFBFE"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M10.1526 12.6816L16.2125 6.6217C16.7576 6.08919 17.05 5.3707 17.05 4.62C17.05 3.86931 16.7576 3.15084 16.2126 2.61834L14.4317 0.837474C13.8992 0.29242 13.1807 0 12.43 0C11.6643 0 10.9529 0.312929 10.4329 0.832893L3.68289 7.58289C3.04127 8.22452 3.00459 9.25075 3.57288 9.93634L1.29187 12.2239C1.09186 12.4245 0.990263 12.6957 1.0007 12.9685L1 14C0.447715 14 0 14.4477 0 15V17C0 17.5523 0.447715 18 1 18H16C16.5523 18 17 17.5523 17 17V15C17 14.4477 16.5523 14 16 14H10.2325C9.83594 14 9.39953 13.4347 10.1526 12.6816ZM4.39 9.35L4.9807 9.9407L2.39762 12.5312H6.63877L7.10501 12.065L7.57125 12.5312H8.88875L15.51 5.91C15.86 5.57 16.05 5.11 16.05 4.62C16.05 4.13 15.86 3.67 15.51 3.33L13.72 1.54C13.38 1.19 12.92 1 12.43 1C11.94 1 11.48 1.2 11.14 1.54L4.39 8.29C4.1 8.58 4.1 9.06 4.39 9.35ZM16 17V15H1V17H16Z" fill="#FBFBFE"/>
<path d="M15.1616 5.55136L15.1616 5.55132L15.1564 5.55645L8.40645 12.3064C8.35915 12.3537 8.29589 12.38 8.23 12.38C8.16411 12.38 8.10085 12.3537 8.05355 12.3064L7.45857 11.7115L7.10501 11.3579L6.75146 11.7115L6.03289 12.43H3.20465L5.33477 10.2937L5.6873 9.94019L5.33426 9.58715L4.74355 8.99645C4.64882 8.90171 4.64882 8.73829 4.74355 8.64355L11.4936 1.89355C11.7436 1.64354 12.0779 1.5 12.43 1.5C12.7883 1.5 13.1179 1.63776 13.3614 1.88839L13.3613 1.88843L13.3664 1.89355L15.1564 3.68355L15.1564 3.68359L15.1616 3.68864C15.4122 3.93211 15.55 4.26166 15.55 4.62C15.55 4.97834 15.4122 5.30789 15.1616 5.55136ZM5.48 8.82V9.02711L5.62645 9.17355L7.87645 11.4236L8.23 11.7771L8.58355 11.4236L11.0642 8.94293L11.4177 8.58938L11.0642 8.23582L8.80918 5.98082L8.45562 5.62727L8.10207 5.98082L5.62645 8.45645L5.48 8.60289V8.81V8.82ZM11.4177 7.88227L11.7713 8.23582L12.1248 7.88227L14.8036 5.20355C15.1288 4.87829 15.1288 4.36171 14.8036 4.03645L13.0136 2.24645C12.8186 2.05146 12.5792 2 12.43 2H12.4134L12.3967 2.00111L12.43 2.5C12.3967 2.00111 12.3966 2.00112 12.3965 2.00112L12.3963 2.00114L12.3957 2.00117L12.3947 2.00125L12.3924 2.00142L12.387 2.00184L12.3732 2.00311C12.3628 2.00416 12.3498 2.00567 12.3346 2.00784C12.3049 2.01208 12.2642 2.01925 12.2178 2.03146C12.1396 2.05202 11.9797 2.10317 11.8464 2.23645L9.16273 4.92016L8.80918 5.27372L9.16273 5.62727L11.4177 7.88227ZM1.5 16.5V15.5H15.5V16.5H1.5Z" stroke="#15141A"/>
</svg>

After

Width:  |  Height:  |  Size: 5.3 KiB

@@ -0,0 +1,5 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd"
d="M11 3H13.6C14 3 14.3 3.3 14.3 3.6C14.3 3.9 14 4.2 13.7 4.2H13.3V14C13.3 15.1 12.4 16 11.3 16H4.80005C3.70005 16 2.80005 15.1 2.80005 14V4.2H2.40005C2.00005 4.2 1.80005 4 1.80005 3.6C1.80005 3.2 2.00005 3 2.40005 3H5.00005V2C5.00005 0.9 5.90005 0 7.00005 0H9.00005C10.1 0 11 0.9 11 2V3ZM6.90005 1.2L6.30005 1.8V3H9.80005V1.8L9.20005 1.2H6.90005ZM11.4 14.7L12 14.1V4.2H4.00005V14.1L4.60005 14.7H11.4ZM7.00005 12.4C7.00005 12.7 6.70005 13 6.40005 13C6.10005 13 5.80005 12.7 5.80005 12.4V7.6C5.70005 7.3 6.00005 7 6.40005 7C6.80005 7 7.00005 7.3 7.00005 7.6V12.4ZM10.2001 12.4C10.2001 12.7 9.90006 13 9.60006 13C9.30006 13 9.00006 12.7 9.00006 12.4V7.6C9.00006 7.3 9.30006 7 9.60006 7C9.90006 7 10.2001 7.3 10.2001 7.6V12.4Z"
fill="black" />
</svg>

After

Width:  |  Height:  |  Size: 909 B

@@ -1,4 +1,3 @@
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><path d="M8 12a1 1 0 0 1-.707-.293l-5-5a1 1 0 0 1 1.414-1.414L8 9.586l4.293-4.293a1 1 0 0 1 1.414 1.414l-5 5A1 1 0 0 1 8 12z"></path></svg>
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M10.999 8.352L5.534 13.818C5.41551 13.9303 5.25786 13.9918 5.09466 13.9895C4.93146 13.9872 4.77561 13.9212 4.66033 13.8057C4.54505 13.6902 4.47945 13.5342 4.47752 13.3709C4.47559 13.2077 4.53748 13.0502 4.65 12.932L9.585 7.998L4.651 3.067C4.53862 2.94864 4.47691 2.79106 4.47903 2.62786C4.48114 2.46466 4.54692 2.30874 4.66233 2.19333C4.77774 2.07792 4.93366 2.01215 5.09686 2.01003C5.26006 2.00792 5.41763 2.06962 5.536 2.182L11 7.647L10.999 8.352Z" fill="black"/>
</svg>

Before

Width:  |  Height:  |  Size: 434 B

After

Width:  |  Height:  |  Size: 578 B

@@ -1,4 +1,3 @@
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><path d="M13 11a1 1 0 0 1-.707-.293L8 6.414l-4.293 4.293a1 1 0 0 1-1.414-1.414l5-5a1 1 0 0 1 1.414 0l5 5A1 1 0 0 1 13 11z"></path></svg>
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M5.001 8.352L10.466 13.818C10.5845 13.9303 10.7421 13.9918 10.9053 13.9895C11.0685 13.9872 11.2244 13.9212 11.3397 13.8057C11.4549 13.6902 11.5205 13.5342 11.5225 13.3709C11.5244 13.2077 11.4625 13.0502 11.35 12.932L6.416 7.999L11.349 3.067C11.4614 2.94864 11.5231 2.79106 11.521 2.62786C11.5189 2.46466 11.4531 2.30874 11.3377 2.19333C11.2223 2.07792 11.0663 2.01215 10.9031 2.01003C10.7399 2.00792 10.5824 2.06962 10.464 2.182L5 7.647L5.001 8.352Z" fill="black"/>
</svg>

Before

Width:  |  Height:  |  Size: 431 B

After

Width:  |  Height:  |  Size: 578 B

@@ -0,0 +1,3 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M16.969 10.059C17.262 9.766 17.737 9.766 18.03 10.059C18.323 10.352 18.323 10.827 18.03 11.12L12.15 17H11.35L5.46896 11.12C5.17596 10.827 5.17596 10.352 5.46896 10.059C5.76196 9.766 6.23696 9.766 6.52996 10.059L11 14.529V2.75C11 2.336 11.336 2 11.75 2C12.164 2 12.5 2.336 12.499 2.75V14.529L16.969 10.059ZM4.98193 19.7L5.78193 20.5H17.7169L18.5169 19.7V17.75C18.5169 17.336 18.8529 17 19.2669 17C19.6809 17 20.0169 17.336 20.0169 17.75V19.5C20.0169 20.881 18.8979 22 17.5169 22H5.98193C4.60093 22 3.48193 20.881 3.48193 19.5V17.75C3.48193 17.336 3.81793 17 4.23193 17C4.64593 17 4.98193 17.336 4.98193 17.75V19.7Z" fill="black"/>
</svg>

After

Width:  |  Height:  |  Size: 782 B

@@ -1,24 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" height="16" width="16"
fill="rgba(255,255,255,1)" style="animation:spinLoadingIcon 1s steps(12,end)
infinite"><style>@keyframes
spinLoadingIcon{to{transform:rotate(360deg)}}</style><path
d="M7 3V1s0-1 1-1 1 1 1 1v2s0 1-1 1-1-1-1-1z"/><path d="M4.63
4.1l-1-1.73S3.13 1.5 4 1c.87-.5 1.37.37 1.37.37l1 1.73s.5.87-.37
1.37c-.87.57-1.37-.37-1.37-.37z" fill-opacity=".93"/><path
d="M3.1 6.37l-1.73-1S.5 4.87 1 4c.5-.87 1.37-.37 1.37-.37l1.73 1s.87.5.37
1.37c-.5.87-1.37.37-1.37.37z" fill-opacity=".86"/><path d="M3
9H1S0 9 0 8s1-1 1-1h2s1 0 1 1-1 1-1 1z" fill-opacity=".79"/><path d="M4.1 11.37l-1.73 1S1.5 12.87 1
12c-.5-.87.37-1.37.37-1.37l1.73-1s.87-.5 1.37.37c.5.87-.37 1.37-.37 1.37z"
fill-opacity=".72"/><path d="M3.63 13.56l1-1.73s.5-.87
1.37-.37c.87.5.37 1.37.37 1.37l-1 1.73s-.5.87-1.37.37c-.87-.5-.37-1.37-.37-1.37z"
fill-opacity=".65"/><path d="M7 15v-2s0-1 1-1 1 1 1 1v2s0 1-1
1-1-1-1-1z" fill-opacity=".58"/><path d="M10.63
14.56l-1-1.73s-.5-.87.37-1.37c.87-.5 1.37.37 1.37.37l1 1.73s.5.87-.37
1.37c-.87.5-1.37-.37-1.37-.37z" fill-opacity=".51"/><path
d="M13.56 12.37l-1.73-1s-.87-.5-.37-1.37c.5-.87 1.37-.37 1.37-.37l1.73 1s.87.5.37
1.37c-.5.87-1.37.37-1.37.37z" fill-opacity=".44"/><path d="M15
9h-2s-1 0-1-1 1-1 1-1h2s1 0 1 1-1 1-1 1z" fill-opacity=".37"/><path d="M14.56 5.37l-1.73
1s-.87.5-1.37-.37c-.5-.87.37-1.37.37-1.37l1.73-1s.87-.5 1.37.37c.5.87-.37 1.37-.37
1.37z" fill-opacity=".3"/><path d="M9.64 3.1l.98-1.66s.5-.874
1.37-.37c.87.5.37 1.37.37 1.37l-1 1.73s-.5.87-1.37.37c-.87-.5-.37-1.37-.37-1.37z"
fill-opacity=".23"/></svg>

Before

Width:  |  Height:  |  Size: 1.5 KiB

@@ -1,15 +1,3 @@
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16
16">
<path
d="M8 16a8 8 0 1 1 8-8 8.009 8.009 0 0 1-8 8zM8 2a6 6 0 1 0 6 6 6.006 6.006 0 0 0-6-6z">
</path>
<path
d="M8 7a1 1 0 0 0-1 1v3a1 1 0 0 0 2 0V8a1 1 0 0 0-1-1z">
</path>
<circle
cx="8" cy="5" r="1.188">
</circle>
</svg>
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M8 1.5C4.41015 1.5 1.5 4.41015 1.5 8C1.5 11.5899 4.41015 14.5 8 14.5C11.5899 14.5 14.5 11.5899 14.5 8C14.5 4.41015 11.5899 1.5 8 1.5ZM0 8C0 3.58172 3.58172 0 8 0C12.4183 0 16 3.58172 16 8C16 12.4183 12.4183 16 8 16C3.58172 16 0 12.4183 0 8ZM8.75 4V5.5H7.25V4H8.75ZM8.75 12V7H7.25V12H8.75Z" fill="black"/>
</svg>

Before

Width:  |  Height:  |  Size: 530 B

After

Width:  |  Height:  |  Size: 417 B

@@ -1 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><path d="M13 13c-.3 0-.5-.1-.7-.3L8 8.4l-4.3 4.3c-.9.9-2.3-.5-1.4-1.4l5-5c.4-.4 1-.4 1.4 0l5 5c.6.6.2 1.7-.7 1.7zm0-11H3C1.7 2 1.7 4 3 4h10c1.3 0 1.3-2 0-2z"/></svg>
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M14 3.5H2V5H14V3.5ZM8 8.811L12.939 13.75L14.001 12.689L8.531 7.219C8.238 6.926 7.763 6.926 7.47 7.219L2 12.689L3.061 13.75L8 8.811Z" fill="black"/>
</svg>

Before

Width:  |  Height:  |  Size: 228 B

After

Width:  |  Height:  |  Size: 260 B

@@ -1 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" height="16" width="16"><path d="M15 3.7V13c0 1.5-1.53 3-3 3H7.13c-.72 0-1.63-.5-2.13-1l-5-5s.84-1 .87-1c.13-.1.33-.2.53-.2.1 0 .3.1.4.2L4 10.6V2.7c0-.6.4-1 1-1s1 .4 1 1v4.6h1V1c0-.6.4-1 1-1s1 .4 1 1v6.3h1V1.7c0-.6.4-1 1-1s1 .4 1 1v5.7h1V3.7c0-.6.4-1 1-1s1 .4 1 1z"/></svg>
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M7.75 2.125C7.75 1.78021 8.03021 1.5 8.375 1.5C8.71979 1.5 9 1.78021 9 2.125V3.125V8H10.5V3.125C10.5 2.78021 10.7802 2.5 11.125 2.5C11.4698 2.5 11.75 2.78021 11.75 3.125V4.625V8H13.25V4.625C13.25 4.28021 13.5302 4 13.875 4C14.2198 4 14.5 4.28021 14.5 4.625V12.0188L13.3802 13.6628C13.2954 13.7872 13.25 13.9344 13.25 14.085V16H14.75V14.3162L15.8698 12.6722C15.9546 12.5478 16 12.4006 16 12.25V4.625C16 3.45179 15.0482 2.5 13.875 2.5C13.6346 2.5 13.4035 2.53996 13.188 2.6136C12.959 1.68724 12.1219 1 11.125 1C10.8235 1 10.5366 1.06286 10.2768 1.17618C9.9281 0.478968 9.20726 0 8.375 0C7.54274 0 6.8219 0.478968 6.47323 1.17618C6.21337 1.06286 5.9265 1 5.625 1C4.45179 1 3.5 1.95179 3.5 3.125V7.25317C2.66504 6.54282 1.41035 6.58199 0.621672 7.37067C-0.208221 8.20056 -0.208221 9.54644 0.621672 10.3763L0.62188 10.3765L5.499 15.2498V16H6.999V14.939C6.999 14.74 6.9199 14.5491 6.77912 14.4085L1.68233 9.31567C1.43823 9.07156 1.43823 8.67544 1.68233 8.43133C1.92644 8.18722 2.32257 8.18722 2.56667 8.43133L3.71967 9.58433C3.93417 9.79883 4.25676 9.863 4.53701 9.74691C4.81727 9.63082 5 9.35735 5 9.054V3.125C5 2.78021 5.28022 2.5 5.625 2.5C5.96921 2.5 6.24906 2.77927 6.25 3.12326V8H7.75L7.75 3.125L7.75 3.12178V2.125Z" fill="black"/>
</svg>

Before

Width:  |  Height:  |  Size: 312 B

After

Width:  |  Height:  |  Size: 1.3 KiB

Some files were not shown because too many files have changed in this diff Show More