├── .all-contributorsrc ├── .github └── workflows │ ├── build-docker-image.yml │ ├── check-conventional-commits.yml │ ├── docker-publish.yml │ └── release-please.yml ├── .gitignore ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── bragibooks_proj ├── __init__.py ├── celery.py ├── settings.py ├── urls.py └── wsgi.py ├── docker ├── .dockerignore ├── Dockerfile └── entrypoint.sh ├── importer ├── __init__.py ├── admin.py ├── apps.py ├── context_processors.py ├── forms.py ├── migrations │ ├── 0001_initial.py │ ├── 0002_setting.py │ ├── 0003_delete_genre.py │ ├── 0004_book_status.py │ ├── 0005_cover_image_link.py │ └── __init__.py ├── models.py ├── static │ └── images │ │ ├── cover_not_available.jpg │ │ ├── favicon.ico │ │ └── logo-small-black.svg ├── tasks.py ├── templates │ ├── base.html │ ├── book_list.html │ ├── book_tabs.html │ ├── book_tabs.js │ ├── directory_contents.html │ ├── importer.html │ ├── importer.js │ ├── match.html │ ├── match.js │ └── setting.html ├── templatetags │ └── directory_explorer_tags.py ├── tests.py ├── urls.py ├── version.py └── views.py ├── manage.py ├── renovate.json ├── requirements.txt └── utils ├── __init__.py ├── merge.py ├── region_tools.py └── search_tools.py /.all-contributorsrc: -------------------------------------------------------------------------------- 1 | { 2 | "files": [ 3 | "README.md" 4 | ], 5 | "imageSize": 100, 6 | "commit": false, 7 | "commitConvention": "angular", 8 | "contributors": [ 9 | { 10 | "login": "AceTugboat", 11 | "name": "Koby Huckabee", 12 | "avatar_url": "https://avatars.githubusercontent.com/u/14910857?v=4", 13 | "profile": "https://koby.huckabee.dev", 14 | "contributions": [ 15 | "code", 16 | "ideas", 17 | "doc" 18 | ] 19 | }, 20 | { 21 | "login": "sandreas", 22 | "name": "Andreas", 23 | "avatar_url": "https://avatars.githubusercontent.com/u/2050604?v=4", 24 | "profile": "https://pilabor.com", 25 | "contributions": [ 26 | "tool" 27 | ] 28 | } 29 | ], 30 | "contributorsPerLine": 7, 31 | "skipCi": true, 32 | "repoType": "github", 33 | "repoHost": "https://github.com", 34 | "projectName": "bragibooks", 35 | "projectOwner": "djdembeck" 36 | } 37 | -------------------------------------------------------------------------------- /.github/workflows/build-docker-image.yml: -------------------------------------------------------------------------------- 1 | name: Docker Image CI 2 | 3 | on: 4 | pull_request: 5 | branches: [ main ] 6 | 7 | jobs: 8 | 9 | build: 10 | 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - uses: actions/checkout@v4 15 | - name: Build the Docker image 16 | run: docker build . --file docker/Dockerfile --tag my-image-name:$(date +%s) 17 | -------------------------------------------------------------------------------- /.github/workflows/check-conventional-commits.yml: -------------------------------------------------------------------------------- 1 | name: Conventional Commits 2 | 3 | on: 4 | pull_request: 5 | branches: [ main, develop ] 6 | 7 | jobs: 8 | build: 9 | name: Conventional Commits 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v4 13 | - uses: webiny/action-conventional-commits@v1.3.0 -------------------------------------------------------------------------------- /.github/workflows/docker-publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish Docker image 2 | 3 | on: 4 | workflow_dispatch: 5 | push: 6 | branches: 7 | - main 8 | - develop 9 | # Publish semver tags as releases. 10 | tags: ['v*.*.*'] 11 | 12 | jobs: 13 | push_to_registries: 14 | name: Push Docker image to multiple registries 15 | runs-on: ubuntu-latest 16 | permissions: 17 | packages: write 18 | contents: read 19 | steps: 20 | - name: Check out the repo 21 | uses: actions/checkout@v4 22 | 23 | - name: Log in to Docker Hub 24 | uses: docker/login-action@9780b0c442fbb1117ed29e0efdff1e18412f7567 25 | with: 26 | username: ${{ secrets.DOCKER_USERNAME }} 27 | password: ${{ secrets.DOCKER_PASSWORD }} 28 | 29 | - name: Log in to the Container registry 30 | uses: docker/login-action@9780b0c442fbb1117ed29e0efdff1e18412f7567 31 | with: 32 | registry: ghcr.io 33 | username: ${{ github.actor }} 34 | password: ${{ secrets.GITHUB_TOKEN }} 35 | 36 | - name: Extract metadata (tags, labels) for Docker 37 | id: meta 38 | uses: docker/metadata-action@60a0d343a0d8a18aedee9d34e62251f752153bdb 39 | with: 40 | images: | 41 | djdembeck/bragibooks 42 | ghcr.io/${{ github.repository }} 43 | 44 | - name: Build and push Docker images 45 | uses: docker/build-push-action@a8d35412fb758de9162fd63e3fa3f0942bdedb4d 46 | with: 47 | file: docker/Dockerfile 48 | context: . 49 | push: true 50 | tags: ${{ steps.meta.outputs.tags }} 51 | labels: ${{ steps.meta.outputs.labels }} 52 | -------------------------------------------------------------------------------- /.github/workflows/release-please.yml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | branches: 4 | - main 5 | 6 | permissions: 7 | contents: write 8 | pull-requests: write 9 | 10 | name: release-please 11 | 12 | jobs: 13 | release-please: 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: googleapis/release-please-action@v4 17 | with: 18 | # this assumes that you have created a personal access token 19 | # (PAT) and configured it as a GitHub action secret named 20 | # `MY_RELEASE_PLEASE_TOKEN` (this secret name is not important). 21 | token: ${{ secrets.GITHUB_TOKEN }} 22 | # this is a built-in strategy in release-please, see "Action Inputs" 23 | # for more options 24 | release-type: python 25 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .python-version 2 | .vscode 3 | /static/ 4 | __pycache__/ 5 | config/ 6 | env/ 7 | venv/ 8 | demo/ 9 | .DS_Store 10 | admin/ 11 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. 4 | 5 | ## [1.2.3](https://github.com/djdembeck/bragibooks/compare/v1.2.2...v1.2.3) (2024-08-07) 6 | 7 | 8 | ### Bug Fixes 9 | 10 | * 🐛 fix redirect check ([#321](https://github.com/djdembeck/bragibooks/issues/321)) ([5a9429d](https://github.com/djdembeck/bragibooks/commit/5a9429dbdd6859509761eff1054d57168ea1616a)) 11 | * 🐛 required attr was in the wrong place ([#319](https://github.com/djdembeck/bragibooks/issues/319)) ([1cd064a](https://github.com/djdembeck/bragibooks/commit/1cd064aad41a192a42c2697bf665198f6a8770c6)) 12 | 13 | ## [1.2.2](https://github.com/djdembeck/bragibooks/compare/v1.2.1...v1.2.2) (2024-08-07) 14 | 15 | 16 | ### Bug Fixes 17 | 18 | * :bug: avoid using split for url checking ([c934c61](https://github.com/djdembeck/bragibooks/commit/c934c61dc674bfa62de70d1a140d87caa1f7b489)) 19 | 20 | ### [1.2.1](https://github.com/djdembeck/bragibooks/compare/v1.2.0...v1.2.1) (2023-06-09) 21 | 22 | 23 | ### Bug Fixes 24 | 25 | * button disabled bug [#178](https://github.com/djdembeck/bragibooks/issues/178) ([#183](https://github.com/djdembeck/bragibooks/issues/183)) ([ab378d5](https://github.com/djdembeck/bragibooks/commit/ab378d518b37c22535ef4ccae5a2832b093e94b2)) 26 | 27 | ## [1.2.0](https://github.com/djdembeck/bragibooks/compare/v1.0.0...v1.2.0) (2023-05-18) 28 | 29 | 30 | ### Features 31 | 32 | * add 'x' to remove search selection ([#166](https://github.com/djdembeck/bragibooks/issues/166)) ([f1f8f6d](https://github.com/djdembeck/bragibooks/commit/f1f8f6ddfcf30a945f263a69ac949c9ed728b460)) 33 | * add cover images to search results ([#167](https://github.com/djdembeck/bragibooks/issues/167)) ([e5acbc0](https://github.com/djdembeck/bragibooks/commit/e5acbc0e32b2a3e4d2803994f2352db0763080d0)) 34 | * updated the file picker ([#153](https://github.com/djdembeck/bragibooks/issues/153)) ([aed75dd](https://github.com/djdembeck/bragibooks/commit/aed75ddbffc939e0b394fe7fc063fcc92cffeac4)) 35 | 36 | 37 | ### Bug Fixes 38 | 39 | * :bug: entrypoint wasn't setting user permissions for processes ([b3bd8a7](https://github.com/djdembeck/bragibooks/commit/b3bd8a765c040ce14d57e0b483fdf689669b976b)) 40 | * updates to Dockerfile and fix bugs ([#163](https://github.com/djdembeck/bragibooks/issues/163)) ([3e0a7b3](https://github.com/djdembeck/bragibooks/commit/3e0a7b3f13b96307e43ad47222f1b3d4fd1fc726)) 41 | 42 | ## [1.0.0](https://github.com/djdembeck/bragibooks/compare/v0.3.7...v1.0.0) (2023-04-18) 43 | 44 | 45 | ### Features 46 | 47 | * Add auto search for books and Add Celery queue and task runner ([#145](https://github.com/djdembeck/bragibooks/issues/145)) ([fb17706](https://github.com/djdembeck/bragibooks/commit/fb17706b9e8e3a50546545ff16d730b7affedcde)), closes [#27](https://github.com/djdembeck/bragibooks/issues/27) [#85](https://github.com/djdembeck/bragibooks/issues/85) 48 | 49 | 50 | ### Bug Fixes 51 | 52 | * :bug: search single file now removes extension ([d05a97a](https://github.com/djdembeck/bragibooks/commit/d05a97a322ba8873d63ea55b7e59bc24fe70f229)) 53 | * :bug: searches with `&` character could fail ([3ac90c1](https://github.com/djdembeck/bragibooks/commit/3ac90c1c8196db2b63242c9e52af23ca69e6500c)) 54 | 55 | ### [0.3.7](https://github.com/djdembeck/bragibooks/compare/v0.3.6...v0.3.7) (2023-02-24) 56 | 57 | ### [0.3.6](https://github.com/djdembeck/bragibooks/compare/v0.3.5...v0.3.6) (2022-09-21) 58 | 59 | 60 | ### Features 61 | 62 | * allow setting CSRF_TRUSTED_ORIGINS via envvar ([f5c68c4](https://github.com/djdembeck/bragibooks/commit/f5c68c46ab3747f340a048ee96781bda7fa70303)) 63 | 64 | 65 | ### Bug Fixes 66 | 67 | * :bug: pass original path to `m4b-merge` so it knows what to move to the completed folder ([101e8f2](https://github.com/djdembeck/bragibooks/commit/101e8f25b6c2ecae5715e129e33f425ac485e048)) 68 | 69 | ### [0.3.5](https://github.com/djdembeck/bragibooks/compare/v0.3.4...v0.3.5) (2022-06-12) 70 | 71 | 72 | ### Features 73 | 74 | * :sparkles: Allow setting CSRF origins for reverse proxies ([ad91f25](https://github.com/djdembeck/bragibooks/commit/ad91f25050d796ca8ea5bda1e5416f50df4fa1a5)) 75 | 76 | 77 | ### Bug Fixes 78 | 79 | * :bug: fix cpu count not being set correctly ([748f980](https://github.com/djdembeck/bragibooks/commit/748f98005e8ce0a7852ce84b9ffad48d49f1fba1)) 80 | * **docker:** :bug: fix for Docker permissions initialization ([8b8386f](https://github.com/djdembeck/bragibooks/commit/8b8386f7a22c43c6b6532cebbbc8fa65cfc1e277)) 81 | 82 | ### [0.3.4](https://github.com/djdembeck/bragibooks/compare/v0.3.3...v0.3.4) (2022-01-11) 83 | 84 | 85 | ### Features 86 | 87 | * :lipstick: add versions to footer ([0969087](https://github.com/djdembeck/bragibooks/commit/0969087b1f96e3dd4e81960e938329e1758dc9b2)) 88 | 89 | ### [0.3.3](https://github.com/djdembeck/bragibooks/compare/v0.3.2...v0.3.3) (2021-12-06) 90 | 91 | 92 | ### Features 93 | 94 | * :sparkles: connect output scheme setting to m4b-merge path format ([5521be4](https://github.com/djdembeck/bragibooks/commit/5521be486a260222f01b9ac492f16223b6cdc524)) 95 | 96 | ### [0.3.2](https://github.com/djdembeck/bragibooks/compare/v0.3.1...v0.3.2) (2021-11-18) 97 | 98 | 99 | ### Features 100 | 101 | * :sparkles: add settings page ([bf90b57](https://github.com/djdembeck/bragibooks/commit/bf90b57fed20e57ed1f23ef82bad0a378a80cc10)) 102 | 103 | 104 | ### Bug Fixes 105 | 106 | * :bug: fix order of setting import ([100853a](https://github.com/djdembeck/bragibooks/commit/100853a6202a1d54cc0e8b9538500f26f521566b)) 107 | * :bug: show durations longer than 24hrs ([098f376](https://github.com/djdembeck/bragibooks/commit/098f37672ce3f0a1677b016811c0d70c88c26b97)) 108 | * **docker:** :ambulance: fix pip package location ([644a422](https://github.com/djdembeck/bragibooks/commit/644a4221512abf844877e56dcdac5b90df3acb3e)) 109 | * **model:** :bug: allow runtime to be 0 for podcasts ([8e99513](https://github.com/djdembeck/bragibooks/commit/8e99513643ddaebe27e4c66b73cf4bd673993363)) 110 | 111 | ### [0.4.1](https://github.com/djdembeck/bragibooks/compare/v0.3.1...v0.4.1) (2021-10-18) 112 | 113 | 114 | ### Bug Fixes 115 | 116 | * :bug: show durations longer than 24hrs ([098f376](https://github.com/djdembeck/bragibooks/commit/098f37672ce3f0a1677b016811c0d70c88c26b97)) 117 | * **model:** :bug: allow runtime to be 0 for podcasts ([8e99513](https://github.com/djdembeck/bragibooks/commit/8e99513643ddaebe27e4c66b73cf4bd673993363)) 118 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | 2 | # Contributing to Bragibooks 3 | 4 | First off, thanks for taking the time to contribute! ❤️ 5 | 6 | All types of contributions are encouraged and valued. See the [Table of Contents](#table-of-contents) for different ways to help and details about how this project handles them. Please make sure to read the relevant section before making your contribution. It will make it a lot easier for us maintainers and smooth out the experience for all involved. The community looks forward to your contributions. 🎉 7 | 8 | > And if you like the project, but just don't have time to contribute, that's fine. There are other easy ways to support the project and show your appreciation, which we would also be very happy about: 9 | > - Star the project 10 | > - Tweet about it 11 | > - Refer this project in your project's readme 12 | > - Mention the project at local meetups and tell your friends/colleagues 13 | 14 | 15 | ## Table of Contents 16 | 17 | - [I Have a Question](#i-have-a-question) 18 | - [I Want To Contribute](#i-want-to-contribute) 19 | - [Reporting Bugs](#reporting-bugs) 20 | - [Suggesting Enhancements](#suggesting-enhancements) 21 | - [Your First Code Contribution](#your-first-code-contribution) 22 | - [Improving The Documentation](#improving-the-documentation) 23 | - [Styleguides](#styleguides) 24 | - [Commit Messages](#commit-messages) 25 | - [Join The Project Team](#join-the-project-team) 26 | 27 | 28 | 29 | ## I Have a Question 30 | 31 | > If you want to ask a question, we assume that you have read the available [Documentation](https://github.com/djdembeck/bragibooks). 32 | 33 | Before you ask a question, it is best to search for existing [Issues](https://github.com/djdembeck/bragibooks/issues) that might help you. In case you have found a suitable issue and still need clarification, you can write your question in this issue. It is also advisable to search the internet for answers first. 34 | 35 | If you then still feel the need to ask a question and need clarification, we recommend the following: 36 | 37 | - Open an [Issue](https://github.com/djdembeck/bragibooks/issues/new). 38 | - Provide as much context as you can about what you're running into. 39 | - Provide project and platform versions (nodejs, npm, etc), depending on what seems relevant. 40 | 41 | We will then take care of the issue as soon as possible. 42 | 43 | 57 | 58 | ## I Want To Contribute 59 | 60 | > ### Legal Notice 61 | > When contributing to this project, you must agree that you have authored 100% of the content, that you have the necessary rights to the content and that the content you contribute may be provided under the project license. 62 | 63 | ### Reporting Bugs 64 | 65 | 66 | #### Before Submitting a Bug Report 67 | 68 | A good bug report shouldn't leave others needing to chase you up for more information. Therefore, we ask you to investigate carefully, collect information and describe the issue in detail in your report. Please complete the following steps in advance to help us fix any potential bug as fast as possible. 69 | 70 | - Make sure that you are using the latest version. 71 | - Determine if your bug is really a bug and not an error on your side e.g. using incompatible environment components/versions (Make sure that you have read the [documentation](https://github.com/djdembeck/bragibooks). If you are looking for support, you might want to check [this section](#i-have-a-question)). 72 | - To see if other users have experienced (and potentially already solved) the same issue you are having, check if there is not already a bug report existing for your bug or error in the [bug tracker](https://github.com/djdembeck/bragibooks/issues?q=label%3Abug). 73 | - Also make sure to search the internet (including Stack Overflow) to see if users outside of the GitHub community have discussed the issue. 74 | - Collect information about the bug: 75 | - Stack trace (Traceback) 76 | - OS, Platform and Version (Windows, Linux, macOS, x86, ARM) 77 | - Version of the interpreter, compiler, SDK, runtime environment, package manager, depending on what seems relevant. 78 | - Possibly your input and the output 79 | - Can you reliably reproduce the issue? And can you also reproduce it with older versions? 80 | 81 | 82 | #### How Do I Submit a Good Bug Report? 83 | 84 | > You must never report security related issues, vulnerabilities or bugs to the issue tracker, or elsewhere in public. Instead sensitive bugs must be sent by email to <>. 85 | 86 | 87 | We use GitHub issues to track bugs and errors. If you run into an issue with the project: 88 | 89 | - Open an [Issue](https://github.com/djdembeck/bragibooks/issues/new). (Since we can't be sure at this point whether it is a bug or not, we ask you not to talk about a bug yet and not to label the issue.) 90 | - Explain the behavior you would expect and the actual behavior. 91 | - Please provide as much context as possible and describe the *reproduction steps* that someone else can follow to recreate the issue on their own. This usually includes your code. For good bug reports you should isolate the problem and create a reduced test case. 92 | - Provide the information you collected in the previous section. 93 | 94 | Once it's filed: 95 | 96 | - The project team will label the issue accordingly. 97 | - A team member will try to reproduce the issue with your provided steps. If there are no reproduction steps or no obvious way to reproduce the issue, the team will ask you for those steps and mark the issue as `needs-repro`. Bugs with the `needs-repro` tag will not be addressed until they are reproduced. 98 | - If the team is able to reproduce the issue, it will be marked `needs-fix`, as well as possibly other tags (such as `critical`), and the issue will be left to be [implemented by someone](#your-first-code-contribution). 99 | 100 | 101 | 102 | 103 | ### Suggesting Enhancements 104 | 105 | This section guides you through submitting an enhancement suggestion for Bragibooks, **including completely new features and minor improvements to existing functionality**. Following these guidelines will help maintainers and the community to understand your suggestion and find related suggestions. 106 | 107 | 108 | #### Before Submitting an Enhancement 109 | 110 | - Make sure that you are using the latest version. 111 | - Read the [documentation](https://github.com/djdembeck/bragibooks) carefully and find out if the functionality is already covered, maybe by an individual configuration. 112 | - Perform a [search](https://github.com/djdembeck/bragibooks/issues) to see if the enhancement has already been suggested. If it has, add a comment to the existing issue instead of opening a new one. 113 | - Find out whether your idea fits with the scope and aims of the project. It's up to you to make a strong case to convince the project's developers of the merits of this feature. Keep in mind that we want features that will be useful to the majority of our users and not just a small subset. If you're just targeting a minority of users, consider writing an add-on/plugin library. 114 | 115 | 116 | #### How Do I Submit a Good Enhancement Suggestion? 117 | 118 | Enhancement suggestions are tracked as [GitHub issues](https://github.com/djdembeck/bragibooks/issues). 119 | 120 | - Use a **clear and descriptive title** for the issue to identify the suggestion. 121 | - Provide a **step-by-step description of the suggested enhancement** in as many details as possible. 122 | - **Describe the current behavior** and **explain which behavior you expected to see instead** and why. At this point you can also tell which alternatives do not work for you. 123 | - You may want to **include screenshots and animated GIFs** which help you demonstrate the steps or point out the part which the suggestion is related to. You can use [this tool](https://www.cockos.com/licecap/) to record GIFs on macOS and Windows, and [this tool](https://github.com/colinkeenan/silentcast) or [this tool](https://github.com/GNOME/byzanz) on Linux. 124 | - **Explain why this enhancement would be useful** to most Bragibooks users. You may also want to point out the other projects that solved it better and which could serve as inspiration. 125 | 126 | 127 | 128 | ### Your First Code Contribution 129 | 133 | 134 | ### Improving The Documentation 135 | 139 | 140 | ## Styleguides 141 | ### Commit Messages 142 | This project uses [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/), and all PRs/contributions must use them as well. 143 | 144 | ## Join The Project Team 145 | 146 | 147 | 148 | ## Attribution 149 | This guide is based on the **contributing-gen**. [Make your own](https://github.com/bttger/contributing-gen)! -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 | Project logo 4 |

