Compare commits

..

6 Commits

Author SHA1 Message Date
IRHM 1e7702b16b docker/ui-build: Add doc link to readme 2025-02-28 23:50:56 +00:00
IRHM fa2a4a40d0 doc: Create docker-compose-subpath installation guide 2025-02-28 23:46:57 +00:00
IRHM 203e4a31ef doc: Remove docsVersionDropdown from nav
Was going to version doc, but never did and don't want to anymore.. doc site will only support latest version of watcharr.

If anyone needs an older version for any reason, can always browse through them in specific git tag.
2025-02-28 23:03:57 +00:00
IRHM 5f2c1977ee Create toBaseUrl and use everywhere we navigate
Simply prefixes the absolute paths we use for internal navigations with the `base` variable set when the app was built.
2025-02-28 22:48:34 +00:00
IRHM 5860fd2783 ui-build compose: Add name to volume
and use latest prod image in ui-replace compose test
2025-02-28 21:11:55 +00:00
IRHM 3c2cbf55c6 new ui-build image, WATCHARR_BASE env var for svelte cfg, rename compose files 2025-02-25 22:58:59 +00:00
377 changed files with 31216 additions and 44684 deletions
+3 -2
View File
@@ -1,2 +1,3 @@
server/data/
server/Makefile
# Docker dev volume
container_data/
data/
+15
View File
@@ -0,0 +1,15 @@
.DS_Store
node_modules
/build
/.svelte-kit
/package
.env
.env.*
!.env.example
/doc
# Ignore files for PNPM, NPM and YARN
pnpm-lock.yaml
package-lock.json
yarn.lock
+27
View File
@@ -0,0 +1,27 @@
module.exports = {
root: true,
parser: "@typescript-eslint/parser",
extends: ["plugin:svelte/recommended"],
plugins: ["@typescript-eslint"],
ignorePatterns: ["*.cjs", "*.config.js"],
overrides: [
{
files: ["*.svelte"],
parser: "svelte-eslint-parser",
parserOptions: {
parser: "@typescript-eslint/parser",
},
},
],
parserOptions: {
project: "./tsconfig.json",
extraFileExtensions: [".svelte"],
sourceType: "module",
ecmaVersion: 2020,
},
env: {
browser: true,
es2017: true,
node: false,
},
};
-2
View File
@@ -1,7 +1,5 @@
<!-- Make sure your code is formatted by running `npm run format` or using prettier manually. -->
<!-- AI Disclosure: <If you used AI to write the code, please disclose it by uncommenting this line and describing the usage. If AI wrote any of the code, do you fully understand it?> -->
### Changes made
<!-- Describe changes made here. If changes are visual a screenshot could be useful! -->
+27
View File
@@ -0,0 +1,27 @@
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
version: 2
updates:
# Web UI
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "weekly"
commit-message:
prefix: "ui"
# Server
- package-ecosystem: "gomod"
directory: "/server"
schedule:
interval: "weekly"
commit-message:
prefix: "server"
# Workflows
- package-ecosystem: "github-actions"
directory: "/" # / will look in /.github/workflows directory by default
schedule:
interval: "weekly"
commit-message:
prefix: "workflow"
+6 -6
View File
@@ -19,29 +19,29 @@ jobs:
steps:
- name: Checkout Repo
uses: actions/checkout@v7.0.0
uses: actions/checkout@v4
- name: Set up QEMU
uses: docker/setup-qemu-action@v4.2.0
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4.2.0
uses: docker/setup-buildx-action@v3
- name: Log in to GitHub Container Registry
uses: docker/login-action@v4.4.0
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Login to Docker Hub
uses: docker/login-action@v4.4.0
uses: docker/login-action@v3
with:
username: sbondco
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build and push Docker image
uses: docker/build-push-action@v7.3.0
uses: docker/build-push-action@v6
with:
context: .
file: ./Dockerfile
+7 -7
View File
@@ -18,37 +18,37 @@ jobs:
steps:
- name: Checkout Repo
uses: actions/checkout@v7.0.0
uses: actions/checkout@v4
- name: Set up QEMU
uses: docker/setup-qemu-action@v4.2.0
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4.2.0
uses: docker/setup-buildx-action@v3
- name: Log in to GitHub Container Registry
uses: docker/login-action@v4.4.0
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Login to Docker Hub
uses: docker/login-action@v4.4.0
uses: docker/login-action@v3
with:
username: sbondco
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@v6.2.0
uses: docker/metadata-action@v5
with:
images: |
${{ env.image }}
ghcr.io/${{ env.image }}
- name: Build and push Docker image
uses: docker/build-push-action@v7.3.0
uses: docker/build-push-action@v6
with:
context: .
file: ./Dockerfile
+4 -4
View File
@@ -21,10 +21,10 @@ jobs:
run:
working-directory: doc
steps:
- uses: actions/checkout@v7.0.0
- uses: actions/setup-node@v7.0.0
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 24
node-version: 18
cache: npm
- name: Install dependencies
@@ -35,7 +35,7 @@ jobs:
# Popular action to deploy to GitHub Pages:
# Docs: https://github.com/peaceiris/actions-gh-pages#%EF%B8%8F-docusaurus
- name: Deploy to GitHub Pages
uses: peaceiris/actions-gh-pages@v4.1.0
uses: peaceiris/actions-gh-pages@v4
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
# Build output to publish to the `gh-pages` branch:
+3 -3
View File
@@ -16,10 +16,10 @@ jobs:
run:
working-directory: doc
steps:
- uses: actions/checkout@v7.0.0
- uses: actions/setup-node@v7.0.0
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 24
node-version: 18
cache: npm
- name: Install dependencies
+3 -13
View File
@@ -11,22 +11,12 @@ on:
- "server/**"
jobs:
test_and_format_check_go:
format_check_go:
runs-on: ubuntu-latest
defaults:
run:
working-directory: server
steps:
- uses: actions/checkout@v7.0.0
- uses: actions/setup-go@v7.0.0
with:
go-version-file: "server/go.mod"
- name: go test all packages
run: go test ./...
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
- name: gofmt test
run: |
+3 -3
View File
@@ -21,12 +21,12 @@ jobs:
steps:
- name: Checkout repo
uses: actions/checkout@v7.0.0
uses: actions/checkout@v4
- name: Setup Node
uses: actions/setup-node@v7.0.0
uses: actions/setup-node@v4
with:
node-version: 24
node-version: "20"
cache: "npm"
- name: Get dependencies
-2
View File
@@ -1,3 +1 @@
engine-strict=true
ignore-scripts=true
min-release-age=14
-1912
View File
File diff suppressed because it is too large Load Diff
+1 -7
View File
@@ -4,14 +4,8 @@ First of all, thank you for looking into contributing! 🫡
Feel free to contribute in any way: 🐞 bug reports, 💡 ideas, 🥖 new features etc - everything is welcome!
Big pull requests (anything more than a few lines) should be discussed first in an issue (dont want to waste anyones time!).
For big PRs (lots of changes/big change in the way something works), if you'd like, it can be discussed first in an issue (dont want to waste anyones time!).
## Project Board
We have a [board to organize new features and bug fixes](https://github.com/orgs/sbondCo/projects/9/views/2) to be worked on. If you see something you'd like to work on, just ask in the issue and it can be assigned to you. Even if it isn't set for the next milestone already, it can be.
## AI
If you use AI, please disclose the usage in your pull request.
Fully understanding any code that is submitted is a must because someone's gotta understand it!
+7 -8
View File
@@ -1,13 +1,12 @@
#
# Backend
#
FROM golang:1.26-alpine AS server
FROM golang:1.22-alpine AS server
WORKDIR /server
# We can copy the whole server folder, since our .dockerignore file
# will filter out stuff we don't want in the final image.
COPY server/ ./
COPY server/*.go server/go.* ./
COPY server/arr/*.go ./arr/
COPY server/game/*.go ./game/
# Required so we can build with cgo
RUN apk update && apk add --no-cache musl-dev gcc build-base
@@ -18,7 +17,7 @@ RUN go mod download && GOOS=linux CGO_ENABLED=1 CGO_CFLAGS="-D_LARGEFILE64_SOURC
#
# Frontend
#
FROM node:24-alpine AS ui
FROM node:20-alpine AS ui
WORKDIR /app
COPY package*.json vite.config.ts svelte.config.js tsconfig.json ./
@@ -30,11 +29,11 @@ RUN npm install && npm run build
#
# Production
#
FROM node:24-alpine AS runner
FROM node:20-alpine AS runner
COPY --from=server /server/watcharr /
COPY --from=ui /app/build /ui
COPY --from=ui /app/package.json /app/package-lock.json /ui/
COPY --from=ui /app/package.json /app/package-lock.json /ui
# Install just the prod dependencies for final step.
# We --ignore-scripts, to stop the `prepare` script from auto-
-59
View File
@@ -1,59 +0,0 @@
# Watcharr Features
A basic top-level view of the features included in Watcharr.
When the word `watched` is used, assume it can be `played` for games too.
**NOTE:** Have a look at when this document was last updated, it may have missing features. This document was made years after starting the project, so I have no doubt I've missed some stuff, this is a good overview anyways.
- Watched List
- Supported Content:
- Movies
- TV Shows / Anime
- Seasons
- Episodes
- Games
- Filtering
- Sorting
- Pinning
- Thoughts (for writing a review, etc)
- Activity (detailed list of modifications made to each watched item)
- Importing from other services
- Content detail pages
- Basic overview
- Watch trailer
- Available streaming providers in your region
- Cast
- Similar content
- List of all seasons and their episodes (for tv shows).
- Person detail pages
- Basic overview
- All credits (movies & tv they appear in or worked on)
- Searching for media
- Inline filters (ex: `y:2008` to get media released in 2008)
- Custom tags
- Discovery page
- Following other users
- Simple user stats (movies watched, time spent watching, etc)
- User Settings
- Dark & Light themes
- Privacy
- Hide Spoilers
- Rating System
- Out of 5
- Out of 10
- Out of 100
- Rating Step
- And more generic settings..
- Server dashboard
- Basic stats
- Configuration editing
- User management (including permissions)
- Jellyfin Integration
- Auth
- 'Play On Jellyfin' buttons
- Plex Integration
- Trusted Header Authentication (for auth via proxy)
- Basic Sonarr & Radarr integration
- Let users Request content (users can be given an auto approve permission)
- Manage content requests
+21 -674
View File
@@ -1,674 +1,21 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
MIT License
Copyright (c) 2023 IRHM
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-16
View File
@@ -1,16 +0,0 @@
.PHONY: dev version
dev:
./node_modules/.bin/vite dev
dev_host:
./node_modules/.bin/vite dev --host
# Don't judge me.
version:
@$(eval VER := $(filter-out $@,$(MAKECMDGOALS)))
@echo "Updating version to $(VER)"
echo -n "$(VER)" > ./server/VERSION
npm version $(VER) --git-tag-version false
%:
@:
+3 -20
View File
@@ -16,19 +16,9 @@ With [some extra configuration](https://watcharr.app/docs/server_config/game-sup
I am built with Go and Svelte(Kit).
### Demo
Feel free to abuse this demo instance (nicely), which runs on the latest `dev` build (there may be bugs, as new features are tested on here too): [https://beta.watcharr.app/](https://beta.watcharr.app/)
Feel free to abuse this demo instance (nicely). It runs on the latest `dev` build so there may be bugs, as new features are tested on here too. The demo is a worst-case scenario for speed (which is why I like it as a testing ground), if you host it yourself the app will be snappy.
Demo: [https://beta.watcharr.app/](https://beta.watcharr.app/)
**NOTE:** There is no demo account, just type in a random username/password (smashing hand into keyboard is supported), then click `Not a user?` at the bottom and a `Sign Up` button will appear.
### Track new features
Most patches are tracked through [our project board](https://github.com/orgs/sbondCo/projects/9/views/3), though I am very unorganised so expect surprise updates (or don't, if you like surprises)!
You can also [view a list of all current features](FEATURES.md).
[Track progress for the next version](https://github.com/orgs/sbondCo/projects/9/views/3).
### Contents
@@ -36,7 +26,6 @@ You can also [view a list of all current features](FEATURES.md).
- [Set Up](#set-up)
- [Community Made Tools](#community-made-tools)
- [Getting Help](#getting-help)
- [License](#license)
- [Contributing](#contributing)
# Screenshots
@@ -65,7 +54,7 @@ You can also [view a list of all current features](FEATURES.md).
# Set Up
[Checkout our documentation](https://watcharr.app/docs/category/installation) for an up to date guide on setup! If you hate manuals, but love docker, this [docker-compose.yml](./docker-compose.yml) file is your friend.
[Checkout our documentation](https://watcharr.app/docs/category/installation) for an up to date guide on setup! If you hate manuals, but love docker, this [compose.yml](./compose.yml) file is your friend.
# Community Made Tools
@@ -83,12 +72,6 @@ If something isn't working for you or you are stuck, [creating an issue](https:/
You can also [join our space on Matrix](https://matrix.to/#/#watcharr:matrix.org) for support.
I'll do my best to reply!
# License
This project is licensed under the GPLv3 license. You should see the [LICENSE](LICENSE) file located in the root folder of this project for the full license text, if not, see <https://www.gnu.org/licenses/>.
# Contributing
Please continue to our [contributing guide](CONTRIBUTING.md).
Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 284 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 273 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 878 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 360 KiB

-5
View File
@@ -1,5 +0,0 @@
## Changelog Data
Changelog images, etc go in this folder.
[View the real changelog for Watcharr.](../CHANGELOG.md)
+24
View File
@@ -0,0 +1,24 @@
# This compose file will replace watcharrs
# built in UI with a custom one provided in
# a named volume (for use with ui-build image).
services:
watcharr:
# We dont need to build here too for testing if
# a custom ui works, so using latest prod image.
image: ghcr.io/sbondco/watcharr:latest
container_name: watcharr
ports:
- 3080:3080
volumes:
- ./container_data:/data
- type: volume
source: watcharr-ui
target: /ui
volume:
nocopy: true
subpath: build
volumes:
watcharr-ui:
external: true
+2 -2
View File
@@ -4,8 +4,8 @@ services:
build:
context: .
dockerfile: Dockerfile
container_name: watcharr-dev
container_name: watcharr
ports:
- 3081:3080
- 3080:3080
volumes:
- ./container_data:/data
View File
+1 -1
View File
@@ -1,5 +1,5 @@
---
sidebar_position: 2
sidebar_position: 1
---
# MyAnimeList
-35
View File
@@ -1,35 +0,0 @@
---
sidebar_position: 1
---
# Text File (.txt list)
:::info Backup?
You may consider a backup of your server before starting any import. They are not easily reversible, though we do our best to ensure they are accurate and bug free!
:::
The text file (.txt) import is of an arbitrary format (the one I used for years before creating Watcharr).
Hopefully it is useful for others with similar files or in scenarios where its the easiest to generate for an import (though if possible, when generating a backup from another service data manually, matching a Watcharr export would enable keeping more data).
## Format
Each line is a new entry. The name of the content (show/movie) must be provided. Doesn't support specifying if name is for a show or movie, the importer will only automatically match on full search matches, if there are multiple results, you will be asked to pick the correct one.
Optionally provide:
- The year in brackets (eg: `(1983)`)
- A rating (out of 10) in square brackets (eg: `[4]` or `[6.9]`)
```
<name> [(<year>)]
```
## An example
```
The Terminator (1984)
Breaking Bad
A Fistful of Dollars
Reacher (2022)
```
-29
View File
@@ -1,29 +0,0 @@
---
sidebar_position: 3
---
# Trakt
:::info Backup?
You may consider a backup of your server before starting any import. They are not easily reversible, though we do our best to ensure they are accurate and bug free!
:::
**Note:** Your Trakt profile must be public _during_ this process. You are free to private it again once it completes.
1. Provide your Trakt username in the text box.
2. (Optional) [Provide your own api key](#optional-api-key).
3. Press `Start Import`.
This will be a long process, possibly a couple hours depending on how large of a Trakt history you have. If you think it has frozen or isn't working, try checking your server logs to see if it is doing anything.
### (Optional) API Key
This step is optional because Watcharr comes built in with its own API Key that it can use for your import, however, if you encounter any issues where imports cannot start or keep failing and you see any `403` errors in your server logs, providing your own key may fix the problem.
#### Getting an API Key
1. [Visit this link to create a new Trakt API App](https://trakt.tv/oauth/applications/new).
2. Fill out all required fields (`Name` and `Redirect uri`) with any random data.
1. You can set the `Redirect uri` to any value the input accepts since we don't use it (eg: `http://localhost`)
3. Click `Save App`.
4. You should now be redirected to your new app. Copy the `Client ID` into the `API Key` textbox in Watcharr.
-16
View File
@@ -1,16 +0,0 @@
---
sidebar_position: 0
---
# Watcharr
:::info Backup?
You may consider a backup of your server before starting any import. They are not easily reversible, though we do our best to ensure they are accurate and bug free!
:::
:::warning May not be what you want
Watcharr import/export is a feature intended for end users. If you are the server admin, it is recommended that you copy your server files directly to any new server you are creating (it'll be much faster and easier). [See backup guide](/docs/server_config/backup).
:::
1. Provide the Watcharr export file (that you generated from your profile page).
2. Review the import table, if everything looks good, start the import.
@@ -0,0 +1,104 @@
---
sidebar_position: 2
description: Install and setup with Docker Compose for access through a subpath.
---
# Docker Compose (subpath)
Install and setup with Docker Compose for access through a subpath.
:::info Not a great experience at the moment!
Currently, hosting Watcharr via a subpath on your server is not very easy (unlike hosting under a subdomain). Hopefully this will change in the future, but as a temporary measure to at least allow hosting under a subpath, this method has been provided.
The following issue will continue to track this: https://github.com/sbondCo/Watcharr/issues/312
:::
## Installing
### Build UI
First we have to build the frontend with our subpath provided as an environment variable.
If you don't want to use `/watcharr` as your subpath, replace the value of `WATCHARR_BASE` before running the command.
```bash
docker run -e WATCHARR_BASE=/watcharr -v watcharr-ui:/ui --rm ghcr.io/sbondco/watcharr-ui-build:latest
```
Once the container has finished running the build script, it will exit and remove itself. The `watcharr-ui` volume will contain the built files.
### Install Watcharr
Now we can install Watcharr. You can copy the example below to get started:
```yaml title="compose.yml"
services:
watcharr:
# The :latest tag is used for simplicity, it is recommended
# to use an actual version, then when updating check the releases for changelogs.
image: ghcr.io/sbondco/watcharr:latest
container_name: watcharr
ports:
- 3080:3080
volumes:
# Contains all of watcharr data (database & cache)
- ./data:/data
# Use our volume containing built ui files
# instead of default ui included in image.
- type: volume
source: watcharr-ui
target: /ui
volume:
nocopy: true
subpath: build
restart: unless-stopped
volumes:
watcharr-ui:
external: true
```
:::danger first account
When **first** running Watcharr, make sure only you have access. The first user created will become admin.
:::
You can now start `Watcharr` like so:
```bash
docker compose up -d
```
If you didn't change the ports in the example, the server will be available at [http://localhost:3080/](http://localhost:3080/).
## Updating
:::danger Take care
We try taking care as to not release breaking changes, however it is still recommended that
you lookover changelogs before updating!
Breaking changes are marked at the top of releases: https://github.com/sbondCo/Watcharr/releases
:::
1. Update your built ui files by following the [Build UI](#build-ui) step again.
2. Update the `image` version in your `compose.yml` file.
Skip this step if you are using the `latest` tag.
```yaml
# eg. update v1.19.0 to v1.20.0 (or whatever version you are updating to)
image: ghcr.io/sbondco/watcharr:v1.19.0
```
3. Pull the new changes and re-create your container:
```bash
docker compose pull && docker compose down && docker compose up -d
```
And that is it!
+2 -2
View File
@@ -9,7 +9,7 @@ description: Install and setup with Docker Compose.
Installing Watcharr with a docker compose file is easy. You can copy the example below to get started:
```yaml title="docker-compose.yml"
```yaml title="compose.yml"
services:
watcharr:
# The :latest tag is used for simplicity, it is recommended
@@ -51,7 +51,7 @@ Breaking changes are marked at the top of releases: https://github.com/sbondCo/W
Updating your server can be done in two steps:
1. Update the `image` version in your `docker-compose.yml` file.
1. Update the `image` version in your `compose.yml` file.
Skip this step if you are using the `latest` tag.
```yaml
+5 -7
View File
@@ -17,7 +17,7 @@ This section assumes you will be forking the repo on Github, of course you can a
![Fork button](./img/forking-repo.png)
2. Get the code by cloning your fork (edit the command and replace `<your username>` with your GitHub username or replace the whole url with the correct one pointing to your fork).
2. Get the code by cloning your fork
```bash
git clone https://github.com/<your username>/Watcharr.git && \
@@ -34,7 +34,7 @@ You only need to do this once after pulling the codebase for the first time, and
npm i
```
2. Install server dependencies (in the `server` folder). Go does this automatically if you try starting the server and it notices you don't have them.
2. Install server dependencies (in the `server` folder)
```
go get .
@@ -44,18 +44,16 @@ You only need to do this once after pulling the codebase for the first time, and
To run the code, you will need to open up two terminals, one for the frontend and the other for the backend.
We have `Makefile`s for the frontend and server, so you can simply call `make` in each directory. Most Linux distros (as far as I know) include `make`, so you don't need to install anything. If you don't have `make`, you can either install it (lookup how to get "GNU Make" for your specific OS) OR you can just look inside the Makefiles and manually run the first command in each.
1. Run the frontend (first terminal, in the project root folder)
```bash
make
npm run dev
```
2. Run the server (second terminal, in the `server` folder)
2. Run the server (second terminal, in the project root folder)
```bash
make
npm run server
```
**Note:** If you're using Windows, running the server can be a little more complicated. You can follow this: https://github.com/sbondCo/Watcharr/discussions/430#discussioncomment-8894110 which amounts to these steps (the first 3 steps only need to be done once):
+1 -1
View File
@@ -35,7 +35,7 @@ Backing up this way is discouraged because new important files could be added la
If you don't care about the warning not to backup this way, here are the "important" files that you can single out for backup:
- `watcharr.db` & `watcharr.db-wal` Your database, holds all users, their watchlists, etc.
- `watcharr.db` Your database, holds all users, their watchlists, etc.
- `watcharr.json` Server config.
- `img/up` Profile picture uploads.
- `img/games` Game posters (not exactly important, but scenarios in which this folder is not backed up have not been tested, only relevant for servers with game support enabled).
-3
View File
@@ -80,9 +80,6 @@ const config = {
position: "left",
label: "Docs",
},
{
type: "docsVersionDropdown",
},
{
href: "https://beta.watcharr.app",
label: "Demo",
+14662 -17164
View File
File diff suppressed because it is too large Load Diff
+10 -10
View File
@@ -14,17 +14,17 @@
"write-heading-ids": "docusaurus write-heading-ids"
},
"dependencies": {
"@docusaurus/core": "3.9.2",
"@docusaurus/preset-classic": "3.9.2",
"@mdx-js/react": "^3.1.1",
"clsx": "^2.1.1",
"prism-react-renderer": "^2.4.1",
"react": "^19.2.4",
"react-dom": "^19.2.4",
"viewerjs": "^1.11.7"
"@docusaurus/core": "3.1.1",
"@docusaurus/preset-classic": "3.1.1",
"@mdx-js/react": "^3.0.0",
"clsx": "^2.1.0",
"prism-react-renderer": "^2.3.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"viewerjs": "^1.11.6"
},
"devDependencies": {
"@docusaurus/module-type-aliases": "3.9.2"
"@docusaurus/module-type-aliases": "3.1.1"
},
"browserslist": {
"production": [
@@ -39,6 +39,6 @@
]
},
"engines": {
"node": ">=20.0"
"node": ">=18.0"
}
}
+8 -7
View File
@@ -1,3 +1,4 @@
import React from "react";
import clsx from "clsx";
import styles from "./styles.module.css";
@@ -7,18 +8,18 @@ const FeatureList = [
Svg: require("@site/static/img/icon/code-slash.svg").default,
description: (
<>
Free and open source, distributed under the GPLv3 license. Feel free to
browse, modify or contribute!
Watcharr is free and open source software distributed under the MIT
license. Feel free to browse, modify or contribute!
</>
),
},
{
title: "Simple & Intuitive",
title: "Simple",
Svg: require("@site/static/img/icon/happy.svg").default,
description: (
<>
Incredibly easy to dive into. Install within the minute and get started
with the seamless experience.
Watcharr is incredibly easy to dive into. Install without hassle and get
started with the seamless and intuitive user experience.
</>
),
},
@@ -27,8 +28,8 @@ const FeatureList = [
Svg: require("@site/static/img/icon/go.svg").default,
description: (
<>
Don't know what else to add here, so now you know I'm built with Go and
Svelte.
Don't know what else to add here, so now you know Watcharr is built with
Go and Svelte.
</>
),
},
+6 -11
View File
@@ -39,37 +39,32 @@ export function HomepageTwoColFeats() {
<TwoColFeat
title="Neat UI"
description="We just look lightweight."
imgSrc="https://github.com/sbondCo/Watcharr/raw/dev/screenshot/homepage.png?v=3"
imgSrc="https://github.com/sbondCo/Watcharr/raw/dev/screenshot/homepage.png?v=2"
/>
<TwoColFeat
title="Easy To Use"
description="Not much to it, other than ease of use."
imgSrc="https://github.com/sbondCo/Watcharr/raw/dev/screenshot/homepage-poster-change-status.png?v=3"
imgSrc="https://github.com/sbondCo/Watcharr/raw/dev/screenshot/homepage-poster-change-status.png?v=2"
/>
<TwoColFeat
title="In-Depth Details"
description="About your favourite content."
imgSrc="https://github.com/sbondCo/Watcharr/raw/dev/screenshot/content-details-page.png?v=3"
imgSrc="https://github.com/sbondCo/Watcharr/raw/dev/screenshot/content-details-page.png?v=2"
/>
<TwoColFeat
title="Personal Stats and Configuration"
description="Make it how you like."
imgSrc="https://github.com/sbondCo/Watcharr/raw/dev/screenshot/user-profile.png?v=3"
imgSrc="https://github.com/sbondCo/Watcharr/raw/dev/screenshot/user-profile.png?v=2"
/>
<TwoColFeat
title="Discovery"
description="Find the latest trending content."
imgSrc="https://github.com/sbondCo/Watcharr/raw/dev/screenshot/discover-page.png?v=3"
imgSrc="https://github.com/sbondCo/Watcharr/raw/dev/screenshot/discover-page.png?v=2"
/>
<TwoColFeat
title="Dark Theme"
description="For you who are still unsatisfied. ;("
imgSrc="https://github.com/sbondCo/Watcharr/raw/dev/screenshot/content-details-page-dark.png?v=3"
/>
<TwoColFeat
title="Cast & Crew"
description="What are your favorite actors up to?"
imgSrc="https://github.com/sbondCo/Watcharr/raw/dev/screenshot/person-page.png?v=3"
imgSrc="https://github.com/sbondCo/Watcharr/raw/dev/screenshot/content-details-page-dark.png?v=2"
/>
</section>
);
+3
View File
@@ -0,0 +1,3 @@
This folder is for any _extra_ images that we produce.
The main watcharr Dockerfile remains in project root.
+16
View File
@@ -0,0 +1,16 @@
#
# Frontend
#
FROM node:20-alpine AS ui
COPY ./docker/ui-build/entrypoint.sh /entrypoint.sh
RUN ["chmod", "+x", "/entrypoint.sh"]
WORKDIR /app
COPY package*.json vite.config.ts svelte.config.js tsconfig.json ./
COPY ./src ./src
COPY ./static ./static
VOLUME /ui
ENTRYPOINT ["/entrypoint.sh"]
+7
View File
@@ -0,0 +1,7 @@
Image for building watcharr ui.
Accepts environment variables:
- `WATCHARR_BASE`
https://watcharr.app/docs/installation/docker-compose-subpath
+15
View File
@@ -0,0 +1,15 @@
# To test prod
services:
watcharr-ui-build:
build:
context: ../../
dockerfile: ./docker/ui-build/Dockerfile
container_name: watcharr-ui-build
volumes:
- watcharr-ui:/ui
environment:
WATCHARR_BASE: "/sp"
volumes:
watcharr-ui:
name: "watcharr-ui"
+25
View File
@@ -0,0 +1,25 @@
#!/bin/sh
# This is loosely based on the main containers Dockerfile commands.
# Just everything needed to get ui built and ready and nothing else.
set -x
echo "wuib: Starting build"
# Install all deps
/usr/local/bin/npm install
# Run build
/usr/local/bin/npm run build
# Remove any existing build files from volume
rm -rf /ui/build
# Move build folder to /ui
mv /app/build /ui
# Move package.json and lock file to /ui/build for final npm ci call
mv /app/package.json /app/package-lock.json /ui/build
# cd to build files final destination and install dependencies for production
cd /ui/build && /usr/local/bin/npm ci --omit=dev --ignore-scripts=true
View File
-60
View File
@@ -1,60 +0,0 @@
import prettier from "eslint-config-prettier";
import path from "node:path";
import js from "@eslint/js";
import svelte from "eslint-plugin-svelte";
import { defineConfig, includeIgnoreFile } from "eslint/config";
import globals from "globals";
import ts from "typescript-eslint";
import svelteConfig from "./svelte.config.js";
const gitignorePath = path.resolve(import.meta.dirname, ".gitignore");
export default defineConfig(
includeIgnoreFile(gitignorePath),
js.configs.recommended,
ts.configs.recommended,
svelte.configs.recommended,
prettier,
svelte.configs.prettier,
{
languageOptions: {
globals: { ...globals.browser /* ...globals.node */ },
parserOptions: {
projectService: true,
parser: ts.parser,
ecmaVersion: "latest",
},
},
rules: {
// typescript-eslint strongly recommend that you do not use the no-undef lint rule on TypeScript projects.
// see: https://typescript-eslint.io/troubleshooting/faqs/eslint/#i-get-errors-from-the-no-undef-rule-about-global-variables-not-being-defined-even-though-there-are-no-typescript-errors
"no-undef": "off",
},
},
{
files: ["**/*.svelte", "**/*.svelte.ts", "**/*.svelte.js"],
languageOptions: {
parserOptions: {
extraFileExtensions: [".svelte"],
svelteConfig,
},
},
},
{
// Override or add rule settings here.
rules: {
"@typescript-eslint/no-empty-object-type": [
"error",
{
// Allowing this because it's nice to create an empty
// interface that extends a base interface for specific
// use, even if it is currently empty, incase i add stuff
// to it in the future. It's also less confusing to read
// the actual type name I want instead of the base type
// everywhere in certain scenarios.
allowInterfaces: "with-single-extends",
},
],
},
},
);
+3218 -3442
View File
File diff suppressed because it is too large Load Diff
+25 -25
View File
@@ -1,7 +1,6 @@
{
"name": "watcharr",
"license": "GPL-3.0-only",
"version": "4.2.1",
"version": "2.0.2",
"private": true,
"scripts": {
"dev": "vite dev",
@@ -10,33 +9,34 @@
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"prepare": "svelte-kit sync",
"lint": "prettier --check ./src/ && eslint ./src/",
"format": "prettier --write ."
"lint": "prettier --check . && eslint .",
"format": "prettier --write .",
"server": "cd ./server && MODE=DEV go run ."
},
"devDependencies": {
"@eslint/js": "10.0.1",
"@sveltejs/adapter-node": "5.5.7",
"@sveltejs/kit": "2.69.3",
"@types/papaparse": "5.3.15",
"@vite-pwa/sveltekit": "1.1.0",
"eslint": "10.7.0",
"eslint-config-prettier": "10.1.8",
"eslint-plugin-svelte": "3.20.0",
"globals": "17.7.0",
"prettier": "3.9.5",
"prettier-plugin-svelte": "4.1.1",
"sass": "1.101.0",
"svelte": "5.56.4",
"svelte-check": "4.7.2",
"svelte-eslint-parser": "1.8.0",
"svelte-preprocess": "6.0.5",
"typescript": "6.0.3",
"typescript-eslint": "8.63.0",
"vite": "8.1.4"
"@sveltejs/adapter-node": "^5.2.12",
"@sveltejs/kit": "^2.16.0",
"@types/papaparse": "^5.3.15",
"@typescript-eslint/eslint-plugin": "^8.18.2",
"@typescript-eslint/parser": "^8.18.2",
"@vite-pwa/sveltekit": "^0.6.6",
"eslint": "^8.57.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-svelte": "^2.45.1",
"prettier": "^3.4.2",
"prettier-plugin-svelte": "^3.2.6",
"sass": "^1.83.0",
"svelte": "^5.17.3",
"svelte-check": "^4.1.3",
"svelte-eslint-parser": "^0.42.0",
"svelte-preprocess": "^6.0.3",
"typescript": "^5.7.2",
"vite": "^6.0.7"
},
"type": "module",
"dependencies": {
"blurhash": "2.0.5",
"papaparse": "5.4.1"
"axios": "^1.7.4",
"blurhash": "^2.0.5",
"papaparse": "^5.4.1"
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 520 KiB

After

Width:  |  Height:  |  Size: 488 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 510 KiB

After

Width:  |  Height:  |  Size: 342 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 MiB

After

Width:  |  Height:  |  Size: 2.3 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 805 KiB

After

Width:  |  Height:  |  Size: 900 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 997 KiB

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 900 KiB

After

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 913 KiB

After

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 989 KiB

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 393 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 279 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 777 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

After

Width:  |  Height:  |  Size: 75 KiB

-8
View File
@@ -1,8 +0,0 @@
run:
MODE=DEV go run .
plainrun:
go run .
test:
go test ./...
-1
View File
@@ -1 +0,0 @@
4.2.1
+130
View File
@@ -0,0 +1,130 @@
package main
import (
"errors"
"log/slog"
"time"
"gorm.io/gorm"
)
type ActivityType string
// _AUTO activities are for when logic updates something for the user (automations basically).
var (
ADDED_WATCHED ActivityType = "ADDED_WATCHED"
REMOVED_WATCHED ActivityType = "REMOVED_WATCHED"
RATING_CHANGED ActivityType = "RATING_CHANGED"
STATUS_CHANGED ActivityType = "STATUS_CHANGED"
STATUS_CHANGED_AUTO ActivityType = "STATUS_CHANGED_AUTO"
THOUGHTS_CHANGED ActivityType = "THOUGHTS_CHANGED"
THOUGHTS_REMOVED ActivityType = "THOUGHTS_REMOVED"
IMPORTED_WATCHED ActivityType = "IMPORTED_WATCHED"
IMPORTED_WATCHED_JF ActivityType = "IMPORTED_WATCHED_JF"
IMPORTED_WATCHED_PLEX ActivityType = "IMPORTED_WATCHED_PLEX"
IMPORTED_RATING ActivityType = "IMPORTED_RATING" // Imported rating, but with no rating acts as original import of content to old platform (where they are importing from) activity
IMPORTED_ADDED_WATCHED ActivityType = "IMPORTED_ADDED_WATCHED" // Imported watched date, so we can save the original watch dates of content from users old platform (where they are importing from).
IMPORTED_ADDED_WATCHED_JF ActivityType = "IMPORTED_ADDED_WATCHED_JF"
IMPORTED_ADDED_WATCHED_PLEX ActivityType = "IMPORTED_ADDED_WATCHED_PLEX"
SEASON_ADDED ActivityType = "SEASON_ADDED"
SEASON_ADDED_AUTO ActivityType = "SEASON_ADDED_AUTO"
SEASON_ADDED_JF ActivityType = "SEASON_ADDED_JF"
SEASON_ADDED_PLEX ActivityType = "SEASON_ADDED_PLEX"
SEASON_REMOVED ActivityType = "SEASON_REMOVED"
SEASON_RATING_CHANGED ActivityType = "SEASON_RATING_CHANGED"
SEASON_STATUS_CHANGED ActivityType = "SEASON_STATUS_CHANGED"
SEASON_STATUS_CHANGED_AUTO ActivityType = "SEASON_STATUS_CHANGED_AUTO"
EPISODE_ADDED ActivityType = "EPISODE_ADDED"
EPISODE_ADDED_JF ActivityType = "EPISODE_ADDED_JF"
EPISODE_ADDED_PLEX ActivityType = "EPISODE_ADDED_PLEX"
EPISODE_REMOVED ActivityType = "EPISODE_REMOVED"
EPISODE_RATING_CHANGED ActivityType = "EPISODE_RATING_CHANGED"
EPISODE_STATUS_CHANGED ActivityType = "EPISODE_STATUS_CHANGED"
)
type Activity struct {
GormModel
// ID of user this activity is linked to, so it can be easily
// secured (users can only view their own activities).
UserID uint `json:"-" gorm:"not null"`
// ID of watched list item this activity is linked to.
WatchedID uint `json:"watchedId" gorm:"not null"`
// Type of activity.
Type ActivityType `json:"type" gorm:"not null"`
// Holds custom data (ex, if rating changed, this can
// hold new rating - if status changed, this will hold that).
Data string `json:"data" gorm:"not null"`
// Custom date for the activity, that the user can define.
CustomDate *time.Time `json:"customDate,omitempty"`
}
type ActivityAddRequest struct {
WatchedID uint `json:"watchedId" binding:"required"`
Type ActivityType `json:"type" binding:"required"`
Data string `json:"data" binding:"required"`
CustomDate *time.Time `json:"customDate,omitempty"`
}
type ActivityUpdateRequest struct {
CustomDate time.Time `json:"customDate" binding:"required"`
}
func getActivity(db *gorm.DB, userId uint, watchedId uint) ([]Activity, error) {
activity := new([]Activity)
res := db.Model(&Activity{}).Where("user_id = ? AND watched_id = ?", userId, watchedId).Find(&activity)
if res.Error != nil {
slog.Error("Failed getting activity from database", "error", res.Error.Error())
return []Activity{}, errors.New("failed getting activity")
}
return *activity, nil
}
func addActivity(db *gorm.DB, userId uint, ar ActivityAddRequest) (Activity, error) {
if ar.WatchedID == 0 {
return Activity{}, errors.New("watchedId must be set to add an activity")
}
activity := Activity{UserID: userId, WatchedID: ar.WatchedID, Type: ar.Type, Data: ar.Data, CustomDate: ar.CustomDate}
res := db.Create(&activity)
if res.Error != nil {
slog.Error("Error adding activity to database", "error", res.Error.Error())
return Activity{}, errors.New("failed adding new activity to database")
}
slog.Debug("Adding activity", "added_activity", activity)
return activity, nil
}
func updateActivity(db *gorm.DB, userId uint, id uint, activityUpdateRequest ActivityUpdateRequest) error {
if id == 0 {
return errors.New("id must be set to update an activity")
}
if activityUpdateRequest.CustomDate.IsZero() {
return errors.New("customDate must be set to update an activity")
}
res := db.Model(&Activity{}).Where("user_id = ? AND id = ?", userId, id).Update("custom_date", activityUpdateRequest.CustomDate)
if res.Error != nil {
slog.Error("Error updating activity in database", "error", res.Error.Error())
return errors.New("failed updating activity in database")
}
if res.RowsAffected < 1 {
slog.Error("No activities were updated. This may be because the activity doesn't exist or is not owned by the calling user.")
return errors.New("failed updating activity in database")
}
slog.Debug("Updating activity", "updated_activity", id)
return nil
}
func deleteActivity(db *gorm.DB, userId uint, id uint) error {
if id == 0 {
return errors.New("an id must be provided to delete an activity")
}
res := db.Where("user_id = ?", userId).Delete(&Activity{}, id)
if res.Error != nil {
slog.Error("Error deleting activity in database", "error", res.Error.Error())
return errors.New("failed deleting activity in database")
}
if res.RowsAffected < 1 {
slog.Error("No activities were deleted. This may be because the activity doesn't exist or is not owned by the calling user.")
return errors.New("failed deleting activity from database")
}
return nil
}
+206
View File
@@ -0,0 +1,206 @@
package main
import (
"errors"
"log/slog"
"github.com/sbondCo/Watcharr/arr"
)
type ArrSettings struct {
Name string `json:"name,omitempty"`
Host string `json:"host,omitempty"`
Key string `json:"key,omitempty"`
}
type SonarrSettings struct {
ArrSettings
QualityProfile int `json:"qualityProfile,omitempty"`
RootFolder int `json:"rootFolder,omitempty"`
LanguageProfile int `json:"languageProfile,omitempty"`
AutomaticSearch bool `json:"automaticSearch"`
// TODO eventually separate profiles and root for anime content (i can see diff language profile being useful)
}
func (s *SonarrSettings) safe() SonarrSettings {
s.Key = ""
return *s
}
type RadarrSettings struct {
ArrSettings
QualityProfile int `json:"qualityProfile,omitempty"`
RootFolder int `json:"rootFolder,omitempty"`
AutomaticSearch bool `json:"automaticSearch"`
}
func (s *RadarrSettings) safe() RadarrSettings {
s.Key = ""
return *s
}
type ArrTestParams struct {
Host string `json:"host,omitempty"`
Key string `json:"key,omitempty"`
}
type SonarrTestResponse struct {
QualityProfiles []arr.QualityProfile `json:"qualityProfiles"`
RootFolders []arr.RootFolder `json:"rootFolders"`
LanguageProfiles []arr.LanguageProfile `json:"languageProfiles"`
}
type RadarrTestResponse struct {
QualityProfiles []arr.QualityProfile `json:"qualityProfiles"`
RootFolders []arr.RootFolder `json:"rootFolders"`
LanguageProfiles []arr.LanguageProfile `json:"languageProfiles"`
}
// Response given to users with PERM_REQUEST_CONTENT - should never include sensitive info
func testSonarr(p ArrTestParams) (SonarrTestResponse, error) {
sonarr := arr.New(arr.SONARR, &p.Host, &p.Key)
qps, err := sonarr.GetQualityProfiles()
if err != nil {
slog.Error("testSonarr failed to get quality profiles!", "error", err)
return SonarrTestResponse{}, errors.New("failed to get quality profiles")
}
rfs, err := sonarr.GetRootFolders()
if err != nil {
slog.Error("testSonarr failed to get root folders!", "error", err)
return SonarrTestResponse{}, errors.New("failed to get root folders")
}
lps, err := sonarr.GetLangaugeProfiles()
if err != nil {
slog.Error("testSonarr failed to get language profiles!", "error", err)
return SonarrTestResponse{}, errors.New("failed to get language profiles")
}
return SonarrTestResponse{QualityProfiles: qps, RootFolders: rfs, LanguageProfiles: lps}, nil
}
// Response given to users with PERM_REQUEST_CONTENT - should never include sensitive info
func testRadarr(p ArrTestParams) (RadarrTestResponse, error) {
radarr := arr.New(arr.RADARR, &p.Host, &p.Key)
qps, err := radarr.GetQualityProfiles()
if err != nil {
slog.Error("testRadarr failed to get quality profiles!", "error", err)
return RadarrTestResponse{}, errors.New("failed to get quality profiles")
}
rfs, err := radarr.GetRootFolders()
if err != nil {
slog.Error("testRadarr failed to get root folders!", "error", err)
return RadarrTestResponse{}, errors.New("failed to get root folders")
}
return RadarrTestResponse{QualityProfiles: qps, RootFolders: rfs}, nil
}
// TODO any way to simplify (deduplicate/reuse) these methods (and the whole file tbh) would be very good
// Add sonarr server to config
func addSonarr(s SonarrSettings) error {
for _, v := range Config.SONARR {
if v.Name == s.Name {
// Server exists with this name...
return errors.New("server with that name already exists")
}
}
Config.SONARR = append(Config.SONARR, s)
writeConfig()
return nil
}
// Edit sonarr server in config
func editSonarr(s SonarrSettings) error {
for i, v := range Config.SONARR {
if v.Name == s.Name {
Config.SONARR[i] = s
writeConfig()
return nil
}
}
return errors.New("can't edit server that does not exist")
}
func rmSonarr(name string) error {
for i, v := range Config.SONARR {
if v.Name == name {
Config.SONARR = append(Config.SONARR[:i], Config.SONARR[i+1:]...)
writeConfig()
return nil
}
}
return errors.New("can't remove a server that does not exist")
}
func getSonarr(name string) (SonarrSettings, error) {
for i, v := range Config.SONARR {
if v.Name == name {
return Config.SONARR[i], nil
}
}
return SonarrSettings{}, errors.New("server not found")
}
// Get list of sonarr servers without api keys.
// Regular users with access to adding to sonarr will request this.
func getSonarrsSafe() []SonarrSettings {
s := []SonarrSettings{}
for _, v := range Config.SONARR {
s = append(s, v.safe())
}
return s
}
// Add radarr server to config
func addRadarr(s RadarrSettings) error {
for _, v := range Config.RADARR {
if v.Name == s.Name {
// Server exists with this name...
return errors.New("server with that name already exists")
}
}
Config.RADARR = append(Config.RADARR, s)
writeConfig()
return nil
}
// Edit radarr server in config
func editRadarr(s RadarrSettings) error {
for i, v := range Config.RADARR {
if v.Name == s.Name {
Config.RADARR[i] = s
writeConfig()
return nil
}
}
return errors.New("can't edit server that does not exist")
}
func rmRadarr(name string) error {
for i, v := range Config.RADARR {
if v.Name == name {
Config.RADARR = append(Config.RADARR[:i], Config.RADARR[i+1:]...)
writeConfig()
return nil
}
}
return errors.New("can't remove a server that does not exist")
}
func getRadarr(name string) (RadarrSettings, error) {
for i, v := range Config.RADARR {
if v.Name == name {
return Config.RADARR[i], nil
}
}
return RadarrSettings{}, errors.New("server not found")
}
// Get list of radarr servers without api keys.
// Regular users with access to adding to radarr will request this.
func getRadarrsSafe() []RadarrSettings {
s := []RadarrSettings{}
for _, v := range Config.RADARR {
s = append(s, v.safe())
}
return s
}
@@ -1,4 +1,4 @@
package arr
package main
import (
"errors"
@@ -7,7 +7,6 @@ import (
"time"
"github.com/sbondCo/Watcharr/arr"
"github.com/sbondCo/Watcharr/config"
)
type ArrDetailsResponse struct {
@@ -32,8 +31,8 @@ type SonarrDetailsResponse struct {
Items []SonarrDetailsResponseItem `json:"items"`
}
func getRadarrQueueDetails(cfg *config.ServerConfig, serverName string, arrId string) (*ArrDetailsResponse, error) {
server, err := getRadarr(cfg, serverName)
func getRadarrQueueDetails(serverName string, arrId string) (*ArrDetailsResponse, error) {
server, err := getRadarr(serverName)
if err != nil {
slog.Error("getRadarrQueueDetails: Failed to get server", "error", err)
return &ArrDetailsResponse{}, errors.New("failed to get server")
@@ -65,8 +64,8 @@ func getRadarrQueueDetails(cfg *config.ServerConfig, serverName string, arrId st
return &adr, nil
}
func getSonarrQueueDetails(cfg *config.ServerConfig, serverName string, arrId string) (*SonarrDetailsResponse, error) {
server, err := getSonarr(cfg, serverName)
func getSonarrQueueDetails(serverName string, arrId string) (*SonarrDetailsResponse, error) {
server, err := getSonarr(serverName)
if err != nil {
slog.Error("getSonarrQueueDetails: Failed to get server", "error", err)
return &SonarrDetailsResponse{}, errors.New("failed to get server")
@@ -120,14 +119,14 @@ func getSonarrQueueDetails(cfg *config.ServerConfig, serverName string, arrId st
// Refresh download queues for our sonarr/radarr servers.
// If the queues don't refresh regularly, our queue detail
// calls will just always return the same info.
func RefreshArrQueues(cfg *config.ServerConfig) {
func refreshArrQueues() {
slog.Debug("refreshArrQueues: Refreshing queues for all configured arr servers.")
// We don't care about responses, errors will be logged by the RunCommand func.
for _, v := range cfg.RADARR {
for _, v := range Config.RADARR {
radarr := arr.New(arr.RADARR, &v.Host, &v.Key)
radarr.RunCommand("RefreshMonitoredDownloads")
}
for _, v := range cfg.SONARR {
for _, v := range Config.SONARR {
sonarr := arr.New(arr.SONARR, &v.Host, &v.Key)
sonarr.RunCommand("RefreshMonitoredDownloads")
}
@@ -1,19 +1,54 @@
package arr
package main
import (
"encoding/json"
"errors"
"log/slog"
"time"
"github.com/sbondCo/Watcharr/arr"
"github.com/sbondCo/Watcharr/config"
"github.com/sbondCo/Watcharr/database/entity"
"github.com/sbondCo/Watcharr/feature/auth/permission"
"gorm.io/gorm"
)
type ArrRequestStatus string
const (
// Pending approval from an admin.
ARR_REQUEST_PENDING ArrRequestStatus = "PENDING"
// Request has been approved and should be added to sonarr/radarr.
ARR_REQUEST_APPROVED ArrRequestStatus = "APPROVED"
ARR_REQUEST_AUTO_APPROVED ArrRequestStatus = "AUTO_APPROVED"
// Request has been denied, not adding content.
ARR_REQUEST_DENIED ArrRequestStatus = "DENIED"
// Content was found on sonarr/radarr already, nothing needs to be done.
ARR_REQUEST_FOUND ArrRequestStatus = "FOUND"
)
type ArrRequest struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
UserID uint `json:"-" gorm:"not null"`
User User `json:"-"`
// Username of `User`.
// We don't want to send back the entire user object, just their name.
// Not stored in DB, only used for our response from api.
Username string `json:"username" gorm:"-"`
ContentID *int `json:"-" gorm:"uniqueIndex:sn_to_cid;not null"`
Content *Content `json:"content,omitempty"`
// Server names are used as an identifier
ServerName string `json:"serverName" gorm:"uniqueIndex:sn_to_cid;not null"`
// Sonarr/Radarrs seriesId/movieId
ArrID int `json:"arrId"`
// Tracked request status
Status ArrRequestStatus `json:"status" gorm:"default:PENDING"`
// Full request made by user (arr.SonarrRequest / arr.RadarrRequest)
// so we know how to fulfil the request if approved.
RequestJson string `json:"requestJson"`
}
func deleteArrRequest(db *gorm.DB, id uint) error {
resp := db.Delete(&entity.ArrRequest{ID: id})
resp := db.Delete(&ArrRequest{ID: id})
if resp.Error != nil {
slog.Error("deleteArrRequest: Failed to remove from db", "error", resp.Error)
return errors.New("failed when removing request")
@@ -22,12 +57,12 @@ func deleteArrRequest(db *gorm.DB, id uint) error {
}
// Gets all requests.
func getArrRequests(db *gorm.DB) ([]entity.ArrRequest, error) {
var req []entity.ArrRequest
func getArrRequests(db *gorm.DB) ([]ArrRequest, error) {
var req []ArrRequest
resp := db.Preload("Content").Preload("User").Find(&req)
if resp.Error != nil {
slog.Error("getArrRequests: Failed to search for requests in db", "error", resp.Error)
return []entity.ArrRequest{}, errors.New("failed to find requests")
return []ArrRequest{}, errors.New("failed to find requests")
}
for i := range req {
req[i].Username = req[i].User.Username
@@ -35,57 +70,57 @@ func getArrRequests(db *gorm.DB) ([]entity.ArrRequest, error) {
return req, nil
}
func getArrRequest(db *gorm.DB, requestId uint) (entity.ArrRequest, error) {
var req entity.ArrRequest
func getArrRequest(db *gorm.DB, requestId uint) (ArrRequest, error) {
var req ArrRequest
resp := db.Where("id = ?", requestId).Take(&req)
if resp.Error != nil {
slog.Error("getArrRequest: Failed to search for request in db", "error", resp.Error)
return entity.ArrRequest{}, errors.New("failed to find request")
return ArrRequest{}, errors.New("failed to find request")
}
return req, nil
}
func getArrRequestByTmdbId(db *gorm.DB, contentType entity.ContentType, tmdbId int) (entity.ArrRequest, error) {
var req entity.ArrRequest
func getArrRequestByTmdbId(db *gorm.DB, contentType ContentType, tmdbId int) (ArrRequest, error) {
var req ArrRequest
resp := db.Joins("JOIN contents ON contents.id = arr_requests.content_id AND contents.tmdb_id = ? AND contents.type = ?", tmdbId, contentType).Find(&req)
if resp.Error != nil {
slog.Error("getArrRequestByTmdbId: Failed to search for request in db", "error", resp.Error)
return entity.ArrRequest{}, errors.New("failed to find request")
return ArrRequest{}, errors.New("failed to find request")
}
return req, nil
}
func createArrRequest(db *gorm.DB, cp ContentProvider, userId uint, serverName string, contentType entity.ContentType, tmdbId int, reqJson string) (*entity.ArrRequest, error) {
content, err := cp.GetOrCacheContent(contentType, tmdbId)
func createArrRequest(db *gorm.DB, userId uint, serverName string, contentType ContentType, tmdbId int, reqJson string) (*ArrRequest, error) {
content, err := getOrCacheContent(db, contentType, tmdbId)
if err != nil {
slog.Error("createArrRequest: GetOrCacheContent errored.")
return &entity.ArrRequest{}, err
slog.Error("createArrRequest: getOrCacheContent errored.")
return &ArrRequest{}, err
}
req := entity.ArrRequest{UserID: userId, ServerName: serverName, ContentID: &content.ID, RequestJson: reqJson}
req := ArrRequest{UserID: userId, ServerName: serverName, ContentID: &content.ID, RequestJson: reqJson}
resp := db.Create(&req)
if resp.Error != nil {
slog.Error("createArrRequest: Failed when inserting request into db.", "error", err)
return &entity.ArrRequest{}, errors.New("failed when adding request")
return &ArrRequest{}, errors.New("failed when adding request")
}
return &req, nil
}
func createSonarrRequest(cfg *config.ServerConfig, db *gorm.DB, cp ContentProvider, userId uint, userPerms int, ur arr.SonarrRequest) (*entity.ArrRequest, error) {
server, err := getSonarr(cfg, ur.ServerName)
func createSonarrRequest(db *gorm.DB, userId uint, userPerms int, ur arr.SonarrRequest) (*ArrRequest, error) {
server, err := getSonarr(ur.ServerName)
if err != nil {
slog.Error("createSonarrRequest: Failed to get server", "error", err)
return &entity.ArrRequest{}, errors.New("failed to get server")
return &ArrRequest{}, errors.New("failed to get server")
}
reqJson, err := json.Marshal(ur)
if err != nil {
slog.Error("createRadarrRequest: Failed when marshalling json request", "error", err)
return &entity.ArrRequest{}, errors.New("failed when processing request")
return &ArrRequest{}, errors.New("failed when processing request")
}
// Since we create the request in the db now, we don't have to check for duplicates, a unique constraint will error us here if hit.
arrReq, err := createArrRequest(db, cp, userId, ur.ServerName, entity.SHOW, ur.TMDBID, string(reqJson[:]))
arrReq, err := createArrRequest(db, userId, ur.ServerName, SHOW, ur.TMDBID, string(reqJson[:]))
if err != nil {
slog.Error("createSonarrRequest: Failed when creating arr request", "error", err)
return &entity.ArrRequest{}, errors.New("failed when creating request")
return &ArrRequest{}, errors.New("failed when creating request")
}
sonarr := arr.New(arr.SONARR, &server.Host, &server.Key)
// 1. Lookup on Sonarr to check if the show has already been added (via method other than watcharr).
@@ -95,14 +130,10 @@ func createSonarrRequest(cfg *config.ServerConfig, db *gorm.DB, cp ContentProvid
found := lookupRes[0] // There should only be one result when looking up by id.
// If it has an ID, then it will have already been added to Sonarr.
if found.ID != 0 {
dbResp := db.
Model(&entity.ArrRequest{}).
Where("id = ?", arrReq.ID).
Update("arr_id", found.ID).
Update("status", entity.ARR_REQUEST_FOUND)
dbResp := db.Model(&ArrRequest{}).Where("id = ?", arrReq.ID).Update("arr_id", found.ID).Update("status", ARR_REQUEST_FOUND)
if dbResp.Error != nil {
slog.Error("createSonarrRequest: Failed to update request in db", "error", err)
return &entity.ArrRequest{}, errors.New("content was requested, but we failed to update the db")
return &ArrRequest{}, errors.New("content was requested, but we failed to update the db")
} else {
slog.Debug("createSonarrRequest: Result from lookup had an ID. Request in database has been updated with it.", "arr_id", found.ID)
arrReq.ArrID = found.ID
@@ -111,50 +142,46 @@ func createSonarrRequest(cfg *config.ServerConfig, db *gorm.DB, cp ContentProvid
}
}
// 2. If user has auto approve perms, add movie to sonarr.
if permission.Has(userPerms, entity.PERM_REQUEST_CONTENT_AUTO_APPROVE) {
if hasPermission(userPerms, PERM_REQUEST_CONTENT_AUTO_APPROVE) {
slog.Debug("createSonarrRequest: User has auto approve permission.. sending request to Sonarr.")
ur.AutomaticSearch = server.AutomaticSearch
resp, err := sonarr.AddContent(sonarr.BuildAddShowBody(ur))
if err != nil {
slog.Error("createSonarrRequest: Failed to add content", "error", err)
return &entity.ArrRequest{}, errors.New("failed to add content")
return &ArrRequest{}, errors.New("failed to add content")
}
dbResp := db.
Model(&entity.ArrRequest{}).
Where("id = ?", arrReq.ID).
Update("arr_id", resp["id"]).
Update("status", entity.ARR_REQUEST_AUTO_APPROVED)
dbResp := db.Model(&ArrRequest{}).Where("id = ?", arrReq.ID).Update("arr_id", resp["id"]).Update("status", ARR_REQUEST_AUTO_APPROVED)
if dbResp.Error != nil {
slog.Error("createSonarrRequest: Failed to update request in db", "error", err)
return &entity.ArrRequest{}, errors.New("content was requested, but we failed to update the db")
return &ArrRequest{}, errors.New("content was requested, but we failed to update the db")
}
arrId, ok := resp["id"].(float64)
if !ok {
slog.Error("createSonarrRequest: Failed to cast arr id as an int", "id", resp["id"])
return &entity.ArrRequest{}, errors.New("failed to get arr id")
return &ArrRequest{}, errors.New("failed to get arr id")
}
arrReq.ArrID = int(arrId)
arrReq.Status = entity.ARR_REQUEST_AUTO_APPROVED
arrReq.Status = ARR_REQUEST_AUTO_APPROVED
}
return arrReq, nil
}
func createRadarrRequest(cfg *config.ServerConfig, db *gorm.DB, cp ContentProvider, userId uint, userPerms int, ur arr.RadarrRequest) (*entity.ArrRequest, error) {
server, err := getRadarr(cfg, ur.ServerName)
func createRadarrRequest(db *gorm.DB, userId uint, userPerms int, ur arr.RadarrRequest) (*ArrRequest, error) {
server, err := getRadarr(ur.ServerName)
if err != nil {
slog.Error("createRadarrRequest: Failed to get server", "error", err)
return &entity.ArrRequest{}, errors.New("failed to get server")
return &ArrRequest{}, errors.New("failed to get server")
}
reqJson, err := json.Marshal(ur)
if err != nil {
slog.Error("createRadarrRequest: Failed when marshalling json request", "error", err)
return &entity.ArrRequest{}, errors.New("failed when processing request")
return &ArrRequest{}, errors.New("failed when processing request")
}
// Since we create the request in the db now, we don't have to check for duplicates, a unique constraint will error us here if hit.
arrReq, err := createArrRequest(db, cp, userId, ur.ServerName, entity.MOVIE, ur.TMDBID, string(reqJson[:]))
arrReq, err := createArrRequest(db, userId, ur.ServerName, MOVIE, ur.TMDBID, string(reqJson[:]))
if err != nil {
slog.Error("createRadarrRequest: Failed when creating arr request", "error", err)
return &entity.ArrRequest{}, errors.New("failed when creating request")
return &ArrRequest{}, errors.New("failed when creating request")
}
radarr := arr.New(arr.RADARR, &server.Host, &server.Key)
// 1. Lookup on Radarr to check if the movie has already been added (via method other than watcharr).
@@ -164,14 +191,10 @@ func createRadarrRequest(cfg *config.ServerConfig, db *gorm.DB, cp ContentProvid
found := lookupRes[0] // There should only be one result when looking up by id.
// If it has an ID, then it will have already been added to Radarr.
if found.ID != 0 {
dbResp := db.
Model(&entity.ArrRequest{}).
Where("id = ?", arrReq.ID).
Update("arr_id", found.ID).
Update("status", entity.ARR_REQUEST_FOUND)
dbResp := db.Model(&ArrRequest{}).Where("id = ?", arrReq.ID).Update("arr_id", found.ID).Update("status", ARR_REQUEST_FOUND)
if dbResp.Error != nil {
slog.Error("createRadarrRequest: Failed to update request in db", "error", err)
return &entity.ArrRequest{}, errors.New("content was requested, but we failed to update the db")
return &ArrRequest{}, errors.New("content was requested, but we failed to update the db")
} else {
slog.Debug("createRadarrRequest: Result from lookup had an ID. Request in database has been updated with it.", "arr_id", found.ID)
arrReq.ArrID = found.ID
@@ -180,35 +203,31 @@ func createRadarrRequest(cfg *config.ServerConfig, db *gorm.DB, cp ContentProvid
}
}
// 2. If user has auto approve perms, add movie to radarr.
if permission.Has(userPerms, entity.PERM_REQUEST_CONTENT_AUTO_APPROVE) {
if hasPermission(userPerms, PERM_REQUEST_CONTENT_AUTO_APPROVE) {
slog.Debug("createRadarrRequest: User has auto approve permission.. sending request to Radarr.")
ur.AutomaticSearch = server.AutomaticSearch
resp, err := radarr.AddContent(radarr.BuildAddMovieBody(ur))
if err != nil {
slog.Error("createRadarrRequest: Failed to add content", "error", err)
return &entity.ArrRequest{}, errors.New("failed to add content")
return &ArrRequest{}, errors.New("failed to add content")
}
dbResp := db.
Model(&entity.ArrRequest{}).
Where("id = ?", arrReq.ID).
Update("arr_id", resp["id"]).
Update("status", entity.ARR_REQUEST_AUTO_APPROVED)
dbResp := db.Model(&ArrRequest{}).Where("id = ?", arrReq.ID).Update("arr_id", resp["id"]).Update("status", ARR_REQUEST_AUTO_APPROVED)
if dbResp.Error != nil {
slog.Error("createRadarrRequest: Failed to update request in db", "error", err)
return &entity.ArrRequest{}, errors.New("content was requested, but we failed to update the db")
return &ArrRequest{}, errors.New("content was requested, but we failed to update the db")
}
arrId, ok := resp["id"].(float64)
if !ok {
slog.Error("createRadarrRequest: Failed to cast arr id as an int", "id", resp["id"])
return &entity.ArrRequest{}, errors.New("failed to get arr id")
return &ArrRequest{}, errors.New("failed to get arr id")
}
arrReq.ArrID = int(arrId)
arrReq.Status = entity.ARR_REQUEST_AUTO_APPROVED
arrReq.Status = ARR_REQUEST_AUTO_APPROVED
}
return arrReq, nil
}
func getRadarrRequestInfo(cfg *config.ServerConfig, db *gorm.DB, requestId uint) (arr.MovieSerie, error) {
func getRadarrRequestInfo(db *gorm.DB, requestId uint) (arr.MovieSerie, error) {
if requestId == 0 {
slog.Error("sonarr info: No request id provided")
return arr.MovieSerie{}, errors.New("no request id provided")
@@ -218,7 +237,7 @@ func getRadarrRequestInfo(cfg *config.ServerConfig, db *gorm.DB, requestId uint)
slog.Error("radarr info: Failed to get server", "error", err)
return arr.MovieSerie{}, errors.New("failed to get server")
}
server, err := getRadarr(cfg, arrRequest.ServerName)
server, err := getRadarr(arrRequest.ServerName)
if err != nil {
slog.Error("radarr info: Failed to get server", "error", err)
return arr.MovieSerie{}, errors.New("failed to get server")
@@ -227,7 +246,7 @@ func getRadarrRequestInfo(cfg *config.ServerConfig, db *gorm.DB, requestId uint)
resp, respStatusCode, err := radarr.GetContent(arrRequest.ArrID)
if err != nil {
slog.Error("radarr info: Failed to get info", "error", err)
if (arrRequest.Status == entity.ARR_REQUEST_APPROVED || arrRequest.Status == entity.ARR_REQUEST_AUTO_APPROVED) && respStatusCode == 404 {
if (arrRequest.Status == ARR_REQUEST_APPROVED || arrRequest.Status == ARR_REQUEST_AUTO_APPROVED) && respStatusCode == 404 {
slog.Error("radarr info: 404 returned.. content must've been removed.. removing request.")
err := deleteArrRequest(db, arrRequest.ID)
if err != nil {
@@ -241,7 +260,7 @@ func getRadarrRequestInfo(cfg *config.ServerConfig, db *gorm.DB, requestId uint)
return resp, nil
}
func getSonarrRequestInfo(cfg *config.ServerConfig, db *gorm.DB, requestId uint) (arr.MovieSerie, error) {
func getSonarrRequestInfo(db *gorm.DB, requestId uint) (arr.MovieSerie, error) {
if requestId == 0 {
slog.Error("sonarr info: No request id provided")
return arr.MovieSerie{}, errors.New("no request id provided")
@@ -251,7 +270,7 @@ func getSonarrRequestInfo(cfg *config.ServerConfig, db *gorm.DB, requestId uint)
slog.Error("sonarr info: Failed to get server", "error", err)
return arr.MovieSerie{}, errors.New("failed to get server")
}
server, err := getSonarr(cfg, arrRequest.ServerName)
server, err := getSonarr(arrRequest.ServerName)
if err != nil {
slog.Error("sonarr info: Failed to get server", "error", err)
return arr.MovieSerie{}, errors.New("failed to get server")
@@ -260,7 +279,7 @@ func getSonarrRequestInfo(cfg *config.ServerConfig, db *gorm.DB, requestId uint)
resp, respStatusCode, err := sonarr.GetContent(arrRequest.ArrID)
if err != nil {
slog.Error("sonarr info: Failed to get info", "error", err)
if (arrRequest.Status == entity.ARR_REQUEST_APPROVED || arrRequest.Status == entity.ARR_REQUEST_AUTO_APPROVED) && respStatusCode == 404 {
if (arrRequest.Status == ARR_REQUEST_APPROVED || arrRequest.Status == ARR_REQUEST_AUTO_APPROVED) && respStatusCode == 404 {
slog.Error("sonarr info: 404 returned.. content must've been removed.. removing request.")
err := deleteArrRequest(db, arrRequest.ID)
if err != nil {
@@ -1,21 +1,16 @@
package arr
package main
import (
"errors"
"log/slog"
"github.com/sbondCo/Watcharr/arr"
"github.com/sbondCo/Watcharr/config"
"github.com/sbondCo/Watcharr/database/entity"
"gorm.io/gorm"
)
// Deny an arr request
func denyArrRequest(db *gorm.DB, id uint) error {
resp := db.
Model(&entity.ArrRequest{}).
Where("id = ?", id).
Update("status", entity.ARR_REQUEST_DENIED)
resp := db.Model(&ArrRequest{}).Where("id = ?", id).Update("status", ARR_REQUEST_DENIED)
if resp.Error != nil {
slog.Error("denyArrRequest: Failed to update status to denied", "error", resp.Error)
return errors.New("failed when updating request status")
@@ -24,14 +19,14 @@ func denyArrRequest(db *gorm.DB, id uint) error {
}
// Approve radarr movie
func approveRadarrRequest(cfg *config.ServerConfig, db *gorm.DB, reqId uint, ur arr.RadarrRequest) (int, error) {
func approveRadarrRequest(db *gorm.DB, reqId uint, ur arr.RadarrRequest) (int, error) {
_, err := getArrRequest(db, reqId)
if err != nil {
slog.Error("approveRadarrRequest: Failed to get request from db", "error", err)
return 0, errors.New("failed to get request")
}
// Get server in request
server, err := getRadarr(cfg, ur.ServerName)
server, err := getRadarr(ur.ServerName)
if err != nil {
slog.Error("approveRadarrRequest: Failed to get server", "error", err)
return 0, errors.New("failed to get server")
@@ -43,11 +38,7 @@ func approveRadarrRequest(cfg *config.ServerConfig, db *gorm.DB, reqId uint, ur
slog.Error("approveRadarrRequest: Failed to add content", "error", err)
return 0, errors.New("failed to add content")
}
dbResp := db.
Model(&entity.ArrRequest{}).
Where("id = ?", reqId).
Update("arr_id", resp["id"]).
Update("status", entity.ARR_REQUEST_APPROVED)
dbResp := db.Model(&ArrRequest{}).Where("id = ?", reqId).Update("arr_id", resp["id"]).Update("status", ARR_REQUEST_APPROVED)
if dbResp.Error != nil {
slog.Error("approveRadarrRequest: Failed to update request in db", "error", err)
return 0, errors.New("content was requested, but we failed to update the db")
@@ -61,14 +52,14 @@ func approveRadarrRequest(cfg *config.ServerConfig, db *gorm.DB, reqId uint, ur
}
// Approve sonarr movie
func approveSonarrRequest(cfg *config.ServerConfig, db *gorm.DB, reqId uint, ur arr.SonarrRequest) (int, error) {
func approveSonarrRequest(db *gorm.DB, reqId uint, ur arr.SonarrRequest) (int, error) {
_, err := getArrRequest(db, reqId)
if err != nil {
slog.Error("approveSonarrRequest: Failed to get request from db", "error", err)
return 0, errors.New("failed to get request")
}
// Get server in request
server, err := getSonarr(cfg, ur.ServerName)
server, err := getSonarr(ur.ServerName)
if err != nil {
slog.Error("approveSonarrRequest: Failed to get server", "error", err)
return 0, errors.New("failed to get server")
@@ -80,11 +71,7 @@ func approveSonarrRequest(cfg *config.ServerConfig, db *gorm.DB, reqId uint, ur
slog.Error("approveSonarrRequest: Failed to add content", "error", err)
return 0, errors.New("failed to add content")
}
dbResp := db.
Model(&entity.ArrRequest{}).
Where("id = ?", reqId).
Update("arr_id", resp["id"]).
Update("status", entity.ARR_REQUEST_APPROVED)
dbResp := db.Model(&ArrRequest{}).Where("id = ?", reqId).Update("arr_id", resp["id"]).Update("status", ARR_REQUEST_APPROVED)
if dbResp.Error != nil {
slog.Error("approveSonarrRequest: Failed to update request in db", "error", err)
return 0, errors.New("content was requested, but we failed to update the db")
+310 -127
View File
@@ -1,4 +1,4 @@
package auth
package main
import (
"bytes"
@@ -17,15 +17,117 @@ import (
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"github.com/sbondCo/Watcharr/config"
"github.com/sbondCo/Watcharr/database/entity"
"github.com/sbondCo/Watcharr/feature/plex"
"github.com/sbondCo/Watcharr/token"
"golang.org/x/crypto/argon2"
"gorm.io/gorm"
)
type UserType uint8
var (
WATCHARR_USER UserType = 0
JELLYFIN_USER UserType = 1
PLEX_USER UserType = 2
// Registered via trusted header auth
PROXY_USER UserType = 3
)
// User Perms
// iota auto increments for us so when adding new
// perms, add to bottom as to not change other perm
// values.
const (
PERM_NONE int = 1 << iota
PERM_ADMIN
PERM_REQUEST_CONTENT
PERM_REQUEST_CONTENT_AUTO_APPROVE
)
// uniqueIndex applied between Username and UserType, so same usernames can exist, but only with different types.
// This is incase different users with same name from different services try to signup.
type User struct {
GormModel
Username string `gorm:"uniqueIndex:usr_name_to_type;not null" json:"username" binding:"required"`
Password string `gorm:"not null" json:"password" binding:"required"`
AvatarID uint `json:"-"`
Avatar Image `json:"avatar"`
Bio string `json:"bio"`
// The type of user/which auth service they originate from.
// Empty if from Watcharr, or the name of the service (eg. jellyfin)
Type UserType `gorm:"uniqueIndex:usr_name_to_type;not null;default:0" json:"type"`
// ID of user from the third party service, this will be used purely for lookup of user at signin.
ThirdPartyID string `json:"-"`
// Auth token from third party (jellyfin)
ThirdPartyAuth string `json:"-"`
// Users third party integrations (minus jellyfin for now)
UserServices []UserServices `json:"-"`
Watched []Watched
// All Tags
Tags []Tag `json:"-"`
// Users permissions
Permissions int `gorm:"default:1" json:"-"`
// All user settings cols, in another struct for reusability
UserSettings
}
func (u *User) GetSafe() PublicUser {
return PublicUser{
ID: u.ID,
Username: u.Username,
Avatar: u.Avatar,
Bio: u.Bio,
}
}
// This struct uses pointer to the values, so in update user settings,
// we can tell which setting is being updated (if not nil..).
type UserSettings struct {
// Is profile private
Private *bool `gorm:"default:false" json:"private"`
// Are watched list content thoughts public (profile must also be public is false)
PrivateThoughts *bool `gorm:"default:false" json:"privateThoughts"`
// If ui 'spoilers' should be shown
HideSpoilers *bool `gorm:"default:false" json:"hideSpoilers"`
// If user wants previously watched items to show in 'Finished' filter,
// even if the watched item state has since been changed.
// Also if user wants to show in watched stats.
IncludePreviouslyWatched *bool `gorm:"default:false" json:"includePreviouslyWatched"`
// User's country to get correct content streaming providers.
Country *string `gorm:"default:'US'" json:"country"`
// Does the user want show, season and episode automations enabled.
AutomateShowStatuses *bool `gorm:"default:true" json:"automateShowStatuses"`
// Rating system user wants to use (frontend only).
// RatingSystem enum in frontend maxes out at 3, so just max=3 on this and we should be gut.
RatingSystem *int `json:"ratingSystem" binding:"omitempty,max=3"`
// Rating step for supported rating systems (frontend only, enum goes up to 2).
RatingStep *int `json:"ratingStep" binding:"omitempty,max=2"`
}
// Holds third party service auth tokens for users.
// Each service may use the fields in their own way.
// Unique index applied between service name and clientID
// to ensure no duplicates (no need to apply it against
// user_id, no accounts should share an integration).
//
// Plex:
// - AuthToken : Used for requests against plex.tv
// - AuthToken2 : Used for requests against home plex server.
type UserServices struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
// Service/integration name
Name string `gorm:"uniqueIndex:svc_name_to_cltid;not null;" json:"-"`
// The users id on the third party service
ClientID string `gorm:"uniqueIndex:svc_name_to_cltid;not null;" json:"-"`
AuthToken string `gorm:"not null;" json:"-"`
// Second auth token, generic name so future services can use it without extra confusion.
// Ex: We require a second auth token for use with our local server for Plex.
AuthToken2 string `json:"-"`
UserID uint `gorm:"not null;" json:"-"`
}
// We use a separate struct for registration to avoid confusion
// and possible accidents where we allow a user to pass in a
// property from the main User struct that shouldn't be allowed.
@@ -55,11 +157,6 @@ type AuthResponse struct {
Token string `json:"token"`
}
type UserPasswordUpdateRequest struct {
OldPassword string `json:"oldPassword" binding:"required"`
NewPassword string `json:"newPassword" binding:"required"`
}
type AvailableAuthProvidersResponse struct {
AvailableAuthProviders []string `json:"available"`
SignupEnabled bool `json:"signupEnabled"`
@@ -68,33 +165,134 @@ type AvailableAuthProvidersResponse struct {
HeaderAuthAutoLogin bool `json:"headerAuthAutoLogin"`
}
type PlexProvider interface {
FetchPlexAccountFromToken(token string) (plex.PlexUser, error)
GetPlexHomeServerAuthToken(plexAuth string, userClientId string) (string, error)
type ArgonParams struct {
memory uint32
iterations uint32
parallelism uint8
saltLength uint32
keyLength uint32
}
type Service struct {
db *gorm.DB
cfg *config.ServerConfig
plexProvider PlexProvider
}
func NewService(db *gorm.DB, cfg *config.ServerConfig, plexProvider PlexProvider) *Service {
return &Service{
db,
cfg,
plexProvider,
func GetPassArgonParams() *ArgonParams {
return &ArgonParams{
memory: 64 * 1024,
iterations: 3,
parallelism: 2,
saltLength: 16,
keyLength: 32,
}
}
func (s *Service) Register(ur *UserRegisterRequest, initialPerm int) (AuthResponse, error) {
if !s.cfg.SIGNUP_ENABLED {
slog.Warn("Register: Register called, but signing up is disabled.")
type TokenClaims struct {
UserID uint `json:"userId"`
Username string `json:"username"`
Type UserType `json:"type"`
jwt.RegisteredClaims
}
type UserPasswordUpdateRequest struct {
OldPassword string `json:"oldPassword" binding:"required"`
NewPassword string `json:"newPassword" binding:"required"`
}
// Auth middleware
// If db is passed, extra user info from the database will be fetched.
func AuthRequired(db *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {
slog.Debug("AuthRequired middleware hit")
atoken := c.GetHeader("Authorization")
// Make sure auth header isn't empty
if atoken == "" {
slog.Warn("Returning 401, Authorization header not provided")
c.AbortWithStatus(401)
return
}
// Parse token
token, err := jwt.ParseWithClaims(atoken, &TokenClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(Config.JWT_SECRET), nil
})
if err != nil {
slog.Error("AuthRequired failed to parse token", "error", err)
c.AbortWithStatus(401)
return
}
// If token is valid, go to next handler
if claims, ok := token.Claims.(*TokenClaims); ok && token.Valid {
// Check if token issuedAt is from before `timeOfNewLoginRequired`.
// Basically just so we can logout old tokens and force relogin...
// since new changes require the user login again.
timeOfNewLoginRequired, _ := time.Parse(time.RFC822, "18 Aug 23 20:30 UTC")
if claims.IssuedAt.Before(timeOfNewLoginRequired) {
slog.Info("Token is from before timeOfNewLoginRequired.. returning 401", "token_issued_at", claims.IssuedAt, "time_of_new_login_required", timeOfNewLoginRequired)
c.AbortWithStatus(401)
return
}
slog.Debug("Token is valid", "claims", claims)
c.Set("userId", claims.UserID)
c.Set("userType", claims.Type)
// If db passed, get extra user info and set as variables in req context
if db != nil {
slog.Debug("AuthRequired: db passed.. getting extra user info")
dbUser := new(User)
res := db.Where("id = ?", claims.UserID).Take(&dbUser)
if res.Error != nil {
slog.Error("AuthRequired: Failed to select user from database", "error", res.Error)
c.AbortWithStatus(401)
return
}
slog.Debug("AuthRequired: fetched extra user info. Setting vars.", "userThirdPartyId", dbUser.ThirdPartyID, "userThirdPartyAuth", "lol this is censored dude")
c.Set("userThirdPartyId", dbUser.ThirdPartyID)
c.Set("userThirdPartyAuth", dbUser.ThirdPartyAuth)
c.Set("username", dbUser.Username)
c.Set("userPermissions", dbUser.Permissions)
}
c.Next()
} else {
slog.Error("Token is **not** valid")
c.AbortWithStatus(401)
return
}
}
}
// Admin only middleware (use after AuthRequired with extra info!)
func AdminRequired() gin.HandlerFunc {
return func(c *gin.Context) {
userId := c.GetUint("userId")
perms := c.GetInt("userPermissions")
if hasPermission(perms, PERM_ADMIN) {
slog.Debug("AdminRequired: User has permission to access admin only route", "user_id", userId)
c.Next()
return
}
slog.Info("AdminRequired: User denied permission to access admin only route", "user_id", userId)
c.AbortWithStatus(401)
}
}
// Specific perm only middleware (use after AuthRequired with extra info!)
func PermRequired(perm int) gin.HandlerFunc {
return func(c *gin.Context) {
userId := c.GetUint("userId")
perms := c.GetInt("userPermissions")
if hasPermission(perms, perm) {
slog.Debug("PermRequired: User has permission to access perm only route", "user_id", userId, "required_perm", perm)
c.Next()
return
}
slog.Info("PermRequired: User denied permission to access perm only route", "user_id", userId, "required_perm", perm)
c.AbortWithStatus(401)
}
}
func register(ur *UserRegisterRequest, initialPerm int, db *gorm.DB) (AuthResponse, error) {
if !Config.SIGNUP_ENABLED {
slog.Warn("Register called, but signing up is disabled.")
return AuthResponse{}, errors.New("registering is disabled")
}
var user entity.User = entity.User{Username: ur.Username, Password: ur.Password}
slog.Info("Register: A user is registering", "username", user.Username)
hash, err := s.hashPassword(user.Password, entity.GetPassArgonParams())
var user User = User{Username: ur.Username, Password: ur.Password}
slog.Info("A user is registering", "username", user.Username)
hash, err := hashPassword(user.Password, GetPassArgonParams())
if err != nil {
log.Fatal(err)
}
@@ -103,14 +301,14 @@ func (s *Service) Register(ur *UserRegisterRequest, initialPerm int) (AuthRespon
user.Password = hash
// Update user permissions if an initial perm is passed in (1 is default)
if initialPerm != 0 && initialPerm != entity.PERM_NONE {
slog.Info("Register: User being registered has been given extra initial permissions", "initial_perm", initialPerm)
if initialPerm != 0 && initialPerm != PERM_NONE {
slog.Info("User being registered has been given extra initial permissions", "initial_perm", initialPerm)
user.Permissions = initialPerm
}
user.Country = &s.cfg.DEFAULT_COUNTRY
user.Country = &Config.DEFAULT_COUNTRY
res := s.db.Create(&user)
res := db.Create(&user)
if res.Error != nil {
// If error is because unique contraint failed.. user already exists
if res.Error == gorm.ErrDuplicatedKey {
@@ -128,7 +326,7 @@ func (s *Service) Register(ur *UserRegisterRequest, initialPerm int) (AuthRespon
return AuthResponse{}, errors.New("failed to get user id, try login")
}
token, err := s.signJWT(&user)
token, err := signJWT(&user)
if err != nil {
slog.Error("Registration: Failed to sign new jwt", "error", err)
return AuthResponse{}, errors.New("failed to get auth token")
@@ -136,10 +334,10 @@ func (s *Service) Register(ur *UserRegisterRequest, initialPerm int) (AuthRespon
return AuthResponse{Token: token}, nil
}
func (s *Service) RegisterFirstUser(urr *UserRegisterRequest) (AuthResponse, error) {
func registerFirstUser(user *UserRegisterRequest, db *gorm.DB) (AuthResponse, error) {
// Ensure no users exist
var userCount int64
uresp := s.db.Model(&entity.User{}).Count(&userCount)
uresp := db.Model(&User{}).Count(&userCount)
if uresp.Error != nil {
slog.Error("registerFirstUser: User count query failed!", "error", uresp.Error)
return AuthResponse{}, errors.New("failed to query db for a count of users")
@@ -149,19 +347,19 @@ func (s *Service) RegisterFirstUser(urr *UserRegisterRequest) (AuthResponse, err
return AuthResponse{}, errors.New("first user already registered")
}
slog.Info("Registering first user.")
return s.Register(urr, entity.PERM_ADMIN)
return register(user, PERM_ADMIN, db)
}
func (s *Service) Login(userL *entity.User) (AuthResponse, error) {
slog.Debug("A User Is Logging In", "username", userL.Username)
dbUser := new(entity.User)
res := s.db.Where("username = ? AND (type IS NULL OR type = 0)", userL.Username).Take(&dbUser)
func login(user *User, db *gorm.DB) (AuthResponse, error) {
slog.Debug("A User Is Logging In", "username", user.Username)
dbUser := new(User)
res := db.Where("username = ? AND (type IS NULL OR type = 0)", user.Username).Take(&dbUser)
if res.Error != nil {
slog.Error("Failed to select user from database for login", "error", res.Error)
return AuthResponse{}, errors.New("User does not exist")
}
match, err := s.compareHash(userL.Password, dbUser.Password)
match, err := compareHash(user.Password, dbUser.Password)
if err != nil {
slog.Error("Failed to compare pass to hash for login", "error", err)
return AuthResponse{}, errors.New("failed to login")
@@ -171,7 +369,7 @@ func (s *Service) Login(userL *entity.User) (AuthResponse, error) {
return AuthResponse{}, errors.New("incorrect details")
}
token, err := s.signJWT(dbUser)
token, err := signJWT(dbUser)
if err != nil {
slog.Error("Failed to sign new jwt", "error", err)
return AuthResponse{}, errors.New("failed to get auth token")
@@ -179,20 +377,20 @@ func (s *Service) Login(userL *entity.User) (AuthResponse, error) {
return AuthResponse{Token: token}, nil
}
func (s *Service) LoginJellyfin(userL *entity.User) (AuthResponse, error) {
if s.cfg.JELLYFIN_HOST == "" {
func loginJellyfin(user *User, db *gorm.DB) (AuthResponse, error) {
if Config.JELLYFIN_HOST == "" {
slog.Error("Request made to login via Jellyfin, but JELLYFIN_HOST has not been configured.")
return AuthResponse{}, errors.New("jellyfin login not enabled")
}
base, err := url.Parse(s.cfg.JELLYFIN_HOST + "/Users/AuthenticateByName")
base, err := url.Parse(Config.JELLYFIN_HOST + "/Users/AuthenticateByName")
if err != nil {
slog.Error("Failed to parse AuthenticateByName api endpoint url", "error", err.Error())
return AuthResponse{}, errors.New("failed to parse api uri")
}
// Marshall struct as json
usrJSON, err := json.Marshal(JellyfinAuth{Username: userL.Username, Pw: userL.Password})
usrJSON, err := json.Marshal(JellyfinAuth{Username: user.Username, Pw: user.Password})
if err != nil {
slog.Error("Error marshalling JellyfinAuth JSON", "error", err.Error())
return AuthResponse{}, errors.New("failed to marshal json")
@@ -205,7 +403,7 @@ func (s *Service) LoginJellyfin(userL *entity.User) (AuthResponse, error) {
return AuthResponse{}, errors.New("request failed")
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("X-Emby-Authorization", "MediaBrowser Client=\"Watcharr\", Device=\"HTTP\", DeviceId=\"WatcharrFor"+userL.Username+"\", Version=\"10.8.0\"")
req.Header.Add("X-Emby-Authorization", "MediaBrowser Client=\"Watcharr\", Device=\"HTTP\", DeviceId=\"WatcharrFor"+user.Username+"\", Version=\"10.8.0\"")
res, err := client.Do(req)
if err != nil {
slog.Error("making request to jellyfin for auth failed", "error", err)
@@ -231,8 +429,8 @@ func (s *Service) LoginJellyfin(userL *entity.User) (AuthResponse, error) {
return AuthResponse{}, errors.New("jellyfin returned empty user id")
}
dbUser := new(entity.User)
dbRes := s.db.Where("third_party_id = ? AND type = ?", resp.User.ID, entity.JELLYFIN_USER).Take(&dbUser)
dbUser := new(User)
dbRes := db.Where("third_party_id = ? AND type = ?", resp.User.ID, JELLYFIN_USER).Take(&dbUser)
if dbRes.Error != nil {
if errors.Is(dbRes.Error, gorm.ErrRecordNotFound) {
// Record not found, so we should create the user
@@ -240,10 +438,10 @@ func (s *Service) LoginJellyfin(userL *entity.User) (AuthResponse, error) {
dbUser.ThirdPartyID = resp.User.ID
dbUser.ThirdPartyAuth = resp.AccessToken
dbUser.Username = resp.User.Name
dbUser.Type = entity.JELLYFIN_USER
dbUser.Country = &s.cfg.DEFAULT_COUNTRY
dbUser.Type = JELLYFIN_USER
dbUser.Country = &Config.DEFAULT_COUNTRY
dbRes = s.db.Create(&dbUser)
dbRes = db.Create(&dbUser)
if dbRes.Error != nil {
slog.Error("Failed to create new user in db from jellyfin response", "error", dbRes.Error)
return AuthResponse{}, errors.New("failed to create new user from jellyfin")
@@ -256,10 +454,10 @@ func (s *Service) LoginJellyfin(userL *entity.User) (AuthResponse, error) {
if resp.AccessToken != "" {
slog.Debug("Jellyfin user login - updating user with new access token")
dbUser.ThirdPartyAuth = resp.AccessToken
s.db.Save(&dbUser)
db.Save(&dbUser)
}
token, err := s.signJWT(dbUser)
token, err := signJWT(dbUser)
if err != nil {
slog.Error("Failed to sign new (jellyfin login) jwt", "error", err)
return AuthResponse{}, errors.New("failed to get auth token")
@@ -268,13 +466,13 @@ func (s *Service) LoginJellyfin(userL *entity.User) (AuthResponse, error) {
}
// Login via Plex.
func (s *Service) LoginPlex(lr *plex.PlexLoginRequest) (AuthResponse, error) {
if s.cfg.PLEX_HOST == "" || s.cfg.PLEX_MACHINE_ID == "" {
func loginPlex(lr *PlexLoginRequest, db *gorm.DB) (AuthResponse, error) {
if Config.PLEX_HOST == "" || Config.PLEX_MACHINE_ID == "" {
slog.Error("Request made to login via Plex, but Plex authentication is disabled")
return AuthResponse{}, errors.New("plex login not enabled")
}
slog.Debug("A Plex User Is Logging In")
account, err := s.plexProvider.FetchPlexAccountFromToken(lr.AuthToken)
account, err := fetchPlexAccountFromToken(lr.AuthToken)
if err != nil {
slog.Error("loginPlex: Could not fetch Plex account", "error", err)
return AuthResponse{}, errors.New("could not fetch plex acount")
@@ -285,27 +483,27 @@ func (s *Service) LoginPlex(lr *plex.PlexLoginRequest) (AuthResponse, error) {
}
// Get users auth token against our home plex server.
// If no auth token, assume they don't have access to our plex server.
homeAuthToken, err := s.plexProvider.GetPlexHomeServerAuthToken(lr.AuthToken, lr.ClientIdentifier)
homeAuthToken, err := getPlexHomeServerAuthToken(lr.AuthToken, lr.ClientIdentifier)
if err != nil || homeAuthToken == "" {
slog.Error("loginPlex: Failed to get home server auth token for user! If not because the request failed, then ensure the user has access to our home servers library.", "error", err)
return AuthResponse{}, errors.New("failed to verify plex access")
}
dbUser := new(entity.User)
userIdQ := s.db.Select("user_id").Where("name = ? AND client_id = ?", "plex", account.Id).Table("user_services")
dbRes := s.db.Where("type = ?", entity.PLEX_USER).Where("id = (?)", userIdQ).Preload("UserServices").Take(&dbUser)
dbUser := new(User)
userIdQ := db.Select("user_id").Where("name = ? AND client_id = ?", "plex", account.Id).Table("user_services")
dbRes := db.Where("type = ?", PLEX_USER).Where("id = (?)", userIdQ).Preload("UserServices").Take(&dbUser)
if dbRes.Error != nil {
if errors.Is(dbRes.Error, gorm.ErrRecordNotFound) {
slog.Debug("loginPlex: New plex user attempted login.. creating Watcharr account now.")
dbUser.Username = account.Username
dbUser.Type = entity.PLEX_USER
dbUser.UserServices = append(dbUser.UserServices, entity.UserServices{
dbUser.Type = PLEX_USER
dbUser.UserServices = append(dbUser.UserServices, UserServices{
Name: "plex",
ClientID: strconv.FormatUint(account.Id, 10),
AuthToken: lr.AuthToken,
AuthToken2: homeAuthToken,
})
dbUser.Country = &s.cfg.DEFAULT_COUNTRY
dbRes = s.db.Create(&dbUser)
dbUser.Country = &Config.DEFAULT_COUNTRY
dbRes = db.Create(&dbUser)
if dbRes.Error != nil {
slog.Error("loginPlex: Failed to create new user in db from plex response", "error", dbRes.Error)
return AuthResponse{}, errors.New("failed to create new user from plex")
@@ -326,9 +524,9 @@ func (s *Service) LoginPlex(lr *plex.PlexLoginRequest) (AuthResponse, error) {
break
}
}
s.db.Save(&dbUser.UserServices)
db.Save(&dbUser.UserServices)
}
token, err := s.signJWT(dbUser)
token, err := signJWT(dbUser)
if err != nil {
slog.Error("loginPlex: Failed to sign new jwt", "error", err)
return AuthResponse{}, errors.New("failed to get auth token")
@@ -336,20 +534,19 @@ func (s *Service) LoginPlex(lr *plex.PlexLoginRequest) (AuthResponse, error) {
return AuthResponse{Token: token}, nil
}
// TODO the logic that gets and validated a token should be moved to Token service.
func (s *Service) UseAdminToken(req *UseAdminTokenRequest, userId uint) error {
var dbToken entity.Token
resp := s.db.Where("value = ?", req.Token).Take(&dbToken)
func useAdminToken(req *UseAdminTokenRequest, db *gorm.DB, userId uint) error {
var dbToken Token
resp := db.Where("value = ?", req.Token).Take(&dbToken)
if resp.Error != nil {
slog.Info("useAdminToken failed", "error", "token not found in db")
return errors.New("invalid token")
}
if dbToken.Type != entity.TOKENTYPE_ADMIN {
slog.Info("useAdminToken failed", "error", "token is of wrong type", "type_wanted", entity.TOKENTYPE_ADMIN, "type_actual", dbToken.Type)
if dbToken.Type != TOKENTYPE_ADMIN {
slog.Info("useAdminToken failed", "error", "token is of wrong type", "type_wanted", TOKENTYPE_ADMIN, "type_actual", dbToken.Type)
return errors.New("invalid token")
}
dur := time.Since(dbToken.CreatedAt)
if dur > token.TokenMaxAge {
if dur > tokenMaxAge {
slog.Info("useAdminToken failed", "error", "token in db has expired")
return errors.New("invalid token")
}
@@ -359,13 +556,13 @@ func (s *Service) UseAdminToken(req *UseAdminTokenRequest, userId uint) error {
}
// Token is valid and for current user.. give user admin.
// Incase removing the token after used fails, this is in a transaction so user wont be admin.
err := s.db.Transaction(func(tx *gorm.DB) error {
err := db.Transaction(func(tx *gorm.DB) error {
// Give user admin
if err := tx.Model(&entity.User{}).Where("id = ?", userId).Update("permissions", entity.PERM_ADMIN).Error; err != nil {
if err := tx.Model(&User{}).Where("id = ?", userId).Update("permissions", PERM_ADMIN).Error; err != nil {
return err
}
// Delete used token
if err := tx.Where("value = ?", req.Token).Delete(&entity.Token{}).Error; err != nil {
if err := tx.Where("value = ?", req.Token).Delete(&Token{}).Error; err != nil {
return err
}
// commit transaction if no errors
@@ -378,13 +575,13 @@ func (s *Service) UseAdminToken(req *UseAdminTokenRequest, userId uint) error {
return nil
}
func (s *Service) signJWT(user *entity.User) (token string, err error) {
func signJWT(user *User) (token string, err error) {
// Create new jwt with claim data
jwt := jwt.NewWithClaims(jwt.SigningMethodHS256, entity.TokenClaims{
UserID: user.ID,
Username: user.Username,
Type: user.Type,
RegisteredClaims: jwt.RegisteredClaims{
jwt := jwt.NewWithClaims(jwt.SigningMethodHS256, TokenClaims{
user.ID,
user.Username,
user.Type,
jwt.RegisteredClaims{
// ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)),
IssuedAt: jwt.NewNumericDate(time.Now()),
Issuer: "watcharr",
@@ -392,43 +589,28 @@ func (s *Service) signJWT(user *entity.User) (token string, err error) {
})
// Sign and get the complete encoded token as a string using the secret
return jwt.SignedString([]byte(s.cfg.JWT_SECRET))
return jwt.SignedString([]byte(Config.JWT_SECRET))
}
func (s *Service) hashPassword(password string, p *entity.ArgonParams) (encodedHash string, err error) {
salt, err := s.generateRandomBytes(p.SaltLength)
func hashPassword(password string, p *ArgonParams) (encodedHash string, err error) {
salt, err := generateRandomBytes(p.saltLength)
if err != nil {
return "", err
}
hash := argon2.IDKey(
[]byte(password),
salt,
p.Iterations,
p.Memory,
p.Parallelism,
p.KeyLength,
)
hash := argon2.IDKey([]byte(password), salt, p.iterations, p.memory, p.parallelism, p.keyLength)
// Base64 encode the salt and hashed password.
b64Salt := base64.RawStdEncoding.EncodeToString(salt)
b64Hash := base64.RawStdEncoding.EncodeToString(hash)
// Format hash in standard way.
encodedHash = fmt.Sprintf(
"$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
argon2.Version,
p.Memory,
p.Iterations,
p.Parallelism,
b64Salt,
b64Hash,
)
encodedHash = fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s", argon2.Version, p.memory, p.iterations, p.parallelism, b64Salt, b64Hash)
return encodedHash, nil
}
func (s *Service) generateRandomBytes(n uint32) ([]byte, error) {
func generateRandomBytes(n uint32) ([]byte, error) {
b := make([]byte, n)
_, err := rand.Read(b)
if err != nil {
@@ -438,23 +620,16 @@ func (s *Service) generateRandomBytes(n uint32) ([]byte, error) {
return b, nil
}
func (s *Service) compareHash(password, encodedHash string) (match bool, err error) {
func compareHash(password, encodedHash string) (match bool, err error) {
// Extract the parameters, salt and derived key from the encoded password
// hash.
p, salt, hash, err := s.decodeHash(encodedHash)
p, salt, hash, err := decodeHash(encodedHash)
if err != nil {
return false, err
}
// Derive the key from the other password using the same parameters.
otherHash := argon2.IDKey(
[]byte(password),
salt,
p.Iterations,
p.Memory,
p.Parallelism,
p.KeyLength,
)
otherHash := argon2.IDKey([]byte(password), salt, p.iterations, p.memory, p.parallelism, p.keyLength)
// Check that the contents of the hashed passwords are identical. Note
// that we are using the subtle.ConstantTimeCompare() function for this
@@ -465,7 +640,7 @@ func (s *Service) compareHash(password, encodedHash string) (match bool, err err
return false, nil
}
func (s *Service) decodeHash(encodedHash string) (p *entity.ArgonParams, salt, hash []byte, err error) {
func decodeHash(encodedHash string) (p *ArgonParams, salt, hash []byte, err error) {
vals := strings.Split(encodedHash, "$")
if len(vals) != 6 {
return nil, nil, nil, errors.New("the encoded hash is not in the correct format")
@@ -480,8 +655,8 @@ func (s *Service) decodeHash(encodedHash string) (p *entity.ArgonParams, salt, h
return nil, nil, nil, errors.New("incompatible version of argon2")
}
p = &entity.ArgonParams{}
_, err = fmt.Sscanf(vals[3], "m=%d,t=%d,p=%d", &p.Memory, &p.Iterations, &p.Parallelism)
p = &ArgonParams{}
_, err = fmt.Sscanf(vals[3], "m=%d,t=%d,p=%d", &p.memory, &p.iterations, &p.parallelism)
if err != nil {
return nil, nil, nil, err
}
@@ -490,27 +665,35 @@ func (s *Service) decodeHash(encodedHash string) (p *entity.ArgonParams, salt, h
if err != nil {
return nil, nil, nil, err
}
p.SaltLength = uint32(len(salt))
p.saltLength = uint32(len(salt))
hash, err = base64.RawStdEncoding.Strict().DecodeString(vals[5])
if err != nil {
return nil, nil, nil, err
}
p.KeyLength = uint32(len(hash))
p.keyLength = uint32(len(hash))
return p, salt, hash, nil
}
func (s *Service) UserChangePassword(pwds UserPasswordUpdateRequest, userId uint) error {
func hasPermission(perms int, reqPerm int) bool {
// Admins have permission for everything.
if perms&PERM_ADMIN == PERM_ADMIN {
return true
}
return (perms & reqPerm) == reqPerm
}
func userChangePassword(db *gorm.DB, pwds UserPasswordUpdateRequest, userId uint) error {
slog.Debug("userChangePassword request running", "user_id", userId)
user := new(entity.User)
res := s.db.Where("id = ?", userId).Select("password").Take(&user)
user := new(User)
res := db.Where("id = ?", userId).Select("password").Take(&user)
if res.Error != nil {
slog.Error("userChangePassword failed - failed to retrieve user from database", "user_id", userId, "error", res.Error)
return errors.New("failed to retrieve user")
}
slog.Debug("userChangePassword user found", "user_id", userId)
match, err := s.compareHash(pwds.OldPassword, user.Password)
match, err := compareHash(pwds.OldPassword, user.Password)
if err != nil {
slog.Error("userChangePassword failed - failed to compare passwords", "user_id", userId, "error", err)
return errors.New("failed to compare passwords")
@@ -521,13 +704,13 @@ func (s *Service) UserChangePassword(pwds UserPasswordUpdateRequest, userId uint
}
slog.Debug("userChangePassword hash for current password matches hash in the database", "user_id", userId)
slog.Debug("userChangePassword hashing new password", "user_id", userId)
hash, err := s.hashPassword(pwds.NewPassword, entity.GetPassArgonParams())
hash, err := hashPassword(pwds.NewPassword, GetPassArgonParams())
if err != nil {
slog.Error("userChangePassword failed - failed to hash new password", "user_id", userId, "error", err)
return errors.New("failed to hash new password")
}
slog.Debug("userChangePassword new password hashed", "user_id", userId)
if err := s.db.Model(&entity.User{}).Where("id = ?", userId).Update("password", hash).Error; err != nil {
if err := db.Model(&User{}).Where("id = ?", userId).Update("password", hash).Error; err != nil {
slog.Error("userChangePassword failed - failed to update password in database", "user_id", userId, "error", err)
return errors.New("failed to update password")
} else {

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