5 | 6 |

Bragibooks

7 | 8 |
9 | 10 | [![Status](https://img.shields.io/badge/status-active-success.svg)]() 11 | [![GitHub Issues](https://img.shields.io/github/issues/djdembeck/bragibooks.svg)](https://github.com/djdembeck/bragibooks/issues) 12 | [![GitHub Pull Requests](https://img.shields.io/github/issues-pr/djdembeck/bragibooks.svg)](https://github.com/djdembeck/bragibooks/pulls) 13 | [![License](https://img.shields.io/github/license/djdembeck/bragibooks)](https://github.com/djdembeck/bragibooks/blob/develop/LICENSE) 14 | [![Docker](https://github.com/djdembeck/bragibooks/actions/workflows/docker-publish.yml/badge.svg)](https://github.com/djdembeck/bragibooks/actions/workflows/docker-publish.yml) 15 | [![Docker Pulls](https://img.shields.io/docker/pulls/djdembeck/bragibooks)](https://hub.docker.com/r/djdembeck/bragibooks) 16 | [![Docker Image Size (latest by date)](https://img.shields.io/docker/image-size/djdembeck/bragibooks)](https://hub.docker.com/r/djdembeck/bragibooks) 17 | [![Docker Image Version (latest by date)](https://img.shields.io/docker/v/djdembeck/bragibooks)](https://hub.docker.com/r/djdembeck/bragibooks) 18 | [![CodeFactor Grade](https://img.shields.io/codefactor/grade/github/djdembeck/bragibooks)](https://www.codefactor.io/repository/github/djdembeck/bragibooks) 19 | 20 | [![All Contributors](https://img.shields.io/badge/all_contributors-2-orange.svg?style=flat-square)](#contributors-) 21 | 22 | 23 |
24 | 25 | --- 26 | 27 |

An audiobook library cleanup & management app, written as a frontend for web use of m4b-merge. 28 |
29 |

30 | 31 | ## 📝 Table of Contents 32 | 33 | - [About](#about) 34 | - [Getting Started](#getting_started) 35 | - [Usage](#usage) 36 | - [Built Using](#built_using) 37 | - [Contributing](../CONTRIBUTING.md) 38 | - [Authors](#authors) 39 | - [Contributors](#contributors) 40 | 41 | ## 🧐 About 42 | 43 | **Bragi - (god of poetry in [Norse mythology](https://en.wikipedia.org/wiki/Bragi)):** 44 | Bragibooks provides a minimal and straightforward webserver that you can run remotely or locally on your server. Since Bragibooks runs in a docker, you no longer need to install dependencies on whichever OS you are on. You can 45 | 46 | Some basics of what Bragi does: 47 | - Merge multiple files 48 | - Convert mp3(s) 49 | - Cleanup existing data on an m4b file 50 | - More features on [m4b-merge's help page](https://github.com/djdembeck/m4b-merge) 51 | 52 | ### Screens 53 | 54 | Folder/file selection | ASIN input 55 | :-------------------------:|:-------------------------: 56 | ![file-selection](../assets/screens/file_picker.png) | ![asin-auto-search](../assets/screens/auto_search_panel.png) 57 | 58 | Folder/file selection | Post-proccess overview 59 | :-------------------------:|:-------------------------: 60 | ![asin-custom-search](../assets/screens/custom_search.png) | ![post-process](../assets/screens/processing_panel.png) 61 | 62 | ## 🏁 Getting Started 63 | 64 | You can either install this project directly or run it prepackaged in Docker. 65 | 66 | ### Prerequisites 67 | 68 | #### Docker 69 | - All prerequisites are included in the image. 70 | 71 | #### Direct (Gunicorn) 72 | - You'll need to install m4b-tool and it's dependants from [the project's readme](https://github.com/sandreas/m4b-tool#installation) 73 | - Run `pip install -r requirements.txt` from this project's directory. 74 | 75 | ### Installing 76 | 77 | #### Docker 78 | To run Bragibooks as a container, you need to pass some paramaters in the run command: 79 | 80 | | Parameter | Function | 81 | | :----: | --- | 82 | | `-v /path/to/input:/input` | Input folder | 83 | | `-v /path/to/output:/output` | Output folder | 84 | | `-v /appdata/bragibooks/config:/config` | Persistent config storage | 85 | | `-p 8000:8000/tcp` | Port for your browser to use | 86 | | `-e LOG_LEVEL=WARNING` | Choose any [logging level](https://www.loggly.com/ultimate-guide/python-logging-basics/) | 87 | | `-e DEBUG=False` | Turn django debug on or off (default False) | 88 | | `-e UID=99` | User ID to run the container as (default 99)| 89 | | `-e GID=100` | Group ID to run the container as (default 100)| 90 | | `-e CELERY_WORKERS=1` | The number or celery workers for processing books (default 1)| 91 | | `-e CSRF_TRUSTED_ORIGINS=https://bragibooks.mydomain.com` | Domains to trust if bragibooks is hosted behind a reverse proxy. | 92 | 93 | 94 | Which all together should look like: 95 | 96 | docker run --rm -d --name bragibooks -v /path/to/input:/input -v /path/to/output:/output -v /appdata/bragibooks/config:/config -p 8000:8000/tcp -e LOG_LEVEL=WARNING ghcr.io/djdembeck/bragibooks:main 97 | 98 | ## Docker Compose 99 | ``` 100 | version: '3' 101 | 102 | services: 103 | bragi: 104 | image: ghcr.io/djdembeck/bragibooks:main 105 | container_name: bragibooks 106 | environment: 107 | - CSRF_TRUSTED_ORIGINS=https://bragibooks.mydomain.com 108 | - LOG_LEVEL=INFO 109 | - DEBUG=False 110 | - UID=1000 111 | - GID=1000 112 | volumes: 113 | - path/to/config:/config 114 | - path/to/input:/input 115 | - path/to/output/output:/output 116 | - path/to/done:/done 117 | ports: 118 | - 8000:8000 119 | restart: unless-stopped 120 | ``` 121 | 122 | 123 | #### Direct Build (Gunicorn) 124 | - Copy static assets to project folder: 125 | ``` 126 | python manage.py collectstatic 127 | ``` 128 | - Create the database: 129 | ``` 130 | python manage.py migrate 131 | ``` 132 | - Run the celery worker for processing books: 133 | ``` 134 | celery -A bragibooks_proj worker \ 135 | --loglevel=info \ 136 | --concurrency 1 \ 137 | -E 138 | ``` 139 | - Run the web server: 140 | ``` 141 | gunicorn bragibooks_proj.wsgi \ 142 | --bind 0.0.0.0:8000 \ 143 | --timeout 1200 \ 144 | --worker-tmp-dir /dev/shm \ 145 | --workers=2 \ 146 | --threads=4 \ 147 | --worker-class=gthread \ 148 | --reload \ 149 | --enable-stdio-inheritance 150 | ``` 151 | 152 | ## 🎈 Usage 153 | 154 | The Bragibooks process is a linear, 3 step process: 155 | 1. __Select input__ - Use the file multi-select box to choose which books to process this session, and click next. 156 | 2. __Submit ASINs__ - Bragi will auto search for the audiobook data on [Audible.com](https://www.audible.com) (US only). If the data found is incorrect you can do a custom search to find the correct title and then submit for processing. 157 | 3. Wait for books to finish processing. This can take anywhere from 10 seconds to a few hours, depending on the number and type of files submitted. This will be done in the background. 158 | 4. __Books page__ - Page where you can see the data assigned to each book after it has finished processing. You can also check the status of the books still being processed. 159 | 160 | ## ⛏️ Built Using 161 | 162 | - [Django](https://www.djangoproject.com/) - Server/web framework 163 | - [Celery](https://docs.celeryq.dev/en/stable/getting-started/introduction.html) - Task queue and worker 164 | - [Bulma](https://bulma.io/) - Frontend CSS framework 165 | - [audnexus](https://github.com/laxamentumtech/audnexus) - API backend for metadata 166 | - [m4b-merge](https://github.com/djdembeck/m4b-merge) - File merging and tagging 167 | 168 | ## ✍️ Authors 169 | 170 | 171 | [@djdembeck](https://github.com/djdembeck) - Idea & Initial work 172 | 173 | ## Contributors ✨ 174 | 175 | Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)): 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 |
Koby Huckabee
Koby Huckabee

💻 🤔 📖
Andreas
Andreas

🔧
188 | 189 | 190 | 191 | 192 | 193 | 194 | This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome! -------------------------------------------------------------------------------- /bragibooks_proj/__init__.py: -------------------------------------------------------------------------------- 1 | from .celery import app as celery_app 2 | 3 | __all__ = ('celery_app',) 4 | -------------------------------------------------------------------------------- /bragibooks_proj/celery.py: -------------------------------------------------------------------------------- 1 | import os 2 | from celery import Celery 3 | 4 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bragibooks_proj.settings') 5 | 6 | app = Celery('bragibooks_proj') 7 | 8 | app.config_from_object('django.conf:settings', namespace='CELERY') 9 | 10 | app.autodiscover_tasks(["importer",]) 11 | -------------------------------------------------------------------------------- /bragibooks_proj/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for bragibooks_proj project. 3 | """ 4 | 5 | import os 6 | 7 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 8 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 9 | 10 | # config section for docker 11 | if os.path.isdir("/config"): 12 | CONFIG_DIR = os.path.abspath("/config") 13 | else: 14 | CONFIG_DIR = os.path.join(BASE_DIR, 'config') 15 | 16 | SECRET_PATH = os.path.join(CONFIG_DIR, 'secret_key.txt') 17 | 18 | # Quick-start development settings - unsuitable for production 19 | # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ 20 | 21 | # SECURITY WARNING: keep the secret key used in production secret! 22 | with open(SECRET_PATH) as f: 23 | SECRET_KEY = f.read().strip() 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True if os.environ.get('DEBUG', 'false').lower() == "true" else False 27 | 28 | ALLOWED_HOSTS = ['*'] 29 | 30 | # Application definition 31 | 32 | INSTALLED_APPS = [ 33 | 'importer', 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | ] 41 | 42 | MIDDLEWARE = [ 43 | 'whitenoise.middleware.WhiteNoiseMiddleware', 44 | 'django.middleware.security.SecurityMiddleware', 45 | 'django.contrib.sessions.middleware.SessionMiddleware', 46 | 'django.middleware.common.CommonMiddleware', 47 | 'django.middleware.csrf.CsrfViewMiddleware', 48 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 49 | 'django.contrib.messages.middleware.MessageMiddleware', 50 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 51 | ] 52 | 53 | ROOT_URLCONF = 'bragibooks_proj.urls' 54 | 55 | CSRF_TRUSTED_ORIGINS = os.getenv("CSRF_TRUSTED_ORIGINS", '').split(',') if os.getenv("CSRF_TRUSTED_ORIGINS") else '' 56 | 57 | TEMPLATES = [ 58 | { 59 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 60 | 'DIRS': [], 61 | 'APP_DIRS': True, 62 | 'OPTIONS': { 63 | 'context_processors': [ 64 | 'django.template.context_processors.debug', 65 | 'django.template.context_processors.request', 66 | 'django.contrib.auth.context_processors.auth', 67 | 'django.contrib.messages.context_processors.messages', 68 | 'importer.context_processors.add_version_to_context', 69 | ], 70 | }, 71 | }, 72 | ] 73 | 74 | WSGI_APPLICATION = 'bragibooks_proj.wsgi.application' 75 | 76 | # Database 77 | DATABASES = { 78 | 'default': { 79 | 'ENGINE': 'django.db.backends.sqlite3', 80 | 'NAME': os.path.join(CONFIG_DIR, 'db.sqlite3'), 81 | } 82 | } 83 | 84 | DEFAULT_AUTO_FIELD='django.db.models.AutoField' 85 | 86 | # Password validation 87 | # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators 88 | 89 | AUTH_PASSWORD_VALIDATORS = [ 90 | { 91 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 92 | }, 93 | { 94 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 95 | }, 96 | { 97 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 98 | }, 99 | { 100 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 101 | }, 102 | ] 103 | 104 | # Internationalization 105 | # https://docs.djangoproject.com/en/2.2/topics/i18n/ 106 | 107 | LANGUAGE_CODE = 'en-us' 108 | 109 | TIME_ZONE = 'UTC' 110 | 111 | USE_I18N = True 112 | 113 | USE_L10N = True 114 | 115 | USE_TZ = True 116 | 117 | # Static files (CSS, JavaScript, Images) 118 | # https://docs.djangoproject.com/en/2.2/howto/static-files/ 119 | 120 | STATIC_ROOT = os.path.join(BASE_DIR, 'static') 121 | STATIC_URL = '/static/' 122 | 123 | # Set environment variable DJANGO_LOG_LEVEL to desired level 124 | # https://docs.djangoproject.com/en/2.2/topics/logging/ 125 | LOGGING = { 126 | 'version': 1, 127 | 'disable_existing_loggers': False, 128 | 'handlers': { 129 | 'console': { 130 | 'level': os.getenv('LOG_LEVEL', 'INFO'), 131 | 'class': 'logging.StreamHandler', 132 | }, 133 | }, 134 | 'root': { 135 | 'handlers': ['console'], 136 | 'level': os.getenv('LOG_LEVEL', 'INFO'), 137 | }, 138 | 'loggers': { 139 | 'gunicorn': { # this was what I was missing, I kept using django and not seeing any server logs 140 | 'level': os.getenv('LOG_LEVEL', 'INFO'), 141 | 'handlers': ['console'], 142 | 'propagate': True, 143 | }, 144 | }, 145 | } 146 | 147 | 148 | # Celery broker 149 | CELERY_BROKER_URL = os.environ.get("BROKER_URL", f"sqla+sqlite:///{os.path.join(CONFIG_DIR, 'db.sqlite3')}") 150 | -------------------------------------------------------------------------------- /bragibooks_proj/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf import settings 2 | from django.contrib import admin 3 | from django.urls import path, include 4 | 5 | 6 | urlpatterns = [ 7 | path('', include('importer.urls')), 8 | ] 9 | 10 | if settings.DEBUG: 11 | urlpatterns += path('admin/', admin.site.urls), 12 | -------------------------------------------------------------------------------- /bragibooks_proj/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for bragibooks_proj project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bragibooks_proj.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /docker/.dockerignore: -------------------------------------------------------------------------------- 1 | **/__pycache__ 2 | **/.venv 3 | **/.classpath 4 | **/.dockerignore 5 | **/.env 6 | **/.git 7 | **/.gitignore 8 | **/.project 9 | **/.settings 10 | **/.toolstarget 11 | **/.vs 12 | **/.vscode 13 | **/*.*proj.user 14 | **/*.dbmdl 15 | **/*.jfm 16 | **/bin 17 | **/charts 18 | **/docker-compose* 19 | **/compose* 20 | **/Dockerfile* 21 | **/node_modules 22 | **/npm-debug.log 23 | **/obj 24 | **/secrets.dev.yaml 25 | **/values.dev.yaml 26 | LICENSE 27 | README.md 28 | -------------------------------------------------------------------------------- /docker/Dockerfile: -------------------------------------------------------------------------------- 1 | # Base image 2 | FROM ghcr.io/djdembeck/m4b-merge:develop 3 | 4 | # Keeps Python from generating .pyc files in the container 5 | ENV PYTHONDONTWRITEBYTECODE=1 6 | 7 | # Turns off buffering for easier container logging 8 | ENV PYTHONUNBUFFERED=1 9 | 10 | # Setup environment variable 11 | ENV APP_HOME=/home/app/web 12 | 13 | # Where your code lives 14 | WORKDIR $APP_HOME 15 | 16 | # Copy the necessary files to the container 17 | COPY requirements.txt . 18 | 19 | # Run this command to install all dependencies 20 | RUN pip install --no-cache-dir --upgrade pip && \ 21 | pip install --no-cache-dir -r requirements.txt 22 | 23 | # Copy whole project to your docker home directory. 24 | COPY bragibooks_proj $APP_HOME/bragibooks_proj/ 25 | COPY importer $APP_HOME/importer/ 26 | COPY utils $APP_HOME/utils/ 27 | COPY manage.py $APP_HOME 28 | 29 | # Copy entrypoint file 30 | COPY docker/entrypoint.sh /usr/local/bin/ 31 | RUN chmod +x /usr/local/bin/entrypoint.sh 32 | 33 | # Port where the Django app runs 34 | EXPOSE 8000 35 | 36 | # Entrypoint for the container 37 | ENTRYPOINT ["/usr/local/bin/entrypoint.sh"] 38 | -------------------------------------------------------------------------------- /docker/entrypoint.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # set environment variables for UID and GID 4 | PUID=${UID:-99} 5 | PGID=${GID:-100} 6 | 7 | # create a user and group with specified UID and GID 8 | addgroup -g $PGID appgroup 9 | adduser -D -u $PUID -G appgroup appuser 10 | 11 | mkdir -p $APP_HOME 12 | chown -R appuser:appuser $APP_HOME 13 | 14 | echo "Starting with UID: $PUID, GID: $PGID" 15 | 16 | # Fix permissions 17 | chown -R "$PUID":"$PGID" /config /input /output 18 | 19 | until cd /home/app/web 20 | do 21 | echo "Waiting for server volume..." 22 | sleep 1 23 | done 24 | 25 | until python manage.py migrate 26 | do 27 | echo "Waiting for db to be ready..." 28 | sleep 2 29 | done 30 | 31 | python manage.py collectstatic --noinput 32 | 33 | # Start Celery Worker 34 | gosu "$PUID":"$PGID" celery -A bragibooks_proj worker --loglevel=info --concurrency ${CELERY_WORKERS:-1} -E & 35 | 36 | # If you want to use the admin panel for debugging 37 | # python manage.py createsuperuser --noinput 38 | 39 | # Start gunicorn server 40 | gosu "$PUID":"$PGID" gunicorn bragibooks_proj.wsgi \ 41 | --bind 0.0.0.0:8000 \ 42 | --timeout 1200 \ 43 | --worker-tmp-dir /dev/shm \ 44 | --workers 2 \ 45 | --threads 4 \ 46 | --worker-class gthread \ 47 | --enable-stdio-inheritance 48 | 49 | # for debug 50 | #python manage.py runserver 0.0.0.0:8000 51 | -------------------------------------------------------------------------------- /importer/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/djdembeck/bragibooks/e5768db2b34e1bb08aa93c38eb03f4faee9f90e7/importer/__init__.py -------------------------------------------------------------------------------- /importer/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from .models import Author, Book, Narrator, Status 3 | 4 | admin.site.register(Book) 5 | admin.site.register(Author) 6 | admin.site.register(Narrator) 7 | admin.site.register(Status) 8 | -------------------------------------------------------------------------------- /importer/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class ImporterConfig(AppConfig): 5 | name = 'importer' 6 | -------------------------------------------------------------------------------- /importer/context_processors.py: -------------------------------------------------------------------------------- 1 | from django import get_version 2 | from importlib.metadata import version 3 | from .version import __version__ 4 | 5 | 6 | def add_version_to_context(request): 7 | return { 8 | 'bragibooks_version': __version__, 9 | 'django_version': get_version(), 10 | 'm4b_merge_version': version('m4b_merge') 11 | } 12 | -------------------------------------------------------------------------------- /importer/forms.py: -------------------------------------------------------------------------------- 1 | from django import forms 2 | from .models import Setting 3 | 4 | 5 | class SettingForm(forms.ModelForm): 6 | class Meta: 7 | model = Setting 8 | fields = ( 9 | 'api_url', 10 | 'completed_directory', 11 | 'input_directory', 12 | 'num_cpus', 13 | 'output_directory', 14 | 'output_scheme' 15 | ) 16 | labels = { 17 | 'api_url': 'Custom API URL', 18 | 'completed_directory': 'Directory for copy of original input files. Leave blank to disable moving.', 19 | 'input_directory': 'Input directory path', 20 | 'num_cpus': 'Number of CPUs to use (0 will use all available)', 21 | 'output_directory': 'Output directory path', 22 | 'output_scheme': 'Output path format' 23 | } 24 | widgets = { 25 | 'api_url': forms.URLInput(attrs={'class': 'input is-fullwidth'}), 26 | 'completed_directory': forms.TextInput(attrs={'class': 'input is-fullwidth', "required": False}), 27 | 'input_directory': forms.TextInput(attrs={'class': 'input is-fullwidth'}), 28 | 'num_cpus': forms.NumberInput(attrs={'class': 'input is-fullwidth'}), 29 | 'output_directory': forms.TextInput(attrs={'class': 'input is-fullwidth'}), 30 | 'output_scheme': forms.TextInput(attrs={'class': 'input is-fullwidth'}), 31 | } 32 | -------------------------------------------------------------------------------- /importer/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.2.4 on 2021-06-23 21:38 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | initial = True 9 | 10 | dependencies = [ 11 | ] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name='Author', 16 | fields=[ 17 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 18 | ('first_name', models.CharField(max_length=45)), 19 | ('last_name', models.CharField(max_length=45)), 20 | ('asin', models.CharField(default='', max_length=10, null=True)), 21 | ('short_desc', models.TextField(blank=True, default='')), 22 | ('long_desc', models.TextField(blank=True, default='')), 23 | ('created_at', models.DateTimeField(auto_now_add=True)), 24 | ('updated_at', models.DateTimeField(auto_now=True)), 25 | ], 26 | ), 27 | migrations.CreateModel( 28 | name='Book', 29 | fields=[ 30 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 31 | ('title', models.CharField(max_length=255)), 32 | ('asin', models.CharField(max_length=10)), 33 | ('short_desc', models.TextField()), 34 | ('long_desc', models.TextField()), 35 | ('release_date', models.DateField()), 36 | ('series', models.CharField(blank=True, default='', max_length=255)), 37 | ('publisher', models.CharField(max_length=255)), 38 | ('lang', models.CharField(max_length=25)), 39 | ('runtime_length_minutes', models.IntegerField()), 40 | ('format_type', models.CharField(max_length=25)), 41 | ('converted', models.BooleanField()), 42 | ('src_path', models.FilePathField()), 43 | ('dest_path', models.FilePathField()), 44 | ('created_at', models.DateTimeField(auto_now_add=True)), 45 | ('updated_at', models.DateTimeField(auto_now=True)), 46 | ], 47 | ), 48 | migrations.CreateModel( 49 | name='Narrator', 50 | fields=[ 51 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 52 | ('first_name', models.CharField(max_length=45)), 53 | ('last_name', models.CharField(max_length=45)), 54 | ('short_desc', models.TextField(blank=True, default='')), 55 | ('long_desc', models.TextField(blank=True, default='')), 56 | ('created_at', models.DateTimeField(auto_now_add=True)), 57 | ('updated_at', models.DateTimeField(auto_now=True)), 58 | ('books', models.ManyToManyField(related_name='narrators', to='importer.Book')), 59 | ], 60 | ), 61 | migrations.CreateModel( 62 | name='Genre', 63 | fields=[ 64 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 65 | ('name', models.CharField(max_length=255)), 66 | ('asin', models.CharField(max_length=10)), 67 | ('created_at', models.DateTimeField(auto_now_add=True)), 68 | ('updated_at', models.DateTimeField(auto_now=True)), 69 | ('authors', models.ManyToManyField(related_name='genres', to='importer.Author')), 70 | ('books', models.ManyToManyField(related_name='genres', to='importer.Book')), 71 | ('narrators', models.ManyToManyField(related_name='genres', to='importer.Narrator')), 72 | ], 73 | ), 74 | migrations.AddField( 75 | model_name='author', 76 | name='books', 77 | field=models.ManyToManyField(related_name='authors', to='importer.Book'), 78 | ), 79 | ] 80 | -------------------------------------------------------------------------------- /importer/migrations/0002_setting.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 3.2.5 on 2021-11-13 22:04 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | dependencies = [ 9 | ('importer', '0001_initial'), 10 | ] 11 | 12 | operations = [ 13 | migrations.CreateModel( 14 | name='Setting', 15 | fields=[ 16 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 17 | ('api_url', models.CharField(max_length=255)), 18 | ('completed_directory', models.CharField(max_length=255)), 19 | ('input_directory', models.CharField(max_length=255)), 20 | ('num_cpus', models.IntegerField()), 21 | ('output_directory', models.CharField(max_length=255)), 22 | ('output_scheme', models.CharField(max_length=255)), 23 | ('created_at', models.DateTimeField(auto_now_add=True)), 24 | ('updated_at', models.DateTimeField(auto_now=True)), 25 | ], 26 | ), 27 | ] 28 | -------------------------------------------------------------------------------- /importer/migrations/0003_delete_genre.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 4.0.1 on 2022-01-10 01:19 2 | 3 | from django.db import migrations 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | dependencies = [ 9 | ('importer', '0002_setting'), 10 | ] 11 | 12 | operations = [ 13 | migrations.DeleteModel( 14 | name='Genre', 15 | ), 16 | ] 17 | -------------------------------------------------------------------------------- /importer/migrations/0004_book_status.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 4.1.4 on 2023-03-30 20:43 2 | 3 | from django.db import migrations, models 4 | import django.db.models.deletion 5 | 6 | from importer.models import StatusChoices 7 | 8 | def create_add_status(apps, _): 9 | Book = apps.get_model("importer", "Book") 10 | Status = apps.get_model("importer", "Status") 11 | 12 | for book in Book.objects.all(): 13 | book.status = Status.objects.create(status=StatusChoices.DONE) 14 | book.save() 15 | 16 | class Migration(migrations.Migration): 17 | 18 | dependencies = [ 19 | ('importer', '0003_delete_genre'), 20 | ] 21 | 22 | operations = [ 23 | migrations.CreateModel( 24 | name='Status', 25 | fields=[ 26 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 27 | ('status', models.CharField(choices=[('Processing', 'Processing'), ('Done', 'Done'), ('Error', 'Error')], max_length=10)), 28 | ('message', models.TextField()), 29 | ], 30 | ), 31 | 32 | migrations.AddField( 33 | model_name='book', 34 | name='status', 35 | field=models.OneToOneField(to='importer.status', on_delete=django.db.models.deletion.CASCADE, null=True, default=None), 36 | preserve_default=False, 37 | ), 38 | 39 | migrations.RunPython(create_add_status, migrations.RunPython.noop), 40 | 41 | migrations.AlterField( 42 | model_name='book', 43 | name='status', 44 | field=models.OneToOneField(to='importer.status', on_delete=django.db.models.deletion.CASCADE, null=False), 45 | ), 46 | migrations.AlterField( 47 | model_name='book', 48 | name='dest_path', 49 | field=models.TextField(), 50 | ), 51 | migrations.AlterField( 52 | model_name='book', 53 | name='src_path', 54 | field=models.TextField(), 55 | ), 56 | ] 57 | -------------------------------------------------------------------------------- /importer/migrations/0005_cover_image_link.py: -------------------------------------------------------------------------------- 1 | from django.db import migrations, models 2 | from m4b_merge import audible_helper, config 3 | 4 | from utils.merge import set_configs 5 | 6 | def add_cover_image_link(apps, _): 7 | Book = apps.get_model("importer", "Book") 8 | set_configs() 9 | 10 | for book in Book.objects.all(): 11 | metadata = audible_helper.BookData(book.asin).fetch_api_data(config.api_url) 12 | book.cover_image_link = metadata['image'] 13 | book.save() 14 | 15 | class Migration(migrations.Migration): 16 | 17 | dependencies = [ 18 | ('importer', '0004_book_status'), 19 | ] 20 | 21 | operations = [ 22 | migrations.AddField( 23 | model_name='book', 24 | name='cover_image_link', 25 | field=models.URLField(blank=True, null=True), 26 | preserve_default=False, 27 | ), 28 | 29 | migrations.RunPython(add_cover_image_link, migrations.RunPython.noop), 30 | 31 | migrations.AlterField( 32 | model_name='book', 33 | name='cover_image_link', 34 | field=models.URLField(null=False) 35 | ), 36 | ] 37 | -------------------------------------------------------------------------------- /importer/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/djdembeck/bragibooks/e5768db2b34e1bb08aa93c38eb03f4faee9f90e7/importer/migrations/__init__.py -------------------------------------------------------------------------------- /importer/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | from pathlib import Path 3 | 4 | 5 | class BookManager(models.Manager): 6 | def book_asin_validator(self, asin): 7 | errors = {} 8 | 9 | if len(asin) != 10 and len(asin) != 0: 10 | errors['invalid_asin'] = f"Invalid ASIN format for {asin}" 11 | 12 | if len(asin) == 0: 13 | errors['blank_asin'] = "Must fill in all ASIN fields" 14 | 15 | return errors 16 | 17 | 18 | class SettingManager(models.Manager): 19 | def file_path_validator(self, path): 20 | errors = {} 21 | 22 | if not Path(path).is_dir(): 23 | try: 24 | Path(path).mkdir(parents=True, exist_ok=True) 25 | except OSError: 26 | errors['invalid_path'] = ( 27 | f"Invalid path: {path}" 28 | ) 29 | return errors 30 | 31 | 32 | class StatusChoices(models.TextChoices): 33 | PROCESSING = "Processing" 34 | DONE = "Done" 35 | ERROR = "Error" 36 | 37 | 38 | class Status(models.Model): 39 | status = models.CharField(max_length=10, choices=StatusChoices.choices) 40 | message = models.TextField() 41 | 42 | def __str__(self) -> str: 43 | return self.status 44 | 45 | 46 | class Book(models.Model): 47 | title = models.CharField(max_length=255) 48 | asin = models.CharField(max_length=10) 49 | short_desc = models.TextField() 50 | long_desc = models.TextField() 51 | release_date = models.DateField() 52 | series = models.CharField(max_length=255, blank=True, default='') 53 | publisher = models.CharField(max_length=255) 54 | lang = models.CharField(max_length=25) 55 | runtime_length_minutes = models.IntegerField() 56 | format_type = models.CharField(max_length=25) 57 | converted = models.BooleanField() 58 | src_path = models.TextField() 59 | dest_path = models.TextField() 60 | created_at = models.DateTimeField(auto_now_add=True) 61 | updated_at = models.DateTimeField(auto_now=True) 62 | status = models.OneToOneField(Status, on_delete=models.CASCADE) 63 | cover_image_link = models.URLField() 64 | objects = BookManager() 65 | 66 | def __str__(self) -> str: 67 | return f"{self.title}: by {', '.join(str(author) for author in self.authors.all())}" 68 | 69 | 70 | class Author(models.Model): 71 | first_name = models.CharField(max_length=45) 72 | last_name = models.CharField(max_length=45) 73 | asin = models.CharField(max_length=10, null=True, default='') 74 | books = models.ManyToManyField(Book, related_name="authors") 75 | short_desc = models.TextField(blank=True, default='') 76 | long_desc = models.TextField(blank=True, default='') 77 | created_at = models.DateTimeField(auto_now_add=True) 78 | updated_at = models.DateTimeField(auto_now=True) 79 | 80 | def __str__(self) -> str: 81 | return f"{self.first_name} {self.last_name}" 82 | 83 | 84 | class Narrator(models.Model): 85 | first_name = models.CharField(max_length=45) 86 | last_name = models.CharField(max_length=45) 87 | books = models.ManyToManyField(Book, related_name="narrators") 88 | short_desc = models.TextField(blank=True, default='') 89 | long_desc = models.TextField(blank=True, default='') 90 | created_at = models.DateTimeField(auto_now_add=True) 91 | updated_at = models.DateTimeField(auto_now=True) 92 | 93 | def __str__(self) -> str: 94 | return f"{self.first_name} {self.last_name}" 95 | 96 | 97 | class Setting(models.Model): 98 | api_url = models.CharField(max_length=255) 99 | completed_directory = models.CharField(max_length=255) 100 | input_directory = models.CharField(max_length=255) 101 | num_cpus = models.IntegerField() 102 | output_directory = models.CharField(max_length=255) 103 | output_scheme = models.CharField(max_length=255) 104 | created_at = models.DateTimeField(auto_now_add=True) 105 | updated_at = models.DateTimeField(auto_now=True) 106 | objects = SettingManager() 107 | -------------------------------------------------------------------------------- /importer/static/images/cover_not_available.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/djdembeck/bragibooks/e5768db2b34e1bb08aa93c38eb03f4faee9f90e7/importer/static/images/cover_not_available.jpg -------------------------------------------------------------------------------- /importer/static/images/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/djdembeck/bragibooks/e5768db2b34e1bb08aa93c38eb03f4faee9f90e7/importer/static/images/favicon.ico -------------------------------------------------------------------------------- /importer/static/images/logo-small-black.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /importer/tasks.py: -------------------------------------------------------------------------------- 1 | from bragibooks_proj.celery import app as celery_app 2 | from utils.merge import run_m4b_merge 3 | 4 | 5 | @celery_app.task 6 | def m4b_merge_task(asin: str): 7 | run_m4b_merge(asin=asin) 8 | -------------------------------------------------------------------------------- /importer/templates/base.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | {% block title %}Bragi Books{% endblock %} 8 | 9 | 10 | {% load static %} 11 | 12 | 31 | 32 | 33 |
34 | 60 |
61 |
62 |
63 | {% if messages %} 64 |
65 |
    66 | {% for message in messages %} 67 |
  • {{message}}
  • 68 | {% endfor %} 69 |
70 |
71 |
72 | {% endif %} 73 |
74 |
75 | {% block content %}{% endblock %} 76 |
77 |
78 |
79 |
80 |

81 | Bragibooks v{{ bragibooks_version }} - 82 | Django v{{ django_version }} - 83 | m4b-merge v{{ m4b_merge_version }} 84 |

85 |
86 |
87 | 91 | 92 | -------------------------------------------------------------------------------- /importer/templates/book_list.html: -------------------------------------------------------------------------------- 1 | {% if books|length > 0 %} 2 | {% for book, book_length in books %} 3 |
4 | {% if book.asin %} 5 |
6 |
7 |
8 |
    9 |
  • 10 |
  • Title: {{ book.title }}{% if book.subtitle %} - {{ book.subtitle }}{% endif %}
  • 11 |
  • Author(s): {% for author in book.authors.all %}{% if not forloop.first %}{% if forloop.last %} and {% else %}, {% endif %}{% endif %}{{ author.first_name }} {{ author.last_name }}{% endfor %}
  • 12 |
  • Narrator(s): {% for narrator in book.narrators.all %}{% if not forloop.first %}{% if forloop.last %} and {% else %}, {% endif %}{% endif %}{{ narrator.first_name }} {{ narrator.last_name }}{% endfor %}
  • 13 | {% if book.series %}
  • Series: {{ book.series }}
  • {% endif %} 14 |
  • Length: {{ book_length }}
  • 15 |
  • Type: {{ book.format_type }}
  • 16 |
  • Release Date: {{ book.release_date }}
  • 17 |
  • Language: {{ book.lang }}
  • 18 |
  • Publisher: {{ book.publisher }}
  • 19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 | Description: 27 | {% if book.status.status == 'Error' %} 28 |

{{ book.status.message }}

29 | {% else %} 30 |

31 | {{ book.long_desc|safe }} 32 |

33 | {% endif %} 34 |
35 |
36 |
37 |
38 | {% endif %} 39 |
40 | {% endfor %} 41 | {% else %} 42 |
43 |
44 |
45 |
46 |

Nothing to see here.

47 |
48 |
49 |
50 |
51 | {% endif %} 52 | 53 | -------------------------------------------------------------------------------- /importer/templates/book_tabs.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | {% block content %} 3 |
4 |
5 | 10 |
11 | 12 |
13 |
14 | {% include "book_list.html" with books=done_books %} 15 |
16 | 19 | 22 |
23 |
24 | {% endblock %} 25 | 26 | {% block script %} 27 | {% include "book_tabs.js" %} 28 | {% endblock %} -------------------------------------------------------------------------------- /importer/templates/book_tabs.js: -------------------------------------------------------------------------------- 1 | function openTab(tabId) { 2 | const tabLinks = document.querySelectorAll(".tab"); 3 | tabLinks.forEach(tab => { 4 | tab.classList.remove("is-active"); 5 | }); 6 | 7 | const tabPanes = document.querySelectorAll(".tab-pane"); 8 | tabPanes.forEach(pane => { 9 | pane.style.display = "none"; 10 | }); 11 | 12 | document.getElementById(tabId).style.display = "block"; 13 | document.getElementById(`${tabId}-tab`).classList.add("is-active"); 14 | } 15 | 16 | window.addEventListener('load', function () { 17 | const defaultTab = document.querySelector(".tabs").dataset.default 18 | openTab(defaultTab); 19 | }); -------------------------------------------------------------------------------- /importer/templates/directory_contents.html: -------------------------------------------------------------------------------- 1 | {% load directory_explorer_tags %} 2 | 3 | {% for item in contents %} 4 | {% with id=item|generate_id %} 5 | {% if item|is_directory %} 6 | 21 | 22 | {% render_directory path=item folder_id=id depth=depth|add_one%} 23 | 24 | {% else %} 25 | 26 | 36 | 37 | {% endif %} 38 | {% endwith %} 39 | {% endfor %} 40 | -------------------------------------------------------------------------------- /importer/templates/importer.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | {% block style %} 3 | .panel { 4 | background: white; 5 | } 6 | 7 | .panel-block { 8 | display: flex; 9 | } 10 | 11 | .panel-block.folder { 12 | display: flex; 13 | justify-content: space-between; 14 | } 15 | 16 | .panel-block.folder div { 17 | display: flex; 18 | align-items: center; 19 | } 20 | 21 | .panel-block label { 22 | word-wrap: break-word; 23 | } 24 | 25 | .panel-block-container { 26 | overflow: auto; 27 | max-height: 500px; 28 | min-heigth: 350px; 29 | display: flex; 30 | flex-grow: 1; 31 | flex-direction: column; 32 | word-break: break-all; 33 | } 34 | 35 | .control.has-icons-right .icon { 36 | pointer-events: auto; 37 | } 38 | 39 | .clear-search { 40 | cursor: default; 41 | } 42 | 43 | .has-icons-right { 44 | position: relative; 45 | } 46 | {% endblock %} 47 | {% load directory_explorer_tags %} 48 | {% block content %} 49 |
50 |
51 | 80 |
81 |
82 | {% endblock %} 83 | {% block script %} 84 | {% include "importer.js" %} 85 | {% endblock %} -------------------------------------------------------------------------------- /importer/templates/importer.js: -------------------------------------------------------------------------------- 1 | function expandFolder(folderId) { 2 | // Select the arrow element 3 | const arrow = document.querySelector(`.folder[id^='${folderId}'] .arrow i`); 4 | 5 | // Toggle the rotation class on the arrow element 6 | arrow.classList.toggle('fa-rotate-90'); 7 | 8 | // Select all items in the folder 9 | const items = document.querySelectorAll(`.panel-block[folder-id^='${folderId}']`); 10 | 11 | // Toggle the display style of each item 12 | items.forEach(item => { 13 | item.style.display = item.style.display === 'none' ? '' : 'none'; 14 | }); 15 | } 16 | 17 | const arrows = document.querySelectorAll(".arrow i"); 18 | arrows.forEach(arrow => { 19 | arrow.addEventListener("click", (event) => { 20 | event.preventDefault(); 21 | expandFolder(arrow.id) 22 | }); 23 | }); 24 | 25 | function fuzzyMatch(needle, haystack) { 26 | let hlen = haystack.length; 27 | let nlen = needle.length; 28 | if (nlen > hlen) { 29 | return false; 30 | } 31 | if (nlen === hlen) { 32 | return needle === haystack; 33 | } 34 | outer: for (let i = 0, j = 0; i < nlen; i++) { 35 | const nch = needle.charCodeAt(i); 36 | while (j < hlen) { 37 | if (haystack.charCodeAt(j++) === nch) { 38 | continue outer; 39 | } 40 | } 41 | return false; 42 | } 43 | return true; 44 | } 45 | 46 | function resetPanel() { 47 | // reset the file explorer to its base config 48 | const depth0 = panelBlock.querySelectorAll('label.panel-block[folder-id=""]'); 49 | const everythingElse = panelBlock.querySelectorAll('label.panel-block:not([folder-id=""])'); 50 | 51 | depth0.forEach(label => { 52 | label.style.display = ''; 53 | }); 54 | 55 | everythingElse.forEach(label => { 56 | label.style.display = 'none'; 57 | }); 58 | 59 | // Select the arrow element 60 | const arrows = document.querySelectorAll(`.arrow i`); 61 | 62 | // Toggle the rotation class on the arrow element 63 | arrows.forEach(arrow => { 64 | arrow.classList.remove('fa-rotate-90'); 65 | }); 66 | } 67 | 68 | // Get the search input and panel elements 69 | const searchInput = document.getElementById('search-input'); 70 | const panelBlock = document.querySelector('.panel-block-container'); 71 | 72 | // Add an input event listener to the search input 73 | searchInput.addEventListener('input', () => { 74 | // Get the search query 75 | let query = searchInput.value.toLowerCase(); 76 | 77 | if (query) { 78 | // Loop through each label in the panel 79 | panelBlock.querySelectorAll('label').forEach(label => { 80 | // Get the label text 81 | const labelText = label.textContent.toLowerCase().trim(); 82 | 83 | // Show or hide the label based on whether the query matches the label text 84 | if (fuzzyMatch(query, labelText)) { 85 | label.style.display = ''; 86 | } else { 87 | label.style.display = 'none'; 88 | } 89 | }); 90 | } else { 91 | resetPanel() 92 | } 93 | }); 94 | 95 | 96 | 97 | // add action to make the select all checkbox select/deselect all top level objects 98 | const selectAllCheckbox = document.getElementById("select-all-checkbox"); 99 | const checkboxes = document.querySelectorAll('.panel-block-container label[folder-id=""] input[type="checkbox"]'); 100 | selectAllCheckbox.addEventListener("change", function () { 101 | checkboxes.forEach(function (checkbox) { 102 | checkbox.checked = selectAllCheckbox.checked; 103 | }); 104 | }); 105 | 106 | const clearSearchButton = document.querySelector('.clear-search'); 107 | clearSearchButton.addEventListener('click', () => { 108 | searchInput.value = ''; 109 | resetPanel() 110 | }); 111 | -------------------------------------------------------------------------------- /importer/templates/match.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | {% load directory_explorer_tags %} 3 | {% block style %} 4 | .modal-card { 5 | position: fixed; 6 | top: 10%; 7 | } 8 | 9 | .modal-card-foot { 10 | display: flex; 11 | justify-content: space-between; 12 | } 13 | 14 | .notification { 15 | flex-grow: 1; 16 | text-align: left; 17 | } 18 | 19 | .image-label-container { 20 | display: flex; 21 | align-items: end; 22 | gap: 10px; 23 | margin-bottom: 10px; 24 | margin-left: 20px; 25 | } 26 | 27 | .image-label-container label { 28 | line-break: anywhere; 29 | } 30 | 31 | .image-label-container img { 32 | width: 150px; 33 | border-radius: 10px; 34 | } 35 | 36 | {% endblock %} 37 | {% block content %} 38 |
39 |
40 |
41 | {% csrf_token %} 42 |
43 |
44 |
45 |

Submit ASINs

46 |
47 |
48 |
49 |
50 | {% for input in context %} 51 |
52 |
53 | {% load static %} 54 | 55 | 56 |
57 |
58 |
59 | 60 |
61 | 64 |
65 | 66 |
67 |
68 |
69 | {% endfor %} 70 |
71 |
72 |
73 | 78 |
79 |
80 |
81 |
82 |
83 | 84 | 85 | 126 | 127 | 143 | {% endblock %} 144 | {% block script %} 145 | {% include "match.js" %} 146 | {% endblock %} -------------------------------------------------------------------------------- /importer/templates/match.js: -------------------------------------------------------------------------------- 1 | function openSearchPanel(srcPath, select_id) { 2 | const modal = document.getElementById('custom-search-modal'); 3 | const modalTitle = modal.querySelector('.modal-card-title'); 4 | modalTitle.textContent = `Custom Search: ${srcPath}`; 5 | modal.classList.add('is-active'); 6 | modal.dataset.value = select_id; 7 | } 8 | 9 | function closeSearchPanel() { 10 | const modal = document.getElementById('custom-search-modal'); 11 | 12 | // Clear the input fields 13 | modal.querySelector('#title').value = ''; 14 | modal.querySelector('#author').value = ''; 15 | modal.querySelector('#keywords').value = ''; 16 | 17 | // Clear the search notification 18 | document.getElementById('search-notification').style.display = "none"; 19 | 20 | // Close the panel 21 | modal.classList.remove("is-active"); 22 | } 23 | 24 | function openRemoveConfirmationModal(label, column_index) { 25 | const modalLabel = document.querySelector("#confirm-modal-title"); 26 | modalLabel.textContent = `Remove ${label} from search`; 27 | 28 | const modalButton = document.querySelector("#remove-column-button"); 29 | modalButton.onclick = () => removeColumn(column_index) 30 | 31 | // Get the modal element and set it to active 32 | const modal = document.getElementById('remove-confirmation-modal'); 33 | modal.classList.add('is-active'); 34 | } 35 | 36 | function closeRemoveConfirmationModal() { 37 | // Get the modal element and remove the active class 38 | const modal = document.getElementById('remove-confirmation-modal'); 39 | modal.classList.remove('is-active'); 40 | } 41 | 42 | function removeColumn(column_index) { 43 | const columnToRemove = document.querySelector(`#asin-search-${column_index}`); 44 | columnToRemove.remove(); 45 | 46 | // Close the modal 47 | closeRemoveConfirmationModal(); 48 | 49 | // Check all searches have values 50 | checkAllSelectsHaveValue(); 51 | } 52 | 53 | function constructQueryParams(media_dir, title, author, keywords) { 54 | let params = []; 55 | if (media_dir) { 56 | params.push(`media_dir=${encodeURIComponent(media_dir)}`); 57 | } 58 | if (title) { 59 | params.push(`title=${encodeURIComponent(title)}`); 60 | } 61 | if (author) { 62 | params.push(`author=${encodeURIComponent(author)}`); 63 | } 64 | if (keywords) { 65 | params.push(`keywords=${encodeURIComponent(keywords)}`); 66 | } 67 | return `?${params.join('&')}`; 68 | } 69 | 70 | async function search(url) { 71 | try { 72 | const response = await fetch(url); 73 | const data = response.json(); 74 | return data; 75 | 76 | } catch (error) { 77 | console.error(`Error fetching options for select with url ${url}: ${error}`); 78 | } 79 | } 80 | 81 | function createOption(value, text, image_link) { 82 | const opt = document.createElement("option"); 83 | if (value) { 84 | opt.value = value; 85 | } 86 | 87 | opt.text = text; 88 | opt.setAttribute("data-image-link", image_link); 89 | return opt; 90 | } 91 | 92 | function noOptionsFound(select) { 93 | select.style.borderColor = "red"; 94 | select.style.borderWidth = "2px"; 95 | let opt = createOption("", "No Audiobook results found, try a custom search...", ""); 96 | select.appendChild(opt); 97 | } 98 | 99 | function updateOptions(select, data) { 100 | select.innerHTML = ""; 101 | 102 | if (!data.length) { 103 | noOptionsFound(select); 104 | select.parentElement.classList.remove("is-loading"); 105 | return; 106 | } 107 | 108 | select.removeAttribute("style"); 109 | 110 | data.forEach(option => { 111 | text = option.title + " by " + option.author + " - Narrator " + option.narrator + ": " + option.asin; 112 | let opt = createOption(option.asin, text, option.image_link); 113 | select.appendChild(opt); 114 | }); 115 | 116 | select.parentElement.classList.remove("is-loading"); 117 | } 118 | 119 | function updateImage(counter) { 120 | // Get the selected value from the select element 121 | const selectElement = document.getElementById(`asin-select-${counter}`); 122 | 123 | // Get the corresponding image element 124 | const imageElement = document.getElementById(`image-${counter}`); 125 | 126 | // Update the image source 127 | let image_link = selectElement.options[selectElement.selectedIndex].dataset.imageLink; 128 | 129 | if (image_link) { 130 | imageElement.src = image_link; 131 | } 132 | } 133 | 134 | function checkAllSelectsHaveValue() { 135 | var hasValues = true; 136 | 137 | document.querySelectorAll(".asin-select").forEach(select => { 138 | if (select.value.length != 10) { 139 | hasValues = false; 140 | return; 141 | } 142 | }); 143 | 144 | if (!hasValues) { 145 | document.getElementById("match-form-submit").disabled = true; 146 | } else { 147 | document.getElementById("match-form-submit").disabled = false; 148 | } 149 | } 150 | 151 | async function searchAsin(title, author, keywords) { 152 | const modal = document.getElementById('custom-search-modal'); 153 | const select = document.getElementById(modal.dataset.value); 154 | 155 | // Build the query params and url 156 | let queryParams = constructQueryParams("", title, author, keywords); 157 | console.debug(queryParams); 158 | url = "asin-search" + queryParams; 159 | 160 | // Call the URL and get response 161 | let data = await search(url); 162 | 163 | if (!data.length) { 164 | // display message in search panel and return, dont close the search panel 165 | document.getElementById('search-notification').style.display = "block"; 166 | return; 167 | } 168 | 169 | // Update the select for the calling custom search 170 | updateOptions(select, data) 171 | 172 | // update cover image 173 | const counter = select.id.split('-').pop(); 174 | updateImage(counter) 175 | 176 | // close the search panel 177 | closeSearchPanel(); 178 | 179 | // check all selects have a value and update submit button 180 | checkAllSelectsHaveValue(); 181 | } 182 | 183 | async function fetchOptions() { 184 | const selects = document.querySelectorAll(".asin-select"); 185 | 186 | const searchPromises = Array.from(selects).map(async select => { 187 | const url = "asin-search" + constructQueryParams(select.name.split('/').pop()); 188 | 189 | const data = await search(url); 190 | updateOptions(select, data); 191 | 192 | const counter = select.id.split('-').pop(); 193 | updateImage(counter); 194 | }); 195 | 196 | await Promise.all(searchPromises); 197 | checkAllSelectsHaveValue(); 198 | } 199 | 200 | fetchOptions(); 201 | checkAllSelectsHaveValue(); 202 | -------------------------------------------------------------------------------- /importer/templates/setting.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | {% block content %} 3 |
4 |
5 |
6 |
7 |
8 |

Settings

9 |
10 |
11 |
12 | {% csrf_token %} 13 |
14 | {% for field in form %} 15 |
16 |
17 |
18 | {{ field.label_tag }} 19 | {% if field.name == "output_scheme" %} 20 |
21 |
22 |

23 | Use "/" for subdirectories. 24 |
25 | Supported output scheme keywords are: 26 |
27 | asin, author, narrator, series_name, series_position, subtitle, title, year 28 |

29 |
30 |
31 | {% endif %} 32 |
33 | {{ field }} 34 |
35 |
36 |
37 |
38 | {% endfor %} 39 |
40 | 47 |
48 |
49 |
50 |
51 | {% endblock %} -------------------------------------------------------------------------------- /importer/templatetags/directory_explorer_tags.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from pathlib import Path 3 | import uuid 4 | from django import template 5 | import os 6 | 7 | logger = logging.getLogger(__name__) 8 | register = template.Library() 9 | 10 | 11 | @register.filter 12 | def is_directory(path): 13 | return os.path.isdir(path) 14 | 15 | 16 | @register.filter 17 | def basename(path): 18 | return os.path.basename(path) 19 | 20 | 21 | @register.filter 22 | def add_one(num): 23 | if num: 24 | return num + 1 25 | else: 26 | return 1 27 | 28 | 29 | @register.filter 30 | def get_range(num): 31 | if num: 32 | return [i for i in range(int(num))] 33 | 34 | 35 | @register.filter 36 | def generate_id(_): 37 | return uuid.uuid4() 38 | 39 | 40 | def directory_contents(path): 41 | """ 42 | Returns a list of files and subdirectories in the given path. 43 | """ 44 | return sorted(Path(path).iterdir(), key=os.path.getmtime, reverse=True) 45 | 46 | 47 | @register.inclusion_tag("directory_contents.html") 48 | def render_directory(path, folder_id, depth): 49 | """ 50 | Renders a directory and its contents as a nested list. 51 | """ 52 | contents = directory_contents(path) 53 | return { 54 | "path": path, 55 | "contents": contents, 56 | "display": "none" if int(depth) > 0 else "", 57 | "folder_id": f"{folder_id}", 58 | "depth": depth, 59 | } 60 | -------------------------------------------------------------------------------- /importer/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /importer/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path, re_path 2 | from . import views 3 | urlpatterns = [ 4 | path('', views.ImportView.as_view(), name='import'), 5 | path('match', views.MatchView.as_view(), name='match'), 6 | re_path(r'^asin-search/$', views.AsinSearch.as_view(), name='asin-search'), 7 | path('books', views.BookListView.as_view(), name='books'), 8 | path('setting', views.SettingView.as_view(), name='setting'), 9 | ] 10 | -------------------------------------------------------------------------------- /importer/version.py: -------------------------------------------------------------------------------- 1 | __version__ = '1.2.3' 2 | -------------------------------------------------------------------------------- /importer/views.py: -------------------------------------------------------------------------------- 1 | # System imports 2 | import logging 3 | import os 4 | from datetime import timedelta 5 | from pathlib import Path 6 | 7 | import requests 8 | from django.conf import settings 9 | from django.contrib import messages 10 | from django.http import HttpRequest, HttpResponseBadRequest, JsonResponse 11 | from django.shortcuts import redirect, render 12 | from django.views.generic import TemplateView, View 13 | # core merge logic: 14 | from m4b_merge import helpers 15 | 16 | # Import Merge functions for django 17 | from utils.merge import create_book 18 | # Import Search tools 19 | from utils.search_tools import ScoreTool, SearchTool 20 | 21 | # Forms import 22 | from .forms import SettingForm 23 | # Models import 24 | from .models import Book, Setting, StatusChoices 25 | from .tasks import m4b_merge_task 26 | 27 | # Get an instance of a logger 28 | logger = logging.getLogger(__name__) 29 | 30 | # If using docker, default to /input folder, else $USER/input 31 | if Path('/input').is_dir(): 32 | rootdir = "/input" 33 | else: 34 | rootdir = f"{str(Path.home())}/input" 35 | 36 | 37 | class ImportView(TemplateView): 38 | template_name = "importer.html" 39 | 40 | def get_context_data(self, **kwargs): 41 | context = { 42 | "contents": sorted( 43 | Path(rootdir).iterdir(), key=os.path.getmtime, reverse=True 44 | ) 45 | } 46 | return context 47 | 48 | def post(self, request): 49 | # Redirect if this is a new session 50 | existing_settings = Setting.objects.first() 51 | if not existing_settings: 52 | logger.debug("No settings found, returning to settings page") 53 | messages.error( 54 | request, "Settings must be configured before import" 55 | ) 56 | return redirect("setting") 57 | 58 | if not (input_dir := request.POST.getlist('input_dir')): 59 | messages.error(request, "You must select content to import") 60 | return redirect("import") 61 | 62 | request.session['input_dir'] = input_dir 63 | return redirect("match") 64 | 65 | 66 | class MatchView(TemplateView): 67 | template_name = "match.html" 68 | 69 | def get(self, request): 70 | # Redirect if this is a new session 71 | if 'input_dir' not in request.session: 72 | logger.debug("No session data found, returning to import page") 73 | return redirect("import") 74 | 75 | return render(request, self.template_name, self.get_context_data()) 76 | 77 | def get_context_data(self, **kwargs) -> dict: 78 | # Check if any of these inputs exist in our DB 79 | # If so, prepopulate their asins 80 | context = [] 81 | for this_dir in self.request.session['input_dir']: 82 | try: 83 | book = Book.objects.get(src_path=f"{this_dir}") 84 | except Book.DoesNotExist: 85 | context.append({'src_path': this_dir}) 86 | else: 87 | context.append({'src_path': this_dir, 'asin': book.asin}) 88 | 89 | return {"context": context} 90 | 91 | def post(self, request: HttpRequest): 92 | created_books = False 93 | for key, asin in request.POST.items(): 94 | 95 | if key == "csrfmiddlewaretoken": 96 | continue 97 | 98 | # Check for validation errors 99 | if len(errors := Book.objects.book_asin_validator(asin)) > 0: 100 | for k, v in errors.items(): 101 | messages.error(request, v) 102 | return redirect("match") 103 | 104 | if not (existing_settings := Setting.objects.first()): 105 | messages.error(request, "Settings not set") 106 | return redirect("setting") 107 | 108 | # Check that asin actually returns data from audible 109 | try: 110 | helpers.validate_asin(existing_settings.api_url, asin) 111 | except ValueError: 112 | messages.error(request, "Bad ASIN: " + asin) 113 | return redirect("match") 114 | 115 | original_path = Path(key) 116 | if not helpers.get_directory(original_path): 117 | messages.error(request, f"No supported files in {original_path}") 118 | continue 119 | 120 | logger.info(f"Making models and merging files for: {original_path}") 121 | 122 | book = create_book(asin, original_path) 123 | created_books = True 124 | 125 | logger.info(f"Adding book {book} to processing queue") 126 | m4b_merge_task.delay(asin) 127 | 128 | if created_books: 129 | return redirect("books") 130 | else: 131 | return redirect("match") 132 | 133 | 134 | class AsinSearch(View): 135 | def get(self, request): 136 | accepted_keywords = ["media_dir", "title", "author", "keywords"] 137 | 138 | if any(key not in accepted_keywords for key in request.GET.keys()): 139 | return HttpResponseBadRequest( 140 | f"'{', '.join(request.GET.keys() - accepted_keywords)}' are not valid parameters. \ 141 | Valid search parameters are {accepted_keywords}" 142 | ) 143 | 144 | return self.search( 145 | request.GET.get("media_dir"), 146 | request.GET.get("title"), 147 | request.GET.get("author"), 148 | request.GET.get("keywords") 149 | ) 150 | 151 | def search(self, media_dir: str = "", title: str = "", author: str = "", keywords: str = "") -> JsonResponse: 152 | """ 153 | Search for an album. 154 | """ 155 | # Instantiate search helper 156 | search_helper = SearchTool( 157 | filename=media_dir, title=title, author=author, keywords=keywords) 158 | 159 | # Call search API 160 | results = self.call_search_api(search_helper) 161 | 162 | # Write search result status to log 163 | if not results: 164 | logger.warn( 165 | f'No results found for query {search_helper.normalizedFileName}') 166 | return JsonResponse([], safe=False) 167 | 168 | logger.debug( 169 | f'Found {len(results)} result(s) for query "{search_helper.normalizedFileName}"') 170 | 171 | results = self.process_results(search_helper, results) 172 | 173 | return JsonResponse(results, safe=False) 174 | 175 | @staticmethod 176 | def process_results(helper: SearchTool, result) -> list[dict[str, str | int]]: 177 | """ 178 | Process the results from the API call. 179 | """ 180 | scored_results = [] 181 | # Walk the found items and gather extended information 182 | logger.debug(msg="Search results") 183 | for index, result_dict in enumerate(result): 184 | score_helper = ScoreTool( 185 | helper, index, settings.LANGUAGE_CODE, result_dict) 186 | scored_results.append(score_helper.run_score_book()) 187 | 188 | # Print separators for easy reading 189 | if index <= len(result): 190 | logger.debug("-" * 35) 191 | 192 | return sorted(scored_results, key=lambda inf: inf['score'], reverse=True) 193 | 194 | @staticmethod 195 | def call_search_api(helper: SearchTool): 196 | ''' 197 | Builds URL then calls API, returns the JSON to helper function. 198 | ''' 199 | query = helper.build_search_args() 200 | search_url = helper.build_url(query) 201 | request = requests.get(search_url) 202 | return helper.parse_api_response(request.json()) 203 | 204 | 205 | class BookListView(TemplateView): 206 | template_name = "book_tabs.html" 207 | 208 | def get(self, request): 209 | done_books = Book.objects.filter(status__status=StatusChoices.DONE).order_by( 210 | '-created_at') 211 | processing_books = Book.objects.filter( 212 | status__status=StatusChoices.PROCESSING).order_by( 213 | '-created_at') 214 | error_books = Book.objects.filter(status__status=StatusChoices.ERROR).order_by( 215 | '-created_at') 216 | 217 | return render(request, self.template_name, self.get_context_data( 218 | done_books=done_books, processing_books=processing_books, error_books=error_books)) 219 | 220 | def get_context_data(self, **kwargs) -> dict: 221 | context = {"default_view": "done"} 222 | 223 | redirect_url = self.request.META.get('HTTP_REFERER', '') 224 | if 'match' in redirect_url: 225 | context.update({"default_view": "processing"}) 226 | 227 | for key, books in filter(lambda item: 'books' in item[0], kwargs.items()): 228 | context.update( 229 | {key: list(zip(books, self.calcBookLength(list(books))))}) 230 | 231 | return context 232 | 233 | def calcBookLength(self, books: list[Book]) -> list[str]: 234 | # Calculate time object into sentence 235 | length_arr = [] 236 | for book in books: 237 | d = int( 238 | timedelta( 239 | minutes=book.runtime_length_minutes 240 | ).total_seconds() 241 | ) 242 | book_length_calc = ( 243 | f'{d//3600} hrs and {(d//60)%60} minutes' 244 | ) 245 | length_arr.append(book_length_calc) 246 | return length_arr 247 | 248 | 249 | class SettingView(TemplateView): 250 | template_name = "setting.html" 251 | 252 | def get_context_data(self, **kwargs): 253 | existing_settings = Setting.objects.first() 254 | default_data = { 255 | 'api_url': 'https://api.audnex.us', 256 | 'completed_directory': '/input/done', 257 | 'input_directory': '/input', 258 | 'num_cpus': 0, 259 | 'output_directory': '/output', 260 | 'output_scheme': 'author/title/title - subtitle' 261 | } 262 | if existing_settings: 263 | form = SettingForm(instance=existing_settings) 264 | else: 265 | form = SettingForm(initial=default_data) 266 | all_settings = Setting.objects.first() 267 | 268 | context = { 269 | "form": form, 270 | "settings": all_settings, 271 | } 272 | return context 273 | 274 | def post(self, request): 275 | existing_settings = Setting.objects.first() 276 | 277 | form = SettingForm(request.POST) 278 | if form.is_valid(): 279 | paths_to_check = [ 280 | 'completed_directory', 281 | 'input_directory', 282 | 'output_directory' 283 | ] 284 | form_data = form.cleaned_data 285 | 286 | # Check file path validity 287 | for path in paths_to_check: 288 | errors = Setting.objects.file_path_validator(form_data[path]) 289 | if len(errors) > 0: 290 | for k, v in errors.items(): 291 | messages.error(request, v) 292 | return redirect("setting") 293 | if not existing_settings: 294 | settings = Setting.objects.create( 295 | api_url=form_data['api_url'], 296 | completed_directory=form_data['completed_directory'], 297 | input_directory=form_data['input_directory'], 298 | num_cpus=form_data['num_cpus'], 299 | output_directory=form_data['output_directory'], 300 | output_scheme=form_data['output_scheme'] 301 | ) 302 | settings.save() 303 | else: 304 | es = existing_settings 305 | es.api_url = form_data['api_url'] 306 | es.completed_directory = form_data['completed_directory'] 307 | es.input_directory = form_data['input_directory'] 308 | es.num_cpus = form_data['num_cpus'] 309 | es.output_directory = form_data['output_directory'] 310 | es.output_scheme = form_data['output_scheme'] 311 | es.save() 312 | 313 | return redirect("import") 314 | 315 | messages.error(request, "Form is invalid") 316 | return redirect("setting") 317 | -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import shutil 5 | import subprocess 6 | import sys 7 | from django.core.management.utils import get_random_secret_key 8 | 9 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 10 | BASE_DIR = os.path.dirname(os.path.abspath(__file__)) 11 | 12 | # config section for docker 13 | if os.path.isdir("/config"): 14 | CONFIG_DIR = os.path.abspath("/config") 15 | else: 16 | CONFIG_DIR = os.path.join(BASE_DIR, 'config') 17 | os.makedirs(CONFIG_DIR, exist_ok=True) 18 | 19 | SECRET_PATH = os.path.join(CONFIG_DIR, 'secret_key.txt') 20 | 21 | # Init django secret and DB 22 | if not os.path.exists(SECRET_PATH): 23 | f = open(SECRET_PATH, "w") 24 | f.write(get_random_secret_key()) 25 | f.close() 26 | python_bin = shutil.which('m4b-tool') 27 | subprocess.run([python_bin, "manage.py", "makemigrations"]) 28 | subprocess.run([python_bin, "manage.py", "migrate"]) 29 | 30 | 31 | def main(): 32 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bragibooks_proj.settings') 33 | try: 34 | from django.core.management import execute_from_command_line 35 | except ImportError as exc: 36 | raise ImportError( 37 | "Couldn't import Django. Are you sure it's installed and " 38 | "available on your PYTHONPATH environment variable? Did you " 39 | "forget to activate a virtual environment?" 40 | ) from exc 41 | execute_from_command_line(sys.argv) 42 | 43 | 44 | if __name__ == '__main__': 45 | main() 46 | -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "baseBranches": ["develop"], 3 | "branchConcurrentLimit": 10, 4 | "commitMessageAction": "Upgrade", 5 | "commitMessagePrefix": "chore:", 6 | "commitMessageTopic": "{{depName}}", 7 | "extends": ["config:base"], 8 | "labels": ["dependencies"], 9 | "lockFileMaintenance": { 10 | "enabled": true, 11 | "automerge": true, 12 | "automergeType": "pr", 13 | "platformAutomerge": true 14 | }, 15 | "packageRules": [ 16 | { 17 | "description": "Automatically merge minor and patch-level updates", 18 | "matchUpdateTypes": ["minor", "digest", "patch", "pin"], 19 | "automerge": true, 20 | "automergeType": "branch" 21 | } 22 | ], 23 | "rebaseWhen": "auto", 24 | "stabilityDays": 5, 25 | "timezone": "Etc/UTC", 26 | "vulnerabilityAlerts": { 27 | "labels": ["security"] 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | celery>=5.2 2 | Django>=4.2 3 | gunicorn>=20.1.0 4 | kombu==5.3.7 # this has the latest update needed to use sqlalchemy>=2.0 5 | Levenshtein==0.25.1 6 | requests>=2.28 7 | sqlalchemy>=2.0.0 # for celery to use sqlite as broker 8 | whitenoise==6.7.0 -------------------------------------------------------------------------------- /utils/__init__.py: -------------------------------------------------------------------------------- 1 | available_regions = { 2 | 'au': { 3 | 'name': 'Australia', 4 | 'TLD': 'com.au', 5 | }, 6 | 'ca': { 7 | 'name': 'Canada', 8 | 'TLD': 'ca', 9 | }, 10 | 'de': { 11 | 'name': 'Germany', 12 | 'TLD': 'de', 13 | }, 14 | 'es': { 15 | 'name': 'Spain', 16 | 'TLD': 'es', 17 | }, 18 | 'fr': { 19 | 'name': 'France', 20 | 'TLD': 'fr', 21 | }, 22 | 'in': { 23 | 'name': 'India', 24 | 'TLD': 'in', 25 | }, 26 | 'it': { 27 | 'name': 'Italy', 28 | 'TLD': 'it', 29 | }, 30 | 'jp': { 31 | 'name': 'Japan', 32 | 'TLD': 'co.jp', 33 | }, 34 | 'us': { 35 | 'name': 'United States', 36 | 'TLD': 'com', 37 | }, 38 | 'uk': { 39 | 'name': 'United Kingdom', 40 | 'TLD': 'co.uk', 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /utils/merge.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | import traceback 4 | from datetime import datetime 5 | from pathlib import Path 6 | 7 | from django.conf import settings 8 | # core merge logic: 9 | from m4b_merge import audible_helper, config, helpers, m4b_helper 10 | 11 | from importer.models import (Author, Book, Narrator, Setting, Status, 12 | StatusChoices) 13 | 14 | # Get an instance of a logger 15 | logger = logging.getLogger(__name__) 16 | 17 | 18 | def set_configs(): 19 | existing_settings = Setting.objects.first() 20 | if existing_settings: 21 | config.api_url = existing_settings.api_url 22 | config.junk_dir = existing_settings.completed_directory 23 | config.num_cpus = ( 24 | existing_settings.num_cpus if existing_settings.num_cpus > 0 25 | else os.cpu_count() 26 | ) 27 | config.output = existing_settings.output_directory 28 | config.path_format = existing_settings.output_scheme 29 | 30 | 31 | def run_m4b_merge(asin: str): 32 | # Log Level 33 | env_log_level = os.environ.get("LOG_LEVEL", "INFO") 34 | logging.basicConfig(level=env_log_level) 35 | 36 | set_configs() 37 | 38 | # Log all Settings 39 | logger.debug(f'Using API URL: {config.api_url}') 40 | logger.debug(f'Using junk path: {config.junk_dir}') 41 | logger.debug(f'Using CPU cores: {config.num_cpus}') 42 | logger.debug(f'Using output path: {config.output}') 43 | logger.debug(f'Using output format: {config.path_format}') 44 | 45 | book = Book.objects.get(asin=asin) 46 | logger.info( 47 | f"{'-' * 15} Starting to process {asin}: {book.title} {'-' * 15}") 48 | 49 | input_data = helpers.get_directory(Path(book.src_path)) 50 | if not input_data: 51 | message = f"invalid input_data: {input_data} for book: {book} at path: {book.src_path}" 52 | logger.error(message) 53 | book.status.status = StatusChoices.ERROR 54 | book.status.message = message 55 | book.status.save() 56 | return 57 | 58 | audible = audible_helper.BookData(asin) 59 | 60 | # Process metadata and run components to merge files 61 | m4b = m4b_helper.M4bMerge( 62 | input_data, 63 | audible.fetch_api_data(config.api_url), 64 | Path(book.src_path), 65 | audible.get_chapters() 66 | ) 67 | 68 | try: 69 | logger.info(f"Processing {book.title}") 70 | m4b.run_merge() 71 | except Exception as e: 72 | logger.error(f"Error occured while merging '{input_data}: {e}'") 73 | book.status.status = StatusChoices.ERROR 74 | message = str(e) + "\n" + \ 75 | traceback.format_exc() if settings.DEBUG else e 76 | book.status.message = message 77 | book.status.save() 78 | return 79 | 80 | book.dest_path = Path( 81 | f"\"" 82 | f"{m4b.book_output}/" 83 | f"{audible.fetch_api_data(config.api_url)['authors'][0]}/" 84 | f"{book.title}/" 85 | f"{book.title}.m4b" 86 | f"\"" 87 | ) 88 | book.status.status = StatusChoices.DONE 89 | book.status.save() 90 | logger.info(f"{'-' * 15} Done processing {asin} {'-' * 15}") 91 | 92 | 93 | def create_book(asin, original_path) -> Book: 94 | # Make models only if book doesn't exist 95 | if not Book.objects.filter(asin=asin).exists(): 96 | book = make_book_model(asin, original_path) 97 | 98 | else: 99 | book = Book.objects.get(asin=asin) 100 | book.src_path = original_path 101 | book.save() 102 | 103 | book.status.status = StatusChoices.PROCESSING 104 | book.status.message = "" 105 | book.status.save() 106 | logger.warning("Book already exists in database, only merging files") 107 | 108 | return book 109 | 110 | 111 | def make_book_model(asin, original_path) -> Book: 112 | set_configs() 113 | # Create BookData object from asin response 114 | metadata = audible_helper.BookData(asin).fetch_api_data(config.api_url) 115 | 116 | # Book DB entry 117 | if 'subtitle' in metadata: 118 | base_title = metadata['title'] 119 | base_subtitle = metadata['subtitle'] 120 | title = f"{base_title} - {base_subtitle}" 121 | else: 122 | title = metadata['title'] 123 | 124 | if 'runtimeLengthMin' in metadata: 125 | runtime = metadata['runtimeLengthMin'] 126 | else: 127 | runtime = 0 128 | 129 | status = Status.objects.create(status=StatusChoices.PROCESSING) 130 | 131 | book = Book.objects.create( 132 | title=title, 133 | asin=asin, 134 | short_desc=metadata['description'], 135 | long_desc=metadata['summary'], 136 | release_date=datetime.strptime( 137 | metadata['releaseDate'], '%Y-%m-%dT%H:%M:%S.%fZ'), 138 | publisher=metadata['publisherName'], 139 | lang=metadata['language'], 140 | runtime_length_minutes=runtime, 141 | format_type=metadata['formatType'], 142 | converted=True, 143 | status=status, 144 | cover_image_link=metadata['image'], 145 | src_path=original_path 146 | ) 147 | 148 | # Only add in series if it exists 149 | if 'primarySeries' in metadata: 150 | book.series = metadata['primarySeries']['name'] 151 | book.save() 152 | 153 | make_author_model(book, metadata['authors']) 154 | make_narrator_model(book, metadata['narrators']) 155 | 156 | return book 157 | 158 | 159 | def make_author_model(book, authors: list[dict[str, str]]): 160 | # Author DB entry 161 | # Create new entry for each author if there's more than one 162 | for author in authors: 163 | author_name_full = author['name'] 164 | author_name_split = author_name_full.split() 165 | last_name_index = len(author_name_split) - 1 166 | 167 | # Check if author asin exists 168 | if 'asin' in author: 169 | author_asin = author['asin'] 170 | _filter_vals = {'asin': author_asin} 171 | 172 | # If author doesn't exist, search by name and set asin to none 173 | else: 174 | author_asin = None 175 | _filter_vals = { 176 | 'first_name': author_name_split[0], 177 | 'last_name': author_name_split[last_name_index] 178 | } 179 | logger.warning( 180 | f"No author ASIN for: " 181 | f"{author_name_full}" 182 | ) 183 | 184 | # Check if author is in database 185 | if not (author := Author.objects.filter(**_filter_vals).first()): 186 | logger.info( 187 | f"Using existing db entry for author: " 188 | f"{author_name_full}" 189 | ) 190 | author = Author.objects.create( 191 | asin=author_asin, 192 | first_name=author_name_split[0], 193 | last_name=author_name_split[last_name_index] 194 | ) 195 | 196 | author.books.add(book) 197 | author.save() 198 | 199 | 200 | def make_narrator_model(book, narrators: list[dict[str, str]]): 201 | # Narrator DB entry 202 | # Create new entry for each narrator if there's more than one 203 | for narrator in narrators: 204 | 205 | narr_name_split = narrator['name'].split() 206 | last_name_index = len(narr_name_split) - 1 207 | 208 | if not (narrator := Narrator.objects.filter( 209 | first_name=narr_name_split[0], 210 | last_name=narr_name_split[last_name_index] 211 | ).first()): 212 | narrator = Narrator.objects.create( 213 | first_name=narr_name_split[0], 214 | last_name=narr_name_split[last_name_index] 215 | ) 216 | 217 | narrator.books.add(book) 218 | narrator.save() 219 | -------------------------------------------------------------------------------- /utils/region_tools.py: -------------------------------------------------------------------------------- 1 | from utils import available_regions 2 | 3 | 4 | class RegionTool: 5 | """ 6 | Used to generate URLs for different regions for both Audible and Audnexus. 7 | 8 | Parameters 9 | ---------- 10 | type : str 11 | The base type, e.g. 'authors' or 'books' 12 | id : str, optional 13 | The ASIN of the item to lookup. Can be None. 14 | query : str, optional 15 | Any additional query parameters to add to the URL. Can be None. 16 | Must be pre-formatted for Audnexus, e.g. '&page=1&limit=10' 17 | region : str 18 | The region code to generate the URL for. 19 | """ 20 | 21 | def __init__(self, region: str, content_type: str = 'books', id: str = '', query: str = ''): 22 | self.region = region 23 | self.content_type = content_type 24 | self.id = id 25 | self.query = query 26 | 27 | # Audnexus 28 | def get_region_query(self): 29 | """ 30 | Returns the region query string. 31 | """ 32 | return '?region=' + self.region 33 | 34 | def get_content_type_url(self): 35 | """ 36 | Returns the content type URL. 37 | """ 38 | return 'https://api.audnex.us' + '/' + self.content_type 39 | 40 | # Audible 41 | def get_api_region_url(self): 42 | """ 43 | Returns the API region URL. 44 | """ 45 | return 'https://api.audible.{}'.format( 46 | available_regions[self.region]['TLD'] 47 | ) 48 | 49 | def get_api_params(self): 50 | """ 51 | Returns the API parameters. 52 | """ 53 | return ( 54 | '?response_groups=contributors,product_desc,product_attrs,media' 55 | '&num_results=25&products_sort_by=Relevance' 56 | ) 57 | 58 | def get_api_search_url(self): 59 | """ 60 | Returns the API search URL. 61 | """ 62 | return self.get_api_region_url() + '/' + '1.0/catalog/products' + self.get_api_params() + '&' + self.query 63 | -------------------------------------------------------------------------------- /utils/search_tools.py: -------------------------------------------------------------------------------- 1 | # Import internal tools 2 | import logging 3 | import os 4 | import re 5 | import unicodedata 6 | import urllib.parse 7 | from functools import reduce 8 | 9 | from django.conf import settings 10 | from Levenshtein import distance 11 | 12 | from .region_tools import RegionTool 13 | 14 | # Setup logger 15 | logger = logging.getLogger(__name__) 16 | 17 | 18 | class SearchTool: 19 | def __init__(self, filename: str, title: str = "", author: str = "", keywords: str = "", region_override: str = ""): 20 | self.filename = filename 21 | self.title = title 22 | self.author = author 23 | self.keywords = keywords 24 | self.normalizedFileName = "" 25 | self.region = region_override or os.environ.get("REGION", "us") 26 | 27 | def build_search_args(self) -> str: 28 | """ 29 | Builds the search arguments for the API call. 30 | """ 31 | # First, normalize the name 32 | if not self.title and not self.author and not self.keywords: 33 | self.normalizedFileName = self.normalize_name(self.filename) 34 | 35 | query = [] 36 | 37 | if self.normalizedFileName or self.keywords: 38 | query.append( 39 | 'keywords=' + urllib.parse.quote(self.normalizedFileName or self.keywords)) 40 | 41 | if self.title: 42 | query.append('title=' + urllib.parse.quote(self.title)) 43 | 44 | if self.author: 45 | query.append('author=' + urllib.parse.quote(self.author)) 46 | 47 | if not query: 48 | return "" 49 | 50 | return "&".join(query) 51 | 52 | def normalize_name(self, name) -> str: 53 | """ 54 | Normalizes the album name by removing 55 | unwanted characters and words. 56 | """ 57 | # Get name from either album or title 58 | logger.debug('Input Name: %s', name) 59 | 60 | # Remove Diacritics 61 | name = self.remove_diacritics(name) 62 | # Remove file extension 63 | name = re.sub(r'\.\w+$', '', name) 64 | # Remove number prefix 65 | name = re.sub(r'^\d+\s', '', name) 66 | # Remove brackets and text inside 67 | name = re.sub(r'\[[^"]*\]', '', name) 68 | # Remove unwanted characters 69 | name = re.sub(r'[^\w\s]', '', name) 70 | # Remove unwanted words 71 | name = re.sub(r'\b(official|audiobook|unabridged|abridged|mp3|m4b)\b', 72 | '', name, flags=re.IGNORECASE) 73 | # Remove unwanted whitespaces 74 | name = re.sub(r'\s+', ' ', name) 75 | # Remove leading and trailing whitespaces 76 | name = name.strip() 77 | 78 | logger.debug(f'Normalized Name: {name}') 79 | 80 | return name 81 | 82 | def build_url(self, query): 83 | """ 84 | Generates the URL string with search paramaters for API call. 85 | """ 86 | # Setup region helper to get search URL 87 | region_helper = RegionTool(region=self.region, query=query) 88 | 89 | search_url = region_helper.get_api_search_url() 90 | 91 | logger.debug('Search URL: %s', search_url) 92 | 93 | return search_url 94 | 95 | def parse_api_response(self, api_response: dict[str, list[dict]]) -> list[dict[str, str | int]]: 96 | """ 97 | Collects keys used for each item from API response, 98 | for Plex search results. 99 | """ 100 | search_results = [] 101 | for item in api_response['products']: 102 | # Only append results which have valid keys 103 | if item.keys() >= { 104 | "asin", 105 | "authors", 106 | "language", 107 | "narrators", 108 | "release_date", 109 | "title", 110 | "product_images" 111 | }: 112 | search_results.append( 113 | { 114 | 'asin': item['asin'], 115 | 'author': item['authors'], 116 | 'date': item['release_date'], 117 | 'language': item['language'], 118 | 'narrator': item['narrators'], 119 | 'region': self.region, 120 | 'title': item['title'], 121 | 'product_images': item['product_images'] 122 | } 123 | ) 124 | return search_results 125 | 126 | @staticmethod 127 | def remove_diacritics(s): 128 | nkfd_form = unicodedata.normalize('NFKD', str(s)) 129 | return u"".join([c for c in nkfd_form if not unicodedata.combining(c)]) 130 | 131 | 132 | class ScoreTool: 133 | # Starting value for score before deductions are taken. 134 | INITIAL_SCORE = 100 135 | 136 | def __init__( 137 | self, 138 | helper: SearchTool, 139 | index, 140 | locale, 141 | result_dict, 142 | year=None 143 | ): 144 | self.helper: SearchTool = helper 145 | self.index = index 146 | self.english_locale = locale 147 | self.result_dict = result_dict 148 | self.year = year 149 | 150 | def reduce_string(self, string: str): 151 | """ 152 | Reduces a string to lowercase and removes 153 | punctuation and spaces. 154 | """ 155 | normalized = string \ 156 | .lower() \ 157 | .replace("-", "") \ 158 | .replace(' ', '') \ 159 | .replace('.', '') \ 160 | .replace(',', '') 161 | return normalized 162 | 163 | def run_score_book(self): 164 | """ 165 | Scores a book result. 166 | """ 167 | self.asin = self.result_dict['asin'] 168 | self.authors_concat = ', '.join( 169 | author['name'] for author in self.result_dict['author'] 170 | ) 171 | self.author = self.result_dict['author'][0]['name'] 172 | self.date = self.result_dict['date'] 173 | self.language = self.result_dict['language'].title() 174 | self.narrator = self.result_dict['narrator'][0]['name'] 175 | self.region = self.result_dict['region'] 176 | self.title = self.result_dict['title'] 177 | self.image_link = list(self.result_dict['product_images'].values()) 178 | return self.score_result() 179 | 180 | def sum_scores(self, numberlist): 181 | """ 182 | Sums a list of numbers. 183 | """ 184 | # Because builtin sum() isn't available 185 | return reduce( 186 | lambda x, y: x + y, numberlist, 0 187 | ) 188 | 189 | def score_create_result(self, score) -> dict[str, str]: 190 | """ 191 | Creates a result dict for the score. 192 | Logs the score and the data used to calculate it. 193 | """ 194 | data_to_logger = [] 195 | score_dict = {} 196 | 197 | # Go through all the keys for the result and log as we go 198 | if self.asin: 199 | score_dict['asin'] = self.asin 200 | data_to_logger.append({'ASIN is': self.asin}) 201 | if self.author: 202 | score_dict['author'] = self.author 203 | data_to_logger.append({'Author is': self.author}) 204 | if self.date: 205 | score_dict['date'] = self.date 206 | data_to_logger.append({'Date is': self.date}) 207 | if self.narrator: 208 | score_dict['narrator'] = self.narrator 209 | data_to_logger.append({'Narrator is': self.narrator}) 210 | if self.region: 211 | score_dict['region'] = self.region 212 | data_to_logger.append({'Region is': self.region}) 213 | if score is not None: 214 | score_dict['score'] = score 215 | data_to_logger.append({'Score is': str(score)}) 216 | if self.title: 217 | score_dict['title'] = self.title 218 | data_to_logger.append({'Title is': self.title}) 219 | if self.year: 220 | score_dict['year'] = self.year 221 | data_to_logger.append({'Year is': self.year}) 222 | if self.image_link: 223 | score_dict['image_link'] = self.image_link 224 | data_to_logger.append({'Image Link is': self.image_link}) 225 | 226 | logger.debug(data_to_logger) 227 | return score_dict 228 | 229 | def score_result(self): 230 | """ 231 | Scores a result. 232 | """ 233 | # Array to hold score points for processing 234 | all_scores = [] 235 | 236 | # Album name score 237 | if self.title: 238 | title_score = self.score_album(self.title) 239 | if title_score: 240 | all_scores.append(title_score) 241 | # Author name score 242 | if self.authors_concat: 243 | author_score = self.score_author(self.authors_concat) 244 | if author_score: 245 | all_scores.append(author_score) 246 | # Library language score 247 | if self.language: 248 | lang_score = self.score_language(self.language) 249 | if lang_score: 250 | all_scores.append(lang_score) 251 | 252 | # Subtract difference from initial score 253 | # Subtract index to use Audible relevance as weight 254 | score = self.INITIAL_SCORE - self.sum_scores(all_scores) - self.index 255 | 256 | logger.debug(f"Result #{self.index + 1}, Score: {score}") 257 | 258 | # Create result dict 259 | return self.score_create_result(score) 260 | 261 | def score_album(self, title: str): 262 | """ 263 | Compare the input album similarity to the search result album. 264 | Score is calculated with LevenshteinDistance 265 | """ 266 | scorebase1 = self.helper.title or self.helper.filename 267 | if not scorebase1: 268 | logger.error('No album title found in file metadata') 269 | return 50 270 | scorebase2 = title # .encode('utf-8') 271 | album_score = distance( 272 | self.reduce_string(scorebase1), 273 | self.reduce_string(scorebase2) 274 | ) * 2 275 | logger.debug("Score deduction from album: " + str(album_score)) 276 | return album_score 277 | 278 | def score_author(self, author: str): 279 | """ 280 | Compare the input author similarity to the search result author. 281 | Score is calculated with LevenshteinDistance 282 | """ 283 | if not self.helper.author: 284 | logger.debug(f'No author found in file metadata for {self.title} - {self.asin}') 285 | return 20 286 | 287 | scorebase3 = self.helper.author 288 | scorebase4 = author 289 | author_score = distance( 290 | self.reduce_string(scorebase3), 291 | self.reduce_string(scorebase4) 292 | ) * 10 293 | logger.debug("Score deduction from author: " + str(author_score)) 294 | return author_score 295 | 296 | def score_language(self, language: str): 297 | """ 298 | Compare the library language to search results 299 | and knock off 2 points if they don't match. 300 | """ 301 | lang_dict = { 302 | self.english_locale: 'English', 303 | 'de': 'German', 304 | 'es': 'Spanish', 305 | 'fr': 'French', 306 | 'it': 'Italian', 307 | 'ja': 'Japanese', 308 | } 309 | 310 | if language != lang_dict[settings.LANGUAGE_CODE]: 311 | logger.debug( 312 | 'Audible language: %s; Library language: %s', 313 | language, 314 | lang_dict[settings.LANGUAGE_CODE] 315 | ) 316 | logger.debug("Book is not library language, deduct 2 points") 317 | return 2 318 | return 0 319 | --------------------------------------------------------------------------------