Compare commits
181 Commits
list-pagination-2
...
dev
| Author | SHA1 | Date | |
|---|---|---|---|
| fa34f1ead1 | |||
| cefed53c7f | |||
| 0d8b050615 | |||
| 63988f833f | |||
| e391d5dc69 | |||
| cba3d11f64 | |||
| 5d95aa4b41 | |||
| 41dff624bb | |||
| 39a77b4428 | |||
| 9b74728afb | |||
| 113ccbbbfd | |||
| 87033f423d | |||
| 3a52a9a592 | |||
| 9b39617650 | |||
| dd1503846d | |||
| 92edb75de9 | |||
| dc2b9a1a63 | |||
| 7b65c8af0f | |||
| cf3168d59c | |||
| fb1017f551 | |||
| bff354fcc3 | |||
| 0be6fdb346 | |||
| a73651808e | |||
| 9da0913d48 | |||
| 0a38171836 | |||
| d009528388 | |||
| cd34ecba61 | |||
| 769e30c9c7 | |||
| ba961bf5c3 | |||
| efddcaed07 | |||
| 76fdbe3cd0 | |||
| f4b7f66104 | |||
| 12ceb13bcb | |||
| 5a5ae0ad83 | |||
| 05e24e42c6 | |||
| e5d93fd8a2 | |||
| bf5d44f404 | |||
| 5abbb47fbf | |||
| 40b54c1065 | |||
| 3967a3f13f | |||
| 1f4b917661 | |||
| 2202b11e39 | |||
| d32a1ecb39 | |||
| 347113be68 | |||
| 68150b38ec | |||
| dc9e7e9309 | |||
| 6457146214 | |||
| baba8c8c60 | |||
| 31ddcacf47 | |||
| be94f1d2b7 | |||
| d7449642ba | |||
| dbc8b74893 | |||
| 9d5e489675 | |||
| 4e6e71687b | |||
| 8c8d604bc6 | |||
| 39b82335eb | |||
| 217be719e4 | |||
| 0da32164a3 | |||
| db72d05d79 | |||
| 88a7542064 | |||
| 19c773976d | |||
| a16c769273 | |||
| f022dc702c | |||
| c2f72dbd9c | |||
| d777630e84 | |||
| f5bfa29877 | |||
| 9b64932af1 | |||
| bf0594c1e8 | |||
| fee82df59d | |||
| 61382de4d2 | |||
| e65ba9d1d9 | |||
| 6654d85448 | |||
| eabdb47cfa | |||
| 643ca0fd38 | |||
| a08b19675a | |||
| 38fba0ac10 | |||
| f23552c170 | |||
| 448fdd9df3 | |||
| ca428327e2 | |||
| f7cca74a41 | |||
| 86286b967f | |||
| 8243838bfb | |||
| 5bebb754ed | |||
| c8920c911d | |||
| dd0bae137f | |||
| d5baee0df7 | |||
| 764a25be6c | |||
| c019162994 | |||
| 05f9813be8 | |||
| f285d1a8f4 | |||
| 4cc9bd3edb | |||
| 34f7f54e72 | |||
| 3fe2d2b155 | |||
| 3461a4ec74 | |||
| 475c9b6ab4 | |||
| 325666c30d | |||
| 92816b02a0 | |||
| 363c648964 | |||
| 2f929e99d5 | |||
| f14be89680 | |||
| ecd027f603 | |||
| f80f237143 | |||
| dbfc354353 | |||
| 28a6d85672 | |||
| b861cfcec3 | |||
| 08e0021535 | |||
| b3bf111f82 | |||
| 23ed5ffca8 | |||
| cc9f246c9a | |||
| 75d75248e1 | |||
| c34a0878b2 | |||
| 681212566b | |||
| df37de00e1 | |||
| fc900d8e93 | |||
| 57ce143ebe | |||
| 3eb2810a31 | |||
| b8598ba404 | |||
| 579428d86b | |||
| 4da8730b6f | |||
| e980a1f70e | |||
| f73105e9c7 | |||
| 755b08b746 | |||
| 5e412f67b9 | |||
| 4ee38a2625 | |||
| dc6ead0fb3 | |||
| a12faf8e72 | |||
| eb1b8b86c7 | |||
| dca1acbbd8 | |||
| 664caa6ba2 | |||
| a425abcdf2 | |||
| 13b15e03d0 | |||
| 3b4a5a27e6 | |||
| 13bd37c32c | |||
| 2d6d3c005c | |||
| f72f950871 | |||
| e4e015daf8 | |||
| 3db89f3214 | |||
| d379d3f147 | |||
| ac8d8769af | |||
| 7a7bd4f566 | |||
| ca82a36d23 | |||
| 1e6a97202b | |||
| 0e54a8c44a | |||
| 5c4c7be115 | |||
| f458eec732 | |||
| 8ad2208162 | |||
| 28c373173b | |||
| d637e04ba4 | |||
| 5fb92daf0c | |||
| 7f4da2d90e | |||
| 199a97e3a7 | |||
| af04698625 | |||
| a9f928a44c | |||
| 485408390b | |||
| 2bad7bc272 | |||
| 8d0642086c | |||
| 3b0b99ad9a | |||
| c16e0af3b2 | |||
| e0f49f25b2 | |||
| 7561b59037 | |||
| 72932f7acd | |||
| e7751807f6 | |||
| cb97aa3914 | |||
| d1e9a60beb | |||
| 0a09e71af7 | |||
| 404b7c680f | |||
| 9bb4f3f948 | |||
| 52bb995937 | |||
| 624a3b1bbf | |||
| a314231780 | |||
| ba6ae06a5f | |||
| fc4d65ccbc | |||
| d5f8644554 | |||
| 4b0abd13cc | |||
| c62c2cdfc0 | |||
| 8955cacee6 | |||
| 8fbf4ddc6d | |||
| 70f59697d3 | |||
| 22f77aa142 | |||
| 532d3f49c7 | |||
| 3ff325cda9 |
@@ -0,0 +1,2 @@
|
||||
server/data/
|
||||
server/Makefile
|
||||
@@ -1,15 +0,0 @@
|
||||
.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
|
||||
@@ -1,27 +0,0 @@
|
||||
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,
|
||||
},
|
||||
};
|
||||
@@ -1,5 +1,7 @@
|
||||
<!-- 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! -->
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
# 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"
|
||||
@@ -19,29 +19,29 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout Repo
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v7.0.0
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
uses: docker/setup-qemu-action@v4.2.0
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
uses: docker/setup-buildx-action@v4.2.0
|
||||
|
||||
- name: Log in to GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@v4.4.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@v4.4.0
|
||||
with:
|
||||
username: sbondco
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Build and push Docker image
|
||||
uses: docker/build-push-action@v6
|
||||
uses: docker/build-push-action@v7.3.0
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile
|
||||
|
||||
@@ -18,37 +18,37 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout Repo
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v7.0.0
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
uses: docker/setup-qemu-action@v4.2.0
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
uses: docker/setup-buildx-action@v4.2.0
|
||||
|
||||
- name: Log in to GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@v4.4.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@v4.4.0
|
||||
with:
|
||||
username: sbondco
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
uses: docker/metadata-action@v6.2.0
|
||||
with:
|
||||
images: |
|
||||
${{ env.image }}
|
||||
ghcr.io/${{ env.image }}
|
||||
|
||||
- name: Build and push Docker image
|
||||
uses: docker/build-push-action@v6
|
||||
uses: docker/build-push-action@v7.3.0
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile
|
||||
|
||||
@@ -21,10 +21,10 @@ jobs:
|
||||
run:
|
||||
working-directory: doc
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/checkout@v7.0.0
|
||||
- uses: actions/setup-node@v7.0.0
|
||||
with:
|
||||
node-version: 18
|
||||
node-version: 24
|
||||
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
|
||||
uses: peaceiris/actions-gh-pages@v4.1.0
|
||||
with:
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
# Build output to publish to the `gh-pages` branch:
|
||||
|
||||
@@ -16,10 +16,10 @@ jobs:
|
||||
run:
|
||||
working-directory: doc
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/checkout@v7.0.0
|
||||
- uses: actions/setup-node@v7.0.0
|
||||
with:
|
||||
node-version: 18
|
||||
node-version: 24
|
||||
cache: npm
|
||||
|
||||
- name: Install dependencies
|
||||
|
||||
@@ -11,12 +11,22 @@ on:
|
||||
- "server/**"
|
||||
|
||||
jobs:
|
||||
format_check_go:
|
||||
test_and_format_check_go:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
defaults:
|
||||
run:
|
||||
working-directory: server
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
- 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 ./...
|
||||
|
||||
- name: gofmt test
|
||||
run: |
|
||||
|
||||
@@ -21,12 +21,12 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout repo
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v7.0.0
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@v7.0.0
|
||||
with:
|
||||
node-version: "20"
|
||||
node-version: 24
|
||||
cache: "npm"
|
||||
|
||||
- name: Get dependencies
|
||||
|
||||
@@ -4,8 +4,14 @@ 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!
|
||||
|
||||
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!).
|
||||
Big pull requests (anything more than a few lines) should 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!
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
#
|
||||
# Backend
|
||||
#
|
||||
FROM golang:1.25-alpine AS server
|
||||
FROM golang:1.26-alpine AS server
|
||||
|
||||
WORKDIR /server
|
||||
COPY server/*.go server/go.* ./
|
||||
COPY server/arr/*.go ./arr/
|
||||
COPY server/game/*.go ./game/
|
||||
|
||||
# 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/ ./
|
||||
|
||||
# Required so we can build with cgo
|
||||
RUN apk update && apk add --no-cache musl-dev gcc build-base
|
||||
@@ -17,7 +18,7 @@ RUN go mod download && GOOS=linux CGO_ENABLED=1 CGO_CFLAGS="-D_LARGEFILE64_SOURC
|
||||
#
|
||||
# Frontend
|
||||
#
|
||||
FROM node:20-alpine AS ui
|
||||
FROM node:24-alpine AS ui
|
||||
|
||||
WORKDIR /app
|
||||
COPY package*.json vite.config.ts svelte.config.js tsconfig.json ./
|
||||
@@ -29,7 +30,7 @@ RUN npm install && npm run build
|
||||
#
|
||||
# Production
|
||||
#
|
||||
FROM node:20-alpine AS runner
|
||||
FROM node:24-alpine AS runner
|
||||
|
||||
COPY --from=server /server/watcharr /
|
||||
COPY --from=ui /app/build /ui
|
||||
|
||||
@@ -4,7 +4,7 @@ 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.
|
||||
|
||||
Have a look at when this document was last updated, it may have missing features.
|
||||
**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:
|
||||
@@ -25,10 +25,12 @@ Have a look at when this document was last updated, it may have missing features
|
||||
- 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 content
|
||||
- Searching for media
|
||||
- Inline filters (ex: `y:2008` to get media released in 2008)
|
||||
- Custom tags
|
||||
- Discovery page
|
||||
- Following other users
|
||||
|
||||
@@ -16,9 +16,19 @@ With [some extra configuration](https://watcharr.app/docs/server_config/game-sup
|
||||
|
||||
I am built with Go and Svelte(Kit).
|
||||
|
||||
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/)
|
||||
### Demo
|
||||
|
||||
[Track progress for the next version](https://github.com/orgs/sbondCo/projects/9/views/3).
|
||||
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).
|
||||
|
||||
### Contents
|
||||
|
||||
@@ -26,6 +36,7 @@ Feel free to abuse this demo instance (nicely), which runs on the latest `dev` b
|
||||
- [Set Up](#set-up)
|
||||
- [Community Made Tools](#community-made-tools)
|
||||
- [Getting Help](#getting-help)
|
||||
- [License](#license)
|
||||
- [Contributing](#contributing)
|
||||
|
||||
# Screenshots
|
||||
@@ -72,6 +83,8 @@ 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/>.
|
||||
|
||||
|
After Width: | Height: | Size: 6.4 KiB |
|
After Width: | Height: | Size: 90 KiB |
|
After Width: | Height: | Size: 36 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 55 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 8.4 KiB |
|
After Width: | Height: | Size: 31 KiB |
|
After Width: | Height: | Size: 7.0 KiB |
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 118 KiB |
|
After Width: | Height: | Size: 284 KiB |
|
After Width: | Height: | Size: 38 KiB |
|
After Width: | Height: | Size: 8.4 KiB |
|
After Width: | Height: | Size: 28 KiB |
|
After Width: | Height: | Size: 27 KiB |
|
After Width: | Height: | Size: 85 KiB |
|
After Width: | Height: | Size: 62 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 9.1 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 273 KiB |
|
After Width: | Height: | Size: 118 KiB |
|
After Width: | Height: | Size: 41 KiB |
|
After Width: | Height: | Size: 34 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 7.9 KiB |
|
After Width: | Height: | Size: 5.1 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 878 KiB |
|
After Width: | Height: | Size: 360 KiB |
@@ -0,0 +1,5 @@
|
||||
## Changelog Data
|
||||
|
||||
Changelog images, etc go in this folder.
|
||||
|
||||
[View the real changelog for Watcharr.](../CHANGELOG.md)
|
||||
@@ -14,7 +14,12 @@ Hopefully it is useful for others with similar files or in scenarios where its t
|
||||
|
||||
## Format
|
||||
|
||||
Each line is a new entry. The name of the content (show/movie) must be provided, the year can be optionally provided surrounded by brackets. 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.
|
||||
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>)]
|
||||
|
||||
@@ -11,6 +11,19 @@ You may consider a backup of your server before starting any import. They are no
|
||||
**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. Press `Start Import`.
|
||||
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.
|
||||
|
||||
@@ -17,7 +17,7 @@ This section assumes you will be forking the repo on Github, of course you can a
|
||||
|
||||

|
||||
|
||||
2. Get the code by cloning your fork
|
||||
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).
|
||||
|
||||
```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)
|
||||
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.
|
||||
|
||||
```
|
||||
go get .
|
||||
@@ -44,16 +44,18 @@ 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
|
||||
npm run dev
|
||||
make
|
||||
```
|
||||
|
||||
2. Run the server (second terminal, in the project root folder)
|
||||
2. Run the server (second terminal, in the `server` folder)
|
||||
|
||||
```bash
|
||||
npm run server
|
||||
make
|
||||
```
|
||||
|
||||
**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):
|
||||
|
||||
@@ -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` Your database, holds all users, their watchlists, etc.
|
||||
- `watcharr.db` & `watcharr.db-wal` 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).
|
||||
|
||||
@@ -14,17 +14,17 @@
|
||||
"write-heading-ids": "docusaurus write-heading-ids"
|
||||
},
|
||||
"dependencies": {
|
||||
"@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"
|
||||
"@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"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@docusaurus/module-type-aliases": "3.1.1"
|
||||
"@docusaurus/module-type-aliases": "3.9.2"
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
@@ -39,6 +39,6 @@
|
||||
]
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.0"
|
||||
"node": ">=20.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import React from "react";
|
||||
import clsx from "clsx";
|
||||
import styles from "./styles.module.css";
|
||||
|
||||
@@ -8,18 +7,18 @@ const FeatureList = [
|
||||
Svg: require("@site/static/img/icon/code-slash.svg").default,
|
||||
description: (
|
||||
<>
|
||||
Watcharr is free and open source software distributed under the MIT
|
||||
license. Feel free to browse, modify or contribute!
|
||||
Free and open source, distributed under the GPLv3 license. Feel free to
|
||||
browse, modify or contribute!
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: "Simple",
|
||||
title: "Simple & Intuitive",
|
||||
Svg: require("@site/static/img/icon/happy.svg").default,
|
||||
description: (
|
||||
<>
|
||||
Watcharr is incredibly easy to dive into. Install without hassle and get
|
||||
started with the seamless and intuitive user experience.
|
||||
Incredibly easy to dive into. Install within the minute and get started
|
||||
with the seamless experience.
|
||||
</>
|
||||
),
|
||||
},
|
||||
@@ -28,8 +27,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 Watcharr is built with
|
||||
Go and Svelte.
|
||||
Don't know what else to add here, so now you know I'm built with Go and
|
||||
Svelte.
|
||||
</>
|
||||
),
|
||||
},
|
||||
|
||||
@@ -39,32 +39,37 @@ export function HomepageTwoColFeats() {
|
||||
<TwoColFeat
|
||||
title="Neat UI"
|
||||
description="We just look lightweight."
|
||||
imgSrc="https://github.com/sbondCo/Watcharr/raw/dev/screenshot/homepage.png?v=2"
|
||||
imgSrc="https://github.com/sbondCo/Watcharr/raw/dev/screenshot/homepage.png?v=3"
|
||||
/>
|
||||
<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=2"
|
||||
imgSrc="https://github.com/sbondCo/Watcharr/raw/dev/screenshot/homepage-poster-change-status.png?v=3"
|
||||
/>
|
||||
<TwoColFeat
|
||||
title="In-Depth Details"
|
||||
description="About your favourite content."
|
||||
imgSrc="https://github.com/sbondCo/Watcharr/raw/dev/screenshot/content-details-page.png?v=2"
|
||||
imgSrc="https://github.com/sbondCo/Watcharr/raw/dev/screenshot/content-details-page.png?v=3"
|
||||
/>
|
||||
<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=2"
|
||||
imgSrc="https://github.com/sbondCo/Watcharr/raw/dev/screenshot/user-profile.png?v=3"
|
||||
/>
|
||||
<TwoColFeat
|
||||
title="Discovery"
|
||||
description="Find the latest trending content."
|
||||
imgSrc="https://github.com/sbondCo/Watcharr/raw/dev/screenshot/discover-page.png?v=2"
|
||||
imgSrc="https://github.com/sbondCo/Watcharr/raw/dev/screenshot/discover-page.png?v=3"
|
||||
/>
|
||||
<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=2"
|
||||
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"
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
|
||||
@@ -4,8 +4,8 @@ services:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
container_name: watcharr
|
||||
container_name: watcharr-dev
|
||||
ports:
|
||||
- 3080:3080
|
||||
- 3081:3080
|
||||
volumes:
|
||||
- ./container_data:/data
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
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",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
);
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "watcharr",
|
||||
"license": "GPL-3.0-only",
|
||||
"version": "2.1.1",
|
||||
"version": "4.2.1",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "vite dev",
|
||||
@@ -10,33 +10,33 @@
|
||||
"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 . && eslint .",
|
||||
"lint": "prettier --check ./src/ && eslint ./src/",
|
||||
"format": "prettier --write ."
|
||||
},
|
||||
"devDependencies": {
|
||||
"@sveltejs/adapter-node": "^5.2.12",
|
||||
"@sveltejs/kit": "^2.21.0",
|
||||
"@types/papaparse": "^5.3.15",
|
||||
"@typescript-eslint/eslint-plugin": "^8.32.1",
|
||||
"@typescript-eslint/parser": "^8.32.1",
|
||||
"@vite-pwa/sveltekit": "^0.6.6",
|
||||
"eslint": "^8.57.0",
|
||||
"eslint-config-prettier": "^10.1.2",
|
||||
"eslint-plugin-svelte": "^2.45.1",
|
||||
"prettier": "^3.4.2",
|
||||
"prettier-plugin-svelte": "^3.4.0",
|
||||
"sass": "^1.97.3",
|
||||
"svelte": "^5.17.3",
|
||||
"svelte-check": "^4.1.3",
|
||||
"svelte-eslint-parser": "^0.42.0",
|
||||
"svelte-preprocess": "^6.0.3",
|
||||
"typescript": "^5.8.3",
|
||||
"vite": "^6.3.5"
|
||||
"@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"
|
||||
},
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"axios": "^1.9.0",
|
||||
"blurhash": "^2.0.5",
|
||||
"papaparse": "^5.4.1"
|
||||
"blurhash": "2.0.5",
|
||||
"papaparse": "5.4.1"
|
||||
}
|
||||
}
|
||||
|
||||
|
Before Width: | Height: | Size: 488 KiB After Width: | Height: | Size: 520 KiB |
|
Before Width: | Height: | Size: 342 KiB After Width: | Height: | Size: 510 KiB |
|
Before Width: | Height: | Size: 2.3 MiB After Width: | Height: | Size: 2.0 MiB |
|
Before Width: | Height: | Size: 900 KiB After Width: | Height: | Size: 805 KiB |
|
Before Width: | Height: | Size: 1.1 MiB After Width: | Height: | Size: 997 KiB |
|
Before Width: | Height: | Size: 1.0 MiB After Width: | Height: | Size: 900 KiB |
|
Before Width: | Height: | Size: 1.0 MiB After Width: | Height: | Size: 913 KiB |
|
Before Width: | Height: | Size: 1.1 MiB After Width: | Height: | Size: 989 KiB |
|
After Width: | Height: | Size: 1.1 MiB |
|
After Width: | Height: | Size: 393 KiB |
|
After Width: | Height: | Size: 279 KiB |
|
After Width: | Height: | Size: 777 KiB |
|
Before Width: | Height: | Size: 75 KiB After Width: | Height: | Size: 60 KiB |
@@ -1 +1 @@
|
||||
3.0.0
|
||||
4.2.1
|
||||
@@ -53,6 +53,12 @@ func CreateCacheKey(name string, u ...any) string {
|
||||
}
|
||||
case int:
|
||||
appnd(strconv.Itoa(vv))
|
||||
case bool:
|
||||
if vv {
|
||||
appnd("1")
|
||||
} else {
|
||||
appnd("0")
|
||||
}
|
||||
default:
|
||||
// This should never happen, but incase of unknown
|
||||
// value passed, hopefully this should make it easier
|
||||
|
||||
@@ -81,7 +81,7 @@ type ServerConfig struct {
|
||||
|
||||
SONARR []cfgmodel.SonarrSettings `json:",omitempty"`
|
||||
RADARR []cfgmodel.RadarrSettings `json:",omitempty"`
|
||||
TWITCH igdb.IGDB `json:",omitempty"`
|
||||
TWITCH igdb.IGDB `json:",omitzero"`
|
||||
|
||||
// Optional: Schedule for tasks.
|
||||
TASK_SCHEDULE map[string]int `json:",omitempty"`
|
||||
@@ -212,6 +212,13 @@ func (c *ServerConfig) SaveTwitchConfig(newt igdb.IGDB) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *ServerConfig) TwitchEnabled() bool {
|
||||
if c.TWITCH.ClientID != nil && c.TWITCH.ClientSecret != nil {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Read config file
|
||||
// Calls generateConfig if file doesn't exist
|
||||
func read() (*ServerConfig, error) {
|
||||
|
||||
@@ -1,26 +1,58 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"path"
|
||||
"time"
|
||||
|
||||
"github.com/sbondCo/Watcharr/config"
|
||||
"github.com/sbondCo/Watcharr/database/entity"
|
||||
"github.com/sbondCo/Watcharr/database/migrate"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Create a new database connection.
|
||||
// Also runs migrations, etc, before returning connection.
|
||||
// Any error returned from this func should always make our app Exit (caller
|
||||
// handled).
|
||||
//
|
||||
// NOTE: Our mock db used in tests mimics this function, so if this func is
|
||||
// changed, you should look at the mock db to make it match if it makes
|
||||
// sense, so our tests stay accurate to prod.
|
||||
func New() (*gorm.DB, error) {
|
||||
slog.Info("New: Opening new database connection")
|
||||
// Open the database.
|
||||
db, err := gorm.Open(
|
||||
sqlite.Open(path.Join(config.DataPath, "watcharr.db")),
|
||||
&gorm.Config{TranslateError: true},
|
||||
)
|
||||
if err != nil {
|
||||
slog.Error("New: Opening database failed.")
|
||||
return nil, err
|
||||
}
|
||||
// Setup the db (migrations, etc)
|
||||
if err := Setup(db); err != nil {
|
||||
slog.Error("New: Setting up connection failed!", "error", err)
|
||||
return nil, err
|
||||
}
|
||||
return db, nil
|
||||
}
|
||||
|
||||
// Setup configures our db connection and applies migrations.
|
||||
//
|
||||
// NOTE: This exists as a separate function so it can be reused by our testutil
|
||||
// package that we want to have configured in the same way as the main db so
|
||||
// that tests reflect real life.
|
||||
func Setup(db *gorm.DB) error {
|
||||
if err := configure(db); err != nil {
|
||||
slog.Error("Setup: Configuring connection failed!", "error", err)
|
||||
return err
|
||||
}
|
||||
// Perform auto migration.
|
||||
err = db.AutoMigrate(
|
||||
slog.Info("Setup: AutoMigrating")
|
||||
err := db.AutoMigrate(
|
||||
&migrate.MigrationRecord{},
|
||||
&entity.User{},
|
||||
&entity.UserServices{},
|
||||
&entity.Content{},
|
||||
@@ -36,7 +68,123 @@ func New() (*gorm.DB, error) {
|
||||
&entity.Tag{},
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
slog.Error("Setup: Auto migration failed.")
|
||||
return err
|
||||
}
|
||||
return db, nil
|
||||
slog.Info("Setup: AutoMigrated")
|
||||
// Perform our manual migrations.
|
||||
if err := migrate.Now(db); err != nil {
|
||||
slog.Error("Setup: Manual migrations failed.", "error", err)
|
||||
return err
|
||||
}
|
||||
// Optimize database.
|
||||
if err := optimize(db); err != nil {
|
||||
slog.Error("Setup: Optimizing database failed.", "error", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Configure our SQLite database connection.
|
||||
// Some PRAGMAs need to be defined per-connection, so we do that here.
|
||||
func configure(db *gorm.DB) error {
|
||||
slog.Info("configure: Configuring connection.")
|
||||
|
||||
// Synchronous: https://sqlite.org/pragma.html#pragma_synchronous
|
||||
// Configured to `FULL` because I'm slightly confused.
|
||||
// `NORMAL` is recommended for most apps with WAL, but you
|
||||
// lose "durability", which doesn't sound like a good thing to me...
|
||||
// personally I'm okay with less performance for the best durability.
|
||||
if res := db.Exec("PRAGMA synchronous=2"); res.Error != nil {
|
||||
slog.Error("configure: Configuring synchronous failed!")
|
||||
return res.Error
|
||||
}
|
||||
slog.Info("configure: Configured synchronous.")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Optimize the database.
|
||||
func optimize(db *gorm.DB) error {
|
||||
slog.Info("optimize: Running optimizations.")
|
||||
|
||||
// WAL Checkpoint (aka commit anything in the WAL to the main db).
|
||||
// Seems best to do this to make sure it has happened, especially since
|
||||
// we are running vacuum next.
|
||||
// https://sqlite.org/pragma.html#pragma_wal_checkpoint
|
||||
timeBeforeQuery := time.Now()
|
||||
if res := db.Exec("PRAGMA wal_checkpoint(TRUNCATE)"); res.Error != nil {
|
||||
slog.Error("optimize: Checkpoint failed!")
|
||||
return res.Error
|
||||
}
|
||||
slog.Info("optimize: Checkpointed.", "took", time.Since(timeBeforeQuery))
|
||||
|
||||
// Optimize pragma.
|
||||
// Running with recommended argument for our new long-living connection.
|
||||
// https://sqlite.org/pragma.html#pragma_optimize
|
||||
timeBeforeQuery = time.Now()
|
||||
if res := db.Exec("PRAGMA optimize=0x10002"); res.Error != nil {
|
||||
slog.Error("optimize: Optimize pragma failed!")
|
||||
return res.Error
|
||||
}
|
||||
slog.Info("optimize: Optimize pragma succeeded.",
|
||||
"took", time.Since(timeBeforeQuery))
|
||||
|
||||
// Vacuum.
|
||||
// > VACUUM rebuilds the database file, repacking it into a minimal amount
|
||||
// > of disk space.
|
||||
// https://sqlite.org/lang_vacuum.html
|
||||
timeBeforeQuery = time.Now()
|
||||
if res := db.Exec("VACUUM"); res.Error != nil {
|
||||
slog.Error("optimize: Vacuum failed!")
|
||||
return res.Error
|
||||
}
|
||||
slog.Info("optimize: Vacuumed successfully.",
|
||||
"took", time.Since(timeBeforeQuery))
|
||||
|
||||
// WAL Checkpoint (aka commit anything in the WAL to the main db).
|
||||
// Do this after vacuum too to ensure we have a clean slate for this
|
||||
// startup.
|
||||
// https://sqlite.org/pragma.html#pragma_wal_checkpoint
|
||||
timeBeforeQuery = time.Now()
|
||||
if res := db.Exec("PRAGMA wal_checkpoint(TRUNCATE)"); res.Error != nil {
|
||||
slog.Error("optimize: Checkpoint failed!")
|
||||
return res.Error
|
||||
}
|
||||
slog.Info("optimize: Checkpointed.", "took", time.Since(timeBeforeQuery))
|
||||
|
||||
slog.Info("optimize: Done.")
|
||||
return nil
|
||||
}
|
||||
|
||||
// Optimize task that is scheduled and ran every whenever.
|
||||
// So this func is for optimzations that we want to re-run every time the
|
||||
// task is scheduled for.
|
||||
func TaskOptimize(db *gorm.DB) error {
|
||||
slog.Info("TaskOptimize: Running optimizations.")
|
||||
|
||||
// WAL Checkpoint (aka commit anything in the WAL to the main db).
|
||||
// To avoid our WAL file becoming huge, we checkpoint regularly.
|
||||
// https://sqlite.org/pragma.html#pragma_wal_checkpoint
|
||||
timeBeforeQuery := time.Now()
|
||||
if res := db.Exec("PRAGMA wal_checkpoint(TRUNCATE)"); res.Error != nil {
|
||||
slog.Error("TaskOptimize: Checkpoint failed!")
|
||||
return res.Error
|
||||
}
|
||||
slog.Info("TaskOptimize: Checkpointed.",
|
||||
"took", time.Since(timeBeforeQuery))
|
||||
|
||||
// Optimize pragma.
|
||||
// No args for our task as recommended.
|
||||
// https://sqlite.org/pragma.html#pragma_optimize
|
||||
timeBeforeQuery = time.Now()
|
||||
if res := db.Exec("PRAGMA optimize"); res.Error != nil {
|
||||
slog.Error("TaskOptimize: Optimize pragma failed!")
|
||||
return res.Error
|
||||
}
|
||||
slog.Info("TaskOptimize: Optimize pragma succeeded.",
|
||||
"took", time.Since(timeBeforeQuery))
|
||||
|
||||
slog.Info("TaskOptimize: Done.")
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -12,3 +12,11 @@ type GormModel struct {
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
|
||||
}
|
||||
|
||||
// Same as GormModel, but without the DeletedAt field,
|
||||
// so use this for tables where we don't need soft deletion.
|
||||
type GormModelNoDel struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ type Activity struct {
|
||||
// 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"`
|
||||
WatchedID uint `json:"watchedId" gorm:"not null;index"`
|
||||
// Type of activity.
|
||||
Type ActivityType `json:"type" gorm:"not null"`
|
||||
// Holds custom data (ex, if rating changed, this can
|
||||
@@ -54,4 +54,18 @@ type Activity struct {
|
||||
Data string `json:"data" gorm:"not null"`
|
||||
// Custom date for the activity, that the user can define.
|
||||
CustomDate *time.Time `json:"customDate,omitempty"`
|
||||
// Count this Activity as a Play?
|
||||
// Currently this was the best way I could see forward for implementing
|
||||
// counting plays of media that doesn't involve inefficient querying of
|
||||
// the actitivties table (or a whole new table, which would create extra
|
||||
// complexities itself, ie, plays/activity showing different records).
|
||||
// We write to this field when creating the activity to count is as a play
|
||||
// or not (ie when we create STATUS CHANGE activities with status of
|
||||
// FINISHED, imports, etc).
|
||||
// We won't support the user (or the system) modifying this value after
|
||||
// creation; if the user wants to delete a 'Play', they should delete the
|
||||
// activity.
|
||||
// Indexed (check migrations) to make search faster, since we frequently
|
||||
// do it over the whole table for watched sorting at the moment.
|
||||
CountAsPlay bool `json:"countAsPlay"`
|
||||
}
|
||||
|
||||
@@ -12,6 +12,18 @@ const (
|
||||
DROPPED WatchedStatus = "DROPPED"
|
||||
)
|
||||
|
||||
func (r WatchedStatus) IsValid() bool {
|
||||
switch r {
|
||||
case FINISHED,
|
||||
WATCHING,
|
||||
PLANNED,
|
||||
HOLD,
|
||||
DROPPED:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type Watched struct {
|
||||
dbmodel.GormModel
|
||||
Status WatchedStatus `json:"status"`
|
||||
|
||||
@@ -8,7 +8,7 @@ import "github.com/sbondCo/Watcharr/database/dbmodel"
|
||||
// since episodes can be removed and re-added. For this reason we store season and episodes nums instead
|
||||
// of just the episode id.
|
||||
type WatchedEpisode struct {
|
||||
dbmodel.GormModel
|
||||
dbmodel.GormModelNoDel
|
||||
UserID uint `json:"-" gorm:"not null"`
|
||||
User User `json:"-"`
|
||||
WatchedID uint `json:"-" gorm:"uniqueIndex:we_watched_to_ens;not null"`
|
||||
|
||||
@@ -4,7 +4,7 @@ import "github.com/sbondCo/Watcharr/database/dbmodel"
|
||||
|
||||
// UniqueIndex applied between WatchedID and SeasonNumber to avoid duplicates incase logic fails.
|
||||
type WatchedSeason struct {
|
||||
dbmodel.GormModel
|
||||
dbmodel.GormModelNoDel
|
||||
UserID uint `json:"-" gorm:"not null"`
|
||||
User User `json:"-"`
|
||||
WatchedID uint `json:"-" gorm:"uniqueIndex:ws_watched_to_season_num;not null"`
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
package migrate
|
||||
|
||||
import "time"
|
||||
|
||||
// Record of all our applied migrations.
|
||||
type MigrationRecord struct {
|
||||
// Migration ID
|
||||
ID string `gorm:"primarykey"`
|
||||
// When migration was applied on this db.
|
||||
CreatedAt time.Time
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package migrate
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Migration struct {
|
||||
// ID of migration, stick to YYYYMMDDHHMM.
|
||||
ID string
|
||||
// Apply migration func.
|
||||
Up func(tx *gorm.DB) error
|
||||
// When `true`, the migration is not run inside of a transaction.
|
||||
// You should only use this when is required by sqlite that the command
|
||||
// we need to run for eg cannot be ran from within a transaction!
|
||||
// YOU SHOULD ENSURE YOU ONLY RUN ONE COMMAND PER MIGRATION WHEN USING
|
||||
// THIS WITH `TRUE` TO AVOID BEING LEFT IN A BAD OR INCOMPLETE STATE!!!
|
||||
//
|
||||
// ALSO: All statements used with this should take into account that since,
|
||||
// it isn't inside of a transaction, it's possible the migration succeeds,
|
||||
// but creating the record of it doesn't. If a user starts the server again
|
||||
// after we error in this case, the migration will run again, so it must
|
||||
// not break data integrity or make any assumptions of it being the first
|
||||
// time running!
|
||||
UNSAFE bool
|
||||
}
|
||||
|
||||
// Start our migrations.
|
||||
// NOTE: This is only to be ran after GORM's AutoMigrate.
|
||||
func Now(db *gorm.DB) error {
|
||||
slog.Info("Starting migrations.")
|
||||
|
||||
for _, mig := range migrations {
|
||||
slog.Debug("Processing migration.", "id", mig.ID)
|
||||
|
||||
migRecord := MigrationRecord{ID: mig.ID}
|
||||
|
||||
// First ensure that the migration hasn't already been applied.
|
||||
var alreadyApplied int64
|
||||
res := db.
|
||||
Model(&MigrationRecord{}).
|
||||
Where(&migRecord).
|
||||
Count(&alreadyApplied)
|
||||
if res.Error != nil {
|
||||
slog.Error("already applied check failed!")
|
||||
return res.Error
|
||||
}
|
||||
if alreadyApplied > 0 {
|
||||
// If record exists in our table, then migration was applied
|
||||
// already, so skip processing it.
|
||||
slog.Debug("Migration already applied.", "id", mig.ID)
|
||||
continue
|
||||
}
|
||||
|
||||
slog.Info("Migration has NOT been applied before.. applying.",
|
||||
"id", mig.ID)
|
||||
|
||||
// Timing the migration.
|
||||
timeBeforeMig := time.Now()
|
||||
|
||||
// Apply the migration.
|
||||
if mig.UNSAFE {
|
||||
// Unsafe migrations are not ran inside of a transaction
|
||||
// and are only used when required by sqlite engine.
|
||||
if err := mig.Up(db); err != nil {
|
||||
slog.Error("Migration failed!", "id", mig.ID, "error", err)
|
||||
return err
|
||||
}
|
||||
// Record the migration record.
|
||||
if res := db.Create(&migRecord); res.Error != nil {
|
||||
slog.Error("Unsafe migration succeeded, but we failed to create the record of it!",
|
||||
"id", mig.ID, "error", res.Error)
|
||||
return res.Error
|
||||
}
|
||||
} else {
|
||||
// Migrations go through a transaction wrapper.
|
||||
err := db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := mig.Up(tx); err != nil {
|
||||
// Errored.. rollback any changes made.
|
||||
return err
|
||||
}
|
||||
// Migration succeeded.. record it.
|
||||
// If the Create succeeds, all will be committed.
|
||||
return tx.Create(&migRecord).Error
|
||||
})
|
||||
if err != nil {
|
||||
// If any migration fails, we return here.
|
||||
slog.Error("Migration failed!", "id", mig.ID, "error", err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
slog.Info("Migration applied successfully.",
|
||||
"id", mig.ID,
|
||||
"duration", time.Since(timeBeforeMig))
|
||||
}
|
||||
|
||||
slog.Info("Done processing all migrations.")
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package migrate
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
"strings"
|
||||
|
||||
"github.com/sbondCo/Watcharr/database/entity"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// NOTE: For obvious reasons, once a migration is created and in production,
|
||||
// it is set in stone, so there should be almost no reason to change an existing
|
||||
// migration, create a new one instead!
|
||||
// If it's not obvious, changing an existing migration won't apply for people
|
||||
// who already have applied it and only apply for people who haven't yet,
|
||||
// so we are risking splitting the consistency of everyones databases as a
|
||||
// whole. I can't forsee any circumstance that would require doing so..
|
||||
|
||||
var migrations = []Migration{
|
||||
{
|
||||
// Backfilling `plays` data from users Activity.
|
||||
// (we have just created the 'count_as_play' column, instead of starting
|
||||
// existing data from 0 plays, we can check what existing activities
|
||||
// should count, and count them).
|
||||
ID: "202603201715_0001",
|
||||
Up: func(tx *gorm.DB) error {
|
||||
migID := "202603201715_0001"
|
||||
slog.Info("Migration is starting.", "mig", migID)
|
||||
// For ADDED_WATCHED and STATUS_CHANGED activities where the data
|
||||
// holds something saying FINISHED somewhere, count as a play.
|
||||
res := tx.
|
||||
Model(&entity.Activity{}).
|
||||
Where(
|
||||
`type IN ? AND data LIKE "%FINISHED%"`,
|
||||
[]entity.ActivityType{
|
||||
entity.ADDED_WATCHED,
|
||||
entity.STATUS_CHANGED,
|
||||
},
|
||||
).
|
||||
Update("count_as_play", 1)
|
||||
if res.Error != nil {
|
||||
slog.Error("First step failed!", "mig", migID,
|
||||
"error", res.Error)
|
||||
return res.Error
|
||||
}
|
||||
slog.Info("First step succeeded, continuing.", "mig", migID)
|
||||
// For IMPORTED_ADDED_WATCHED* activities, we don't need to check
|
||||
// data (since there isn't any). We know these should always count
|
||||
// as a play, so count them.
|
||||
res = tx.
|
||||
Model(&entity.Activity{}).
|
||||
Where("type IN ?", []entity.ActivityType{
|
||||
entity.IMPORTED_ADDED_WATCHED,
|
||||
entity.IMPORTED_ADDED_WATCHED_JF,
|
||||
entity.IMPORTED_ADDED_WATCHED_PLEX,
|
||||
}).
|
||||
Update("count_as_play", 1)
|
||||
if res.Error != nil {
|
||||
slog.Error("Second step failed!", "mig", migID,
|
||||
"error", res.Error)
|
||||
return res.Error
|
||||
}
|
||||
slog.Info("Second step succeeded, continuing.", "mig", migID)
|
||||
return nil
|
||||
},
|
||||
},
|
||||
{
|
||||
// Dropping `deleted_at` columns for `watched_seasons` and
|
||||
// `watched_episodes` tables since we do not use them.
|
||||
ID: "202604142234_0002",
|
||||
Up: func(tx *gorm.DB) error {
|
||||
migID := "202604142234_0002"
|
||||
slog.Info("Migration is starting.", "mig", migID)
|
||||
|
||||
// Drop deleted_at for watched_seasons
|
||||
err := tx.Migrator().DropColumn(&entity.WatchedSeason{}, "deleted_at")
|
||||
if err != nil {
|
||||
slog.Error("watched_seasons migration failed!", "mig", migID)
|
||||
return err
|
||||
}
|
||||
slog.Info("watched_seasons migration succeeded.", "mig", migID)
|
||||
|
||||
// Drop deleted_at for watched_episodes
|
||||
err = tx.Migrator().DropColumn(&entity.WatchedEpisode{}, "deleted_at")
|
||||
if err != nil {
|
||||
slog.Error("watched_episodes migration failed!", "mig", migID)
|
||||
return err
|
||||
}
|
||||
slog.Info("watched_episodes migration succeeded.", "mig", migID)
|
||||
|
||||
slog.Info("Migration complete.", "mig", migID)
|
||||
return nil
|
||||
},
|
||||
},
|
||||
{
|
||||
// Moving to using WAL journal_mode for our sqlite database, which
|
||||
// should grant us improvements in all areas.
|
||||
// https://sqlite.org/pragma.html#pragma_journal_mode
|
||||
ID: "202604162229_0003",
|
||||
// NOTE: We are using `unsafe` so that this migration isn't ran inside
|
||||
// of a transaction (can't change into WAL from within one), so we
|
||||
// MUST ENSURE we are only doing one thing!
|
||||
UNSAFE: true,
|
||||
Up: func(db *gorm.DB) error {
|
||||
migID := "202604162229_0003"
|
||||
slog.Info("Migration is starting.", "mig", migID)
|
||||
|
||||
var mode string
|
||||
res := db.Raw("PRAGMA journal_mode=WAL").Scan(&mode)
|
||||
if res.Error != nil {
|
||||
slog.Error("Setting journal_mode=WAL failed!", "mig", migID)
|
||||
return res.Error
|
||||
}
|
||||
// Setting journal_mode might not return an error if it fails,
|
||||
// it always returns the current journal_mode of the db, which
|
||||
// will be WAL if it succeeds OR the "old" journal_mode if it
|
||||
// wasn't changed.
|
||||
// If the mode returned isn't WAL, then something has failed, so
|
||||
// we'll error to stop here and prevent the migration record from
|
||||
// being created, allowing the user to try again.
|
||||
// Note: I was able to test this code by opening the db like this
|
||||
// `sqlite.Open("file:data/watcharr.db?immutable=true")` and
|
||||
// commenting out other code so we get right to this migration
|
||||
// without failing at AutoMigration, etc.
|
||||
slog.Info("journal_mode response.", "mode", mode)
|
||||
if strings.ToLower(mode) != "wal" {
|
||||
slog.Error("Setting journal_mode=WAL failed silently!")
|
||||
return errors.New("Database is not in WAL mode after setting journal_mode=WAL")
|
||||
}
|
||||
slog.Info("WAL journal_mode migration succeeded.", "mig", migID)
|
||||
|
||||
slog.Info("Migration complete.", "mig", migID)
|
||||
return nil
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -7,7 +7,8 @@ import (
|
||||
)
|
||||
|
||||
type (
|
||||
ActivityAddRequest struct {
|
||||
// Internal struct accepted by AddActivity function.
|
||||
ActivityAddProps struct {
|
||||
WatchedID uint `json:"watchedId" binding:"required"`
|
||||
Type entity.ActivityType `json:"type" binding:"required"`
|
||||
Data string `json:"data" binding:"required"`
|
||||
@@ -19,6 +20,22 @@ type (
|
||||
}
|
||||
|
||||
ActivityAddProvider interface {
|
||||
AddActivity(userId uint, ar ActivityAddRequest) (entity.Activity, error)
|
||||
AddActivity(
|
||||
userId uint,
|
||||
ar ActivityAddProps,
|
||||
countAsPlay bool,
|
||||
) (entity.Activity, error)
|
||||
}
|
||||
)
|
||||
|
||||
// Looks through Activity for Watched entry and calculates the amount
|
||||
// that count as plays.
|
||||
func getPlaysFromActivity(a []entity.Activity) int {
|
||||
plays := 0
|
||||
for i := range a {
|
||||
if a[i].CountAsPlay {
|
||||
plays++
|
||||
}
|
||||
}
|
||||
return plays
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ type DiscoverRequestMeta struct {
|
||||
}
|
||||
|
||||
type DiscoverResponse struct {
|
||||
util.PaginationResponse[Media]
|
||||
util.PaginationResponse[Media, util.None]
|
||||
}
|
||||
|
||||
var ValidDiscoverFilter validator.Func = func(fl validator.FieldLevel) bool {
|
||||
|
||||
@@ -1,11 +1,35 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/sbondCo/Watcharr/database/entity"
|
||||
"github.com/sbondCo/Watcharr/util"
|
||||
)
|
||||
|
||||
type ImportContentType string
|
||||
|
||||
const (
|
||||
ImportContentTypeMovie ImportContentType = "movie"
|
||||
ImportContentTypeShow ImportContentType = "tv"
|
||||
ImportContentTypeShowEpisode ImportContentType = "tv_episode"
|
||||
ImportContentTypeGame ImportContentType = "game"
|
||||
)
|
||||
|
||||
func ImportContentTypeToSearchType(t ImportContentType) SearchType {
|
||||
switch t {
|
||||
case ImportContentTypeMovie:
|
||||
return SearchTypeMovie
|
||||
case ImportContentTypeShow:
|
||||
return SearchTypeShow
|
||||
case ImportContentTypeGame:
|
||||
return SearchTypeGame
|
||||
}
|
||||
// Empty string should be caught as an error.
|
||||
return ""
|
||||
}
|
||||
|
||||
type ImportResponseType string
|
||||
|
||||
var (
|
||||
@@ -22,10 +46,13 @@ var (
|
||||
)
|
||||
|
||||
type ImportRequest struct {
|
||||
TmdbID int `json:"tmdbId"`
|
||||
ImdbID string `json:"imdbId"`
|
||||
IgdbID int `json:"igdbId"`
|
||||
|
||||
Name string `json:"name"`
|
||||
Year int `json:"year"`
|
||||
TmdbID int `json:"tmdbId"`
|
||||
Type entity.ContentType `json:"type"`
|
||||
Type ImportContentType `json:"type"`
|
||||
Rating float64 `json:"rating" binding:"max=10"`
|
||||
RatingCustomDate *time.Time `json:"ratingCustomDate"`
|
||||
Status entity.WatchedStatus `json:"status"`
|
||||
@@ -35,7 +62,26 @@ type ImportRequest struct {
|
||||
WatchedEpisodes []entity.WatchedEpisode `json:"watchedEpisodes"`
|
||||
WatchedSeason []entity.WatchedSeason `json:"watchedSeasons"`
|
||||
Tags []TagAddRequest `json:"tags"`
|
||||
ImdbID string `json:"imdbId"`
|
||||
}
|
||||
|
||||
// Internal struct given to the SuccessfulImport function.
|
||||
type SuccessfulImportProps struct {
|
||||
TmdbID int
|
||||
IgdbID int
|
||||
ContentType util.SupportedMedia
|
||||
}
|
||||
|
||||
func NewSuccessfulImportPropsFromMedia(m *Media) (SuccessfulImportProps, error) {
|
||||
p := SuccessfulImportProps{ContentType: m.GetMediaType()}
|
||||
switch p.ContentType {
|
||||
case util.SupportedMediaMovie, util.SupportedMediaShow:
|
||||
p.TmdbID = m.IDs.TMDB
|
||||
case util.SupportedMediaGame:
|
||||
p.IgdbID = m.IDs.IGDB
|
||||
default:
|
||||
return p, errors.New("unsupported content type on media")
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
type ImportResponse struct {
|
||||
|
||||
@@ -63,6 +63,9 @@ type Media struct {
|
||||
// A link to the database we are using that lists all providers with max details.
|
||||
// (especially for TMDB since it's data from JustWatch isn't available to us).
|
||||
ProvidersFullListLink string `json:"providersFullListLink,omitempty"`
|
||||
// Status of the media (released, ended, etc).
|
||||
// Depending on media type, this will contain different values.
|
||||
Status string `json:"status,omitempty"`
|
||||
|
||||
//
|
||||
// Properties only for movies/tv.
|
||||
@@ -78,6 +81,9 @@ type Media struct {
|
||||
// details for the server to fetch fully/verify, i.e fetched full details from
|
||||
// tmdb again to verify if show is anime itself, etc).
|
||||
IsShowAnime bool `json:"isShowAnime,omitempty"`
|
||||
// Last release date.
|
||||
// Currently used for tv shows so frontend can display its end date.
|
||||
ReleaseDateLast time.Time `json:"releaseDateLast,omitzero"`
|
||||
|
||||
//
|
||||
// Properties only for Games
|
||||
@@ -98,6 +104,7 @@ func (t Media) GetId() int {
|
||||
return -99
|
||||
}
|
||||
|
||||
// If this changes, verify all use cases still make sense!
|
||||
func (t Media) GetMediaType() util.SupportedMedia {
|
||||
switch t.Type {
|
||||
case MediaTypeTMDBMovie:
|
||||
|
||||
@@ -26,10 +26,18 @@ type SearchRequest struct {
|
||||
Type SearchType `form:"type" binding:"validsearchtype"`
|
||||
// The search term.
|
||||
Query string `form:"query"`
|
||||
// Prefer a search of our watched list first and return that if any results.
|
||||
PreferMyList bool `form:"preferMyList"`
|
||||
}
|
||||
|
||||
type SearchResponse struct {
|
||||
util.PaginationResponse[Media]
|
||||
util.PaginationResponse[Media, SearchResponseMeta]
|
||||
}
|
||||
|
||||
// Search response metadata
|
||||
type SearchResponseMeta struct {
|
||||
// When true, indicates that results were found from our list.
|
||||
FromMyList bool `json:"fromMyList,omitempty"`
|
||||
}
|
||||
|
||||
var ValidSearchType validator.Func = func(fl validator.FieldLevel) bool {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/sbondCo/Watcharr/database/entity"
|
||||
@@ -8,6 +9,13 @@ import (
|
||||
"github.com/sbondCo/Watcharr/util"
|
||||
)
|
||||
|
||||
var (
|
||||
// Watched entry already exists.
|
||||
ErrWatchedExists = errors.New("watched entry exists")
|
||||
// Watched entry exists as a soft deleted record (..and restore wasn't attempted by choice).
|
||||
ErrWatchedExistsSoftDeleted = errors.New("watched entry exists soft deleted")
|
||||
)
|
||||
|
||||
type WatchedSort string
|
||||
|
||||
const (
|
||||
@@ -41,6 +49,21 @@ type WatchedGetPageRequest struct {
|
||||
type WatchedGetPageExtraProps struct {
|
||||
// Only get these watched ids.
|
||||
WatchedIds []int
|
||||
// Only get watched items where content matches this query.
|
||||
Query string
|
||||
}
|
||||
|
||||
type WatchedAddExtraProps struct {
|
||||
// The type of activity this is (will be added to db as this type).
|
||||
ActivityType entity.ActivityType
|
||||
// When watched entry to db, if a unique constraint is hit, should
|
||||
// we skip the restoration logic (bring back soft deleted record)?
|
||||
// - Syncing logic may use this field as it might not make sense to restore
|
||||
// a record when doing a task like a regular sync, otherwise the user could
|
||||
// soft delte a record and then have it come back when they next sync.
|
||||
// - Importers however probably shouldn't use this flag as true because
|
||||
// importing will always be a manual decision.
|
||||
DontRestore bool
|
||||
}
|
||||
|
||||
type WatchedDto struct {
|
||||
@@ -56,6 +79,9 @@ type WatchedDto struct {
|
||||
// Properties that may not be included in all watched dtos
|
||||
// (depending on where we are making the dto for)
|
||||
|
||||
// Thoughts aren't always included (not needed on watched list pages
|
||||
// & on public pages because they could be private).
|
||||
Thoughts string `json:"thoughts,omitempty"`
|
||||
// Watching Season extra detail for list.
|
||||
WatchingSeason string `json:"watchingSeason,omitempty"`
|
||||
Activity []entity.Activity `json:"activity,omitempty"`
|
||||
@@ -63,6 +89,8 @@ type WatchedDto struct {
|
||||
WatchedEpisodes []entity.WatchedEpisode `json:"watchedEpisodes,omitempty"`
|
||||
Tags []entity.Tag `json:"tags,omitempty"`
|
||||
LastViewedSeason *int `json:"lastViewedSeason,omitempty"`
|
||||
// Amount of plays this media has, calculated from activity.
|
||||
Plays int `json:"plays,omitempty"`
|
||||
}
|
||||
|
||||
// New dto with base properties that we have for all WatchedDtos.
|
||||
@@ -105,11 +133,13 @@ func NewWatchedDtoForPublicLists(w *entity.Watched) WatchedDto {
|
||||
func NewWatchedDtoForContentPage(w *entity.Watched) WatchedDto {
|
||||
dto := NewWatchedDtoWithBaseProps(w)
|
||||
|
||||
dto.Thoughts = w.Thoughts
|
||||
dto.Activity = w.Activity
|
||||
dto.WatchedSeasons = w.WatchedSeasons
|
||||
dto.WatchedEpisodes = w.WatchedEpisodes
|
||||
dto.Tags = w.Tags
|
||||
dto.LastViewedSeason = w.LastViewedSeason
|
||||
dto.Plays = getPlaysFromActivity(w.Activity)
|
||||
|
||||
return dto
|
||||
}
|
||||
@@ -117,6 +147,7 @@ func NewWatchedDtoForContentPage(w *entity.Watched) WatchedDto {
|
||||
// Get our watched page response.
|
||||
type WatchedGetPageResponse []Media
|
||||
|
||||
// Used for GetWatchedPage (and GetWatchedPage for our search).
|
||||
func NewWatchedGetPageResponse(w []entity.Watched) WatchedGetPageResponse {
|
||||
r := WatchedGetPageResponse{}
|
||||
for i := range w {
|
||||
@@ -164,11 +195,35 @@ type WatchedAddRequest struct {
|
||||
|
||||
// Update watched entry request
|
||||
type WatchedUpdateRequest struct {
|
||||
Status entity.WatchedStatus `json:"status" binding:"required_without_all=Rating Thoughts RemoveThoughts Pinned"`
|
||||
Rating float64 `json:"rating" binding:"max=10,required_without_all=Status Thoughts RemoveThoughts Pinned"`
|
||||
Thoughts string `json:"thoughts" binding:"required_without_all=Status Rating RemoveThoughts Pinned"`
|
||||
Status entity.WatchedStatus `json:"status"`
|
||||
Rating float64 `json:"rating"`
|
||||
Thoughts string `json:"thoughts" `
|
||||
RemoveThoughts bool `json:"removeThoughts"`
|
||||
Pinned *bool `json:"pinned" binding:"required_without_all=Status Rating Thoughts RemoveThoughts"`
|
||||
Pinned *bool `json:"pinned" `
|
||||
// Allow the added activity count as play?
|
||||
// If the activity was going to count, this can stop it.
|
||||
LetCountAsPlay *bool `json:"letCountAsPlay"`
|
||||
}
|
||||
|
||||
// If the struct is valid for the Update Request.
|
||||
// - has atleast one property set.
|
||||
// - If rating is set, can't be out of bounds.
|
||||
func (w WatchedUpdateRequest) Valid() error {
|
||||
if w.Status == "" &&
|
||||
w.Rating == 0 &&
|
||||
(w.Thoughts == "" && !w.RemoveThoughts) &&
|
||||
w.Pinned == nil &&
|
||||
w.LetCountAsPlay == nil {
|
||||
// No properties are set, so this struct is not valid.
|
||||
return errors.New("no properties provided")
|
||||
}
|
||||
if w.Status != "" && !w.Status.IsValid() {
|
||||
return errors.New("status is not set to a supported status")
|
||||
}
|
||||
if w.Rating < 0 || w.Rating > 10 {
|
||||
return errors.New("rating can only be a value from 0-10")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Update response.
|
||||
|
||||
@@ -19,31 +19,61 @@ func NewService(db *gorm.DB) *Service {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) GetActivity(userId uint, watchedId uint) ([]entity.Activity, error) {
|
||||
func (s *Service) GetActivity(
|
||||
userId uint,
|
||||
watchedId uint,
|
||||
) ([]entity.Activity, error) {
|
||||
activity := new([]entity.Activity)
|
||||
res := s.db.Model(&entity.Activity{}).Where("user_id = ? AND watched_id = ?", userId, watchedId).Find(&activity)
|
||||
res := s.db.Model(&entity.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())
|
||||
slog.Error("Failed getting activity from database",
|
||||
"error", res.Error.Error())
|
||||
return []entity.Activity{}, errors.New("failed getting activity")
|
||||
}
|
||||
return *activity, nil
|
||||
}
|
||||
|
||||
func (s *Service) AddActivity(userId uint, ar domain.ActivityAddRequest) (entity.Activity, error) {
|
||||
// NOTE: Currently this function doesn't verify if `userId` owns the referenced
|
||||
// watched item at `ar.WatchedID`. If we ever need this function to work from an
|
||||
// "AddActivity" endpoint on the API, we should create another func that has
|
||||
// that validation, since this func is only for internal operations!
|
||||
// AddActivity: Only for internal use.
|
||||
func (s *Service) AddActivity(
|
||||
userId uint,
|
||||
ar domain.ActivityAddProps,
|
||||
// If this activity counts as a play.
|
||||
countAsPlay bool,
|
||||
) (entity.Activity, error) {
|
||||
if ar.WatchedID == 0 {
|
||||
return entity.Activity{}, errors.New("watchedId must be set to add an activity")
|
||||
return entity.Activity{},
|
||||
errors.New("watchedId must be set to add an activity")
|
||||
}
|
||||
activity := entity.Activity{
|
||||
UserID: userId,
|
||||
WatchedID: ar.WatchedID,
|
||||
Type: ar.Type,
|
||||
Data: ar.Data,
|
||||
CustomDate: ar.CustomDate,
|
||||
CountAsPlay: countAsPlay,
|
||||
}
|
||||
activity := entity.Activity{UserID: userId, WatchedID: ar.WatchedID, Type: ar.Type, Data: ar.Data, CustomDate: ar.CustomDate}
|
||||
res := s.db.Create(&activity)
|
||||
if res.Error != nil {
|
||||
slog.Error("Error adding activity to database", "error", res.Error.Error())
|
||||
return entity.Activity{}, errors.New("failed adding new activity to database")
|
||||
slog.Error("Error adding activity to database",
|
||||
"error", res.Error.Error())
|
||||
return entity.Activity{},
|
||||
errors.New("failed adding new activity to database")
|
||||
}
|
||||
slog.Debug("Adding activity", "added_activity", activity)
|
||||
return activity, nil
|
||||
}
|
||||
|
||||
func (s *Service) UpdateActivity(userId uint, id uint, activityUpdateRequest domain.ActivityUpdateRequest) error {
|
||||
func (s *Service) UpdateActivity(
|
||||
userId uint,
|
||||
id uint,
|
||||
activityUpdateRequest domain.ActivityUpdateRequest,
|
||||
) error {
|
||||
if id == 0 {
|
||||
return errors.New("id must be set to update an activity")
|
||||
}
|
||||
@@ -55,11 +85,12 @@ func (s *Service) UpdateActivity(userId uint, id uint, activityUpdateRequest dom
|
||||
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())
|
||||
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.")
|
||||
slog.Error("No activities were updated.")
|
||||
return errors.New("failed updating activity in database")
|
||||
}
|
||||
slog.Debug("Updating activity", "updated_activity", id)
|
||||
@@ -72,11 +103,12 @@ func (s *Service) DeleteActivity(userId uint, id uint) error {
|
||||
}
|
||||
res := s.db.Where("user_id = ?", userId).Delete(&entity.Activity{}, id)
|
||||
if res.Error != nil {
|
||||
slog.Error("Error deleting activity in database", "error", res.Error.Error())
|
||||
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.")
|
||||
slog.Error("No activities were deleted.")
|
||||
return errors.New("failed deleting activity from database")
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -27,7 +27,6 @@ func (r *Router) AddRoutes() {
|
||||
activity := r.br.Router.Group("/activity").Use(authmiddleware.AuthRequired(nil, r.br.Cfg))
|
||||
|
||||
activity.GET(":watchedId", r.GetActivity)
|
||||
activity.POST("", r.AddActivity)
|
||||
activity.PUT(":id", r.UpdateActivity)
|
||||
activity.DELETE(":id", r.DeleteActivity)
|
||||
}
|
||||
@@ -47,22 +46,6 @@ func (r *Router) GetActivity(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, activity)
|
||||
}
|
||||
|
||||
func (r *Router) AddActivity(c *gin.Context) {
|
||||
userId := c.MustGet("userId").(uint)
|
||||
var ar domain.ActivityAddRequest
|
||||
err := c.ShouldBindJSON(&ar)
|
||||
if err == nil {
|
||||
response, err := r.service.AddActivity(userId, ar)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusForbidden, router.ErrorResponse{Error: err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, response)
|
||||
return
|
||||
}
|
||||
c.AbortWithStatusJSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
|
||||
}
|
||||
|
||||
func (r *Router) UpdateActivity(c *gin.Context) {
|
||||
userId := c.MustGet("userId").(uint)
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 32)
|
||||
|
||||
@@ -14,6 +14,10 @@ import (
|
||||
|
||||
// Auth middleware
|
||||
// If db is passed, extra user info from the database will be fetched.
|
||||
//
|
||||
// **NOTE:** Instead of providing the `db` parameter, it is probably better to
|
||||
// fetch what you need in the handler directly! We might follow that pattern
|
||||
// from now on and potentially remove `db` from this func in the future.
|
||||
func AuthRequired(db *gorm.DB, cfg *config.ServerConfig) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
slog.Debug("AuthRequired middleware hit")
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package content
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -13,7 +12,6 @@ import (
|
||||
"time"
|
||||
|
||||
gocache "github.com/robfig/go-cache"
|
||||
"github.com/sbondCo/Watcharr/cache"
|
||||
"github.com/sbondCo/Watcharr/config"
|
||||
"github.com/sbondCo/Watcharr/database/entity"
|
||||
"github.com/sbondCo/Watcharr/media/tmdb"
|
||||
@@ -160,8 +158,11 @@ func (s *Service) saveContent(c *entity.Content, onlyUpdate bool) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) cacheContentTv(content tmdb.TMDBShowDetails, onlyUpdate bool) (entity.Content, error) {
|
||||
slog.Debug("cacheContentTv", "content", content)
|
||||
func (s *Service) CacheContentShow(
|
||||
content tmdb.ShowDetails,
|
||||
onlyUpdate bool,
|
||||
) (entity.Content, error) {
|
||||
slog.Debug("CacheContentShow", "content", content)
|
||||
var (
|
||||
releaseDate time.Time
|
||||
runtime uint32
|
||||
@@ -193,14 +194,17 @@ func (s *Service) cacheContentTv(content tmdb.TMDBShowDetails, onlyUpdate bool)
|
||||
|
||||
err = s.saveContent(&c, onlyUpdate)
|
||||
if err != nil {
|
||||
slog.Error("cacheContentTv: Failed to save content!", "error", err)
|
||||
slog.Error("CacheContentShow: Failed to save content!", "error", err)
|
||||
return entity.Content{}, errors.New("failed to save content")
|
||||
}
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (s *Service) cacheContentMovie(content tmdb.TMDBMovieDetails, onlyUpdate bool) (entity.Content, error) {
|
||||
func (s *Service) CacheContentMovie(
|
||||
content tmdb.MovieDetails,
|
||||
onlyUpdate bool,
|
||||
) (entity.Content, error) {
|
||||
var (
|
||||
releaseDate time.Time
|
||||
)
|
||||
@@ -238,7 +242,10 @@ func (s *Service) cacheContentMovie(content tmdb.TMDBMovieDetails, onlyUpdate bo
|
||||
}
|
||||
|
||||
// Get content from our db cache, or cache it if it doesn't exist.
|
||||
func (s *Service) GetOrCacheContent(contentType entity.ContentType, tmdbId int) (entity.Content, error) {
|
||||
func (s *Service) GetOrCacheContent(
|
||||
contentType entity.ContentType,
|
||||
tmdbId int,
|
||||
) (entity.Content, error) {
|
||||
var content entity.Content
|
||||
// Look in db for content.
|
||||
s.db.Where("type = ? AND tmdb_id = ?", contentType, tmdbId).Find(&content)
|
||||
@@ -246,407 +253,51 @@ func (s *Service) GetOrCacheContent(contentType entity.ContentType, tmdbId int)
|
||||
if content == (entity.Content{}) {
|
||||
slog.Debug("Content not in db, fetching...", "type", contentType, "tmdbId", tmdbId)
|
||||
|
||||
resp, err := s.tmdb.APIRequest("/"+string(contentType)+"/"+strconv.Itoa(tmdbId), map[string]string{})
|
||||
if err != nil {
|
||||
slog.Error("GetOrCacheContent: content tmdb api request failed", "error", err)
|
||||
return entity.Content{}, errors.New("failed to find requested media")
|
||||
tmdbId := strconv.Itoa(tmdbId)
|
||||
|
||||
switch contentType {
|
||||
case entity.MOVIE:
|
||||
resp, err := s.tmdb.MovieDetails(tmdb.MovieDetailsOptions{
|
||||
ID: tmdbId,
|
||||
DontRunDBCache: true,
|
||||
})
|
||||
if err != nil {
|
||||
slog.Error("GetOrCacheContent: MovieDetails failed.",
|
||||
"content_id", tmdbId,
|
||||
"err", err)
|
||||
return entity.Content{}, errors.New("details request failed")
|
||||
}
|
||||
content, err = s.CacheContentMovie(resp, false)
|
||||
if err != nil {
|
||||
slog.Error("GetOrCacheContent: Caching movie failed",
|
||||
"content_id", tmdbId,
|
||||
"err", err)
|
||||
return entity.Content{}, errors.New("caching failed")
|
||||
}
|
||||
case entity.SHOW:
|
||||
resp, err := s.tmdb.ShowDetails(tmdb.ShowDetailsOptions{
|
||||
ID: tmdbId,
|
||||
DontRunDBCache: true,
|
||||
})
|
||||
if err != nil {
|
||||
slog.Error("GetOrCacheContent: ShowDetails failed.",
|
||||
"content_id", tmdbId,
|
||||
"err", err)
|
||||
}
|
||||
content, err = s.CacheContentShow(resp, false)
|
||||
if err != nil {
|
||||
slog.Error("GetOrCacheContent: Caching show failed",
|
||||
"content_id", tmdbId,
|
||||
"err", err)
|
||||
return entity.Content{}, errors.New("caching failed")
|
||||
}
|
||||
default:
|
||||
slog.Error("GetOrCacheContent: Unsupported contentType",
|
||||
"type", contentType,
|
||||
"content_id", tmdbId)
|
||||
return entity.Content{}, errors.New("unsupported contentType")
|
||||
}
|
||||
|
||||
if contentType == "movie" {
|
||||
c := new(tmdb.TMDBMovieDetails)
|
||||
err := json.Unmarshal([]byte(resp), &c)
|
||||
if err != nil {
|
||||
slog.Error("Failed to unmarshal movie details", "error", err)
|
||||
return entity.Content{}, errors.New("failed to process movie details response")
|
||||
}
|
||||
content, err = s.cacheContentMovie(*c, false)
|
||||
if err != nil {
|
||||
slog.Error("GetOrCacheContent: failed to cache movie content", "type", contentType, "content_id", tmdbId, "err", err)
|
||||
return entity.Content{}, errors.New("failed to cache content")
|
||||
}
|
||||
} else {
|
||||
c := new(tmdb.TMDBShowDetails)
|
||||
err := json.Unmarshal(resp, &c)
|
||||
if err != nil {
|
||||
slog.Error("Failed to unmarshal tv details", "error", err)
|
||||
return entity.Content{}, errors.New("failed to process tv details response")
|
||||
}
|
||||
content, err = s.cacheContentTv(*c, false)
|
||||
if err != nil {
|
||||
slog.Error("GetOrCacheContent: failed to cache tv content", "type", contentType, "content_id", tmdbId, "err", err)
|
||||
return entity.Content{}, errors.New("failed to cache content")
|
||||
}
|
||||
}
|
||||
}
|
||||
return content, nil
|
||||
}
|
||||
|
||||
// TMDB Multi Search.
|
||||
func (s *Service) SearchContent(query string, pageNum int) (tmdb.TMDBSearchMultiResponse, error) {
|
||||
resp := new(tmdb.TMDBSearchMultiResponse)
|
||||
if pageNum == 0 {
|
||||
pageNum = 1
|
||||
}
|
||||
cacheKey := cache.CreateCacheKey("SearchContent", query, pageNum)
|
||||
if cache.GetCache(ContentStore, cacheKey, &resp) {
|
||||
slog.Debug("SearchContent: Returning cache.")
|
||||
return *resp, nil
|
||||
}
|
||||
err := s.tmdb.Request("/search/multi", map[string]string{"query": query, "page": strconv.Itoa(pageNum)}, &resp)
|
||||
if err != nil {
|
||||
slog.Error("Failed to complete multi search request!", "error", err.Error())
|
||||
return tmdb.TMDBSearchMultiResponse{}, errors.New("failed to complete multi search request")
|
||||
}
|
||||
ContentStore.Set(cacheKey, resp, time.Hour*24)
|
||||
return *resp, nil
|
||||
}
|
||||
|
||||
func (s *Service) SearchMovies(query string, pageNum int) (tmdb.TMDBSearchMoviesResponse, error) {
|
||||
resp := new(tmdb.TMDBSearchMoviesResponse)
|
||||
if pageNum == 0 {
|
||||
pageNum = 1
|
||||
}
|
||||
cacheKey := cache.CreateCacheKey("SearchMovies", query, pageNum)
|
||||
if cache.GetCache(ContentStore, cacheKey, &resp) {
|
||||
slog.Debug("SearchMovies: Returning cache.")
|
||||
return *resp, nil
|
||||
}
|
||||
err := s.tmdb.Request("/search/movie", map[string]string{"query": query, "page": strconv.Itoa(pageNum)}, &resp)
|
||||
if err != nil {
|
||||
slog.Error("Failed to complete movie search request!", "error", err.Error())
|
||||
return tmdb.TMDBSearchMoviesResponse{}, errors.New("failed to complete movie search request")
|
||||
}
|
||||
for i := range resp.Results {
|
||||
resp.Results[i].MediaType = "movie"
|
||||
}
|
||||
ContentStore.Set(cacheKey, resp, time.Hour*24)
|
||||
return *resp, nil
|
||||
}
|
||||
|
||||
func (s *Service) SearchTv(query string, pageNum int) (tmdb.TMDBSearchShowsResponse, error) {
|
||||
resp := new(tmdb.TMDBSearchShowsResponse)
|
||||
if pageNum == 0 {
|
||||
pageNum = 1
|
||||
}
|
||||
cacheKey := cache.CreateCacheKey("SearchTv", query, pageNum)
|
||||
if cache.GetCache(ContentStore, cacheKey, &resp) {
|
||||
slog.Debug("SearchTv: Returning cache.")
|
||||
return *resp, nil
|
||||
}
|
||||
err := s.tmdb.Request("/search/tv", map[string]string{"query": query, "page": strconv.Itoa(pageNum)}, &resp)
|
||||
if err != nil {
|
||||
slog.Error("Failed to complete tv search request!", "error", err.Error())
|
||||
return tmdb.TMDBSearchShowsResponse{}, errors.New("failed to complete tv search request")
|
||||
}
|
||||
for i := range resp.Results {
|
||||
resp.Results[i].MediaType = "tv"
|
||||
}
|
||||
ContentStore.Set(cacheKey, resp, time.Hour*24)
|
||||
return *resp, nil
|
||||
}
|
||||
|
||||
func (s *Service) SearchPeople(query string, pageNum int) (tmdb.TMDBSearchPeopleResponse, error) {
|
||||
resp := new(tmdb.TMDBSearchPeopleResponse)
|
||||
if pageNum == 0 {
|
||||
pageNum = 1
|
||||
}
|
||||
cacheKey := cache.CreateCacheKey("SearchPeople", query, pageNum)
|
||||
if cache.GetCache(ContentStore, cacheKey, &resp) {
|
||||
slog.Debug("SearchPeople: Returning cache.")
|
||||
return *resp, nil
|
||||
}
|
||||
err := s.tmdb.Request("/search/person", map[string]string{
|
||||
"query": query,
|
||||
"page": strconv.Itoa(pageNum),
|
||||
}, &resp)
|
||||
if err != nil {
|
||||
slog.Error("Failed to complete people search request!", "error", err.Error())
|
||||
return tmdb.TMDBSearchPeopleResponse{}, errors.New("failed to complete people search request")
|
||||
}
|
||||
for i := range resp.Results {
|
||||
resp.Results[i].MediaType = "person"
|
||||
}
|
||||
ContentStore.Set(cacheKey, resp, time.Hour*24)
|
||||
return *resp, nil
|
||||
}
|
||||
|
||||
// Search for content by an external id (imdb, etc).
|
||||
// Defaults to imdb if no source if provided (probably most common).
|
||||
func (s *Service) SearchByExternalId(id string, source string) (tmdb.TMDBSearchMultiResponse, error) {
|
||||
resp := new(tmdb.TMDBFindByExternalIdResponse)
|
||||
if source == "" {
|
||||
source = "imdb"
|
||||
}
|
||||
cacheKey := cache.CreateCacheKey("SearchByExternalId", id, source)
|
||||
if cache.GetCache(ContentStore, cacheKey, &resp) {
|
||||
slog.Debug("SearchByExternalId: Got cache.")
|
||||
} else {
|
||||
// If not found in cache, request data from tmdb.
|
||||
err := s.tmdb.Request("/find/"+id, map[string]string{"external_source": source + "_id"}, &resp)
|
||||
if err != nil {
|
||||
slog.Error("Failed to complete find/external_id request!", "error", err.Error())
|
||||
return tmdb.TMDBSearchMultiResponse{}, errors.New("failed to complete find/external_id request")
|
||||
}
|
||||
ContentStore.Set(cacheKey, resp, time.Hour*24)
|
||||
}
|
||||
comb := []tmdb.TMDBSearchMultiResult{}
|
||||
comb = append(comb, resp.MovieResults...)
|
||||
comb = append(comb, resp.TvResults...)
|
||||
comb = append(comb, resp.PersonResults...)
|
||||
comb = append(comb, resp.TvSeasonResults...)
|
||||
comb = append(comb, resp.TvEpisodeResults...)
|
||||
return tmdb.TMDBSearchMultiResponse{TMDBSearchResponse: tmdb.TMDBSearchResponse[tmdb.TMDBSearchMultiResult]{
|
||||
Results: comb,
|
||||
TMDBPageFields: tmdb.TMDBPageFields{
|
||||
TotalResults: len(comb),
|
||||
// Just providing these so we don't break frontend pagination logic.
|
||||
TotalPages: 1,
|
||||
Page: 1,
|
||||
},
|
||||
}}, nil
|
||||
}
|
||||
|
||||
func (s *Service) MovieDetails(
|
||||
id string,
|
||||
country string,
|
||||
rParams map[string]string,
|
||||
) (tmdb.TMDBMovieDetails, error) {
|
||||
resp := new(tmdb.TMDBMovieDetails)
|
||||
cacheKey := cache.CreateCacheKey("MovieDetails", id, country, rParams)
|
||||
if cache.GetCache(ContentStore, cacheKey, &resp) {
|
||||
slog.Debug("MovieDetails: Returning cache.")
|
||||
return *resp, nil
|
||||
}
|
||||
err := s.tmdb.Request("/movie/"+id, rParams, &resp)
|
||||
if err != nil {
|
||||
slog.Error("Failed to complete movie details request!",
|
||||
"error", err.Error())
|
||||
return tmdb.TMDBMovieDetails{},
|
||||
errors.New("failed to complete movie details request")
|
||||
}
|
||||
resp.WatchProvidersTransformed = transformProviders(&resp.WatchProviders, country)
|
||||
resp.WatchProviders = nil // We don't want this to linger around (in cache) since we have the transformed version now..
|
||||
go s.cacheContentMovie(*resp, true)
|
||||
ContentStore.Set(cacheKey, resp, time.Hour*24)
|
||||
return *resp, nil
|
||||
}
|
||||
|
||||
func (s *Service) MovieCredits(id string) (tmdb.TMDBContentCredits, error) {
|
||||
resp := new(tmdb.TMDBContentCredits)
|
||||
err := s.tmdb.Request("/movie/"+id+"/credits", map[string]string{}, &resp)
|
||||
if err != nil {
|
||||
slog.Error("Failed to complete movie cast request!", "error", err.Error())
|
||||
return tmdb.TMDBContentCredits{}, errors.New("failed to complete movie cast request")
|
||||
}
|
||||
return *resp, nil
|
||||
}
|
||||
|
||||
func (s *Service) TvDetails(
|
||||
id string,
|
||||
country string,
|
||||
rParams map[string]string,
|
||||
) (tmdb.TMDBShowDetails, error) {
|
||||
cacheKey := cache.CreateCacheKey("TvDetails", id, country, rParams)
|
||||
resp := new(tmdb.TMDBShowDetails)
|
||||
if cache.GetCache(ContentStore, cacheKey, &resp) {
|
||||
slog.Debug("TvDetails: Returning cache.")
|
||||
return *resp, nil
|
||||
}
|
||||
err := s.tmdb.Request("/tv/"+id, rParams, &resp)
|
||||
if err != nil {
|
||||
slog.Error("Failed to complete tv details request!", "error", err.Error())
|
||||
return tmdb.TMDBShowDetails{}, errors.New("failed to complete tv details request")
|
||||
}
|
||||
resp.WatchProvidersTransformed = transformProviders(&resp.WatchProviders, country)
|
||||
resp.WatchProviders = nil // We don't want this to linger around (in cache) since we have the transformed version now..
|
||||
go s.cacheContentTv(*resp, true)
|
||||
ContentStore.Set(cacheKey, resp, time.Hour*24)
|
||||
return *resp, nil
|
||||
}
|
||||
|
||||
func (s *Service) TvCredits(id string) (tmdb.TMDBContentCredits, error) {
|
||||
resp := new(tmdb.TMDBContentCredits)
|
||||
err := s.tmdb.Request("/tv/"+id+"/credits", map[string]string{}, &resp)
|
||||
if err != nil {
|
||||
slog.Error("Failed to complete tv cast request!", "error", err.Error())
|
||||
return tmdb.TMDBContentCredits{}, errors.New("failed to complete tv cast request")
|
||||
}
|
||||
return *resp, nil
|
||||
}
|
||||
|
||||
// This method is manually cached, so it can be easily used in other places (on the server) with cache benefits
|
||||
func (s *Service) SeasonDetails(tvId string, seasonNumber string) (tmdb.TMDBSeasonDetails, error) {
|
||||
cacheKey := cache.CreateCacheKey("SeasonDetails", tvId, seasonNumber)
|
||||
resp := new(tmdb.TMDBSeasonDetails)
|
||||
if cache.GetCache(ContentStore, cacheKey, &resp) {
|
||||
slog.Debug("SeasonDetails: Returning cache.")
|
||||
return *resp, nil
|
||||
}
|
||||
err := s.tmdb.Request("/tv/"+tvId+"/season/"+seasonNumber, map[string]string{}, &resp)
|
||||
if err != nil {
|
||||
slog.Error("SeasonDetails: Failed to complete season details request!", "error", err.Error())
|
||||
return tmdb.TMDBSeasonDetails{}, errors.New("failed to complete season details request")
|
||||
}
|
||||
ContentStore.Set(cacheKey, resp, time.Hour*24)
|
||||
return *resp, nil
|
||||
}
|
||||
|
||||
func (s *Service) PersonDetails(id string) (tmdb.TMDBPersonDetails, error) {
|
||||
resp := new(tmdb.TMDBPersonDetails)
|
||||
err := s.tmdb.Request("/person/"+id, map[string]string{}, &resp)
|
||||
if err != nil {
|
||||
slog.Error("Failed to complete person details request!", "error", err.Error())
|
||||
return tmdb.TMDBPersonDetails{}, errors.New("failed to complete person details request")
|
||||
}
|
||||
return *resp, nil
|
||||
}
|
||||
|
||||
func (s *Service) PersonCredits(id string) (tmdb.TMDBPersonCombinedCredits, error) {
|
||||
cacheKey := cache.CreateCacheKey("PersonCredits", id)
|
||||
resp := new(tmdb.TMDBPersonCombinedCredits)
|
||||
if cache.GetCache(ContentStore, cacheKey, &resp) {
|
||||
slog.Debug("PersonCredits: Returning cache.")
|
||||
return *resp, nil
|
||||
}
|
||||
err := s.tmdb.Request("/person/"+id+"/combined_credits", map[string]string{}, &resp)
|
||||
if err != nil {
|
||||
slog.Error("Failed to complete person details request!", "error", err.Error())
|
||||
return tmdb.TMDBPersonCombinedCredits{}, errors.New("failed to complete person details request")
|
||||
}
|
||||
ContentStore.Set(cacheKey, resp, time.Hour*24)
|
||||
return *resp, nil
|
||||
}
|
||||
|
||||
func (s *Service) Trending(t tmdb.TrendingType, pageNum int, region string) (tmdb.TMDBTrendingCombined, error) {
|
||||
resp := new(tmdb.TMDBTrendingCombined)
|
||||
if t != tmdb.TrendingTypeAll &&
|
||||
t != tmdb.TrendingTypeMovie &&
|
||||
t != tmdb.TrendingTypeShow &&
|
||||
t != tmdb.TrendingTypePerson {
|
||||
slog.Error("Trending: Invalid type provided", "provided_t", t)
|
||||
return *resp, errors.New("invalid type")
|
||||
}
|
||||
if pageNum <= 0 {
|
||||
pageNum = 1
|
||||
}
|
||||
cacheKey := cache.CreateCacheKey("Trending", string(t), region, pageNum)
|
||||
if cache.GetCache(ContentStore, cacheKey, &resp) {
|
||||
slog.Debug("Trending: Returning cache.")
|
||||
return *resp, nil
|
||||
}
|
||||
err := s.tmdb.Request("/trending/"+string(t)+"/day", map[string]string{
|
||||
"page": strconv.Itoa(pageNum),
|
||||
"region": region,
|
||||
}, &resp)
|
||||
if err != nil {
|
||||
slog.Error("Failed to complete all trending request!", "error", err.Error())
|
||||
return *resp, errors.New("failed to complete all trending request")
|
||||
}
|
||||
ContentStore.Set(cacheKey, resp, time.Hour*24)
|
||||
return *resp, nil
|
||||
}
|
||||
|
||||
func (s *Service) DiscoverMovies(
|
||||
o tmdb.DiscoverOptions,
|
||||
pageNum int,
|
||||
region string,
|
||||
) (tmdb.TMDBDiscoverMovies, error) {
|
||||
resp := new(tmdb.TMDBDiscoverMovies)
|
||||
reqParams := map[string]string{
|
||||
"page": strconv.Itoa(pageNum),
|
||||
"region": region,
|
||||
}
|
||||
s.applyDiscoverOptionsToMap(true, o, reqParams)
|
||||
cacheKey := cache.CreateCacheKey("DiscoverMovies", pageNum, reqParams)
|
||||
if cache.GetCache(ContentStore, cacheKey, &resp) {
|
||||
slog.Debug("DiscoverMovies: Returning cache.")
|
||||
return *resp, nil
|
||||
}
|
||||
err := s.tmdb.Request("/discover/movie", reqParams, &resp)
|
||||
if err != nil {
|
||||
slog.Error("DiscoverMovies: Failed to complete request!", "error", err.Error())
|
||||
return tmdb.TMDBDiscoverMovies{}, errors.New("failed to complete discover movies request")
|
||||
}
|
||||
ContentStore.Set(cacheKey, resp, time.Hour*24)
|
||||
return *resp, nil
|
||||
}
|
||||
|
||||
func (s *Service) DiscoverTv(
|
||||
o tmdb.DiscoverOptions,
|
||||
pageNum int,
|
||||
region string,
|
||||
) (tmdb.TMDBDiscoverShows, error) {
|
||||
resp := new(tmdb.TMDBDiscoverShows)
|
||||
reqParams := map[string]string{
|
||||
"page": strconv.Itoa(pageNum),
|
||||
"region": region,
|
||||
}
|
||||
s.applyDiscoverOptionsToMap(false, o, reqParams)
|
||||
cacheKey := cache.CreateCacheKey("DiscoverTv", pageNum, reqParams)
|
||||
if cache.GetCache(ContentStore, cacheKey, &resp) {
|
||||
slog.Debug("DiscoverTv: Returning cache.")
|
||||
return *resp, nil
|
||||
}
|
||||
err := s.tmdb.Request("/discover/tv", reqParams, &resp)
|
||||
if err != nil {
|
||||
slog.Error("DiscoverTv: Failed to complete request!", "error", err.Error())
|
||||
return tmdb.TMDBDiscoverShows{}, errors.New("failed to complete discover tv request")
|
||||
}
|
||||
ContentStore.Set(cacheKey, resp, time.Hour*24)
|
||||
return *resp, nil
|
||||
}
|
||||
|
||||
func (s *Service) applyDiscoverOptionsToMap(
|
||||
// Some properties are named differently for sorting the same thing as far
|
||||
// as we care, so we need to differenciate to name them properly.
|
||||
forMovie bool,
|
||||
o tmdb.DiscoverOptions,
|
||||
m map[string]string,
|
||||
) {
|
||||
releaseDateMinKey := "release_date.gte"
|
||||
releaseDateMaxKey := "release_date.lte"
|
||||
withReleaseTypeKey := "with_release_type"
|
||||
if !forMovie {
|
||||
// Replace with names for equivalent tv filters
|
||||
releaseDateMinKey = "first_air_date.gte"
|
||||
releaseDateMaxKey = "first_air_date.lte"
|
||||
withReleaseTypeKey = "with_type"
|
||||
}
|
||||
if !o.ReleaseDateMin.IsZero() {
|
||||
m[releaseDateMinKey] = o.ReleaseDateMin.Format("2006-01-02")
|
||||
}
|
||||
if !o.ReleaseDateMax.IsZero() {
|
||||
m[releaseDateMaxKey] = o.ReleaseDateMax.Format("2006-01-02")
|
||||
}
|
||||
if o.WithReleaseType != "" {
|
||||
m[withReleaseTypeKey] = o.WithReleaseType
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) PopularPeople(pageNum int) (tmdb.TMDBPopularPeople, error) {
|
||||
cacheKey := cache.CreateCacheKey("PopularPeople", pageNum)
|
||||
resp := new(tmdb.TMDBPopularPeople)
|
||||
if cache.GetCache(ContentStore, cacheKey, &resp) {
|
||||
slog.Debug("PopularPeople: Returning cache.")
|
||||
return *resp, nil
|
||||
}
|
||||
err := s.tmdb.Request("/person/popular",
|
||||
map[string]string{"page": strconv.Itoa(pageNum)},
|
||||
&resp)
|
||||
if err != nil {
|
||||
slog.Error("PopularPeople: Failed to complete request!", "error", err.Error())
|
||||
return tmdb.TMDBPopularPeople{}, errors.New("failed to complete request")
|
||||
}
|
||||
ContentStore.Set(cacheKey, resp, time.Hour*24)
|
||||
return *resp, nil
|
||||
}
|
||||
|
||||
func (s *Service) Regions() (tmdb.TMDBRegions, error) {
|
||||
resp := new(tmdb.TMDBRegions)
|
||||
err := s.tmdb.Request("/watch/providers/regions", map[string]string{}, &resp)
|
||||
if err != nil {
|
||||
slog.Error("Failed to complete regions request!", "error", err.Error())
|
||||
return tmdb.TMDBRegions{}, errors.New("failed to complete regions request")
|
||||
}
|
||||
return *resp, nil
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"github.com/sbondCo/Watcharr/domain"
|
||||
"github.com/sbondCo/Watcharr/feature/auth/authmiddleware"
|
||||
"github.com/sbondCo/Watcharr/feature/watched/addedtocontent"
|
||||
"github.com/sbondCo/Watcharr/media/tmdb"
|
||||
"github.com/sbondCo/Watcharr/router"
|
||||
"github.com/sbondCo/Watcharr/util"
|
||||
)
|
||||
@@ -23,16 +24,23 @@ type WatchedProvider interface {
|
||||
}
|
||||
|
||||
type Router struct {
|
||||
br *router.BaseRouter
|
||||
cs *Service
|
||||
wp WatchedProvider
|
||||
br *router.BaseRouter
|
||||
cs *Service
|
||||
wp WatchedProvider
|
||||
tmdb *tmdb.TMDB
|
||||
}
|
||||
|
||||
func NewRouter(br *router.BaseRouter, cs *Service, wp WatchedProvider) *Router {
|
||||
func NewRouter(
|
||||
br *router.BaseRouter,
|
||||
cs *Service,
|
||||
wp WatchedProvider,
|
||||
tmdb *tmdb.TMDB,
|
||||
) *Router {
|
||||
return &Router{
|
||||
br: br,
|
||||
cs: cs,
|
||||
wp: wp,
|
||||
br: br,
|
||||
cs: cs,
|
||||
wp: wp,
|
||||
tmdb: tmdb,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,13 +76,13 @@ func (r *Router) GetMovieDetails(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: "an id was not provided"})
|
||||
return
|
||||
}
|
||||
content, err := r.cs.MovieDetails(
|
||||
c.Param("id"),
|
||||
c.MustGet("userCountry").(string),
|
||||
map[string]string{
|
||||
content, err := r.tmdb.MovieDetails(tmdb.MovieDetailsOptions{
|
||||
ID: c.Param("id"),
|
||||
Country: c.MustGet("userCountry").(string),
|
||||
Params: map[string]string{
|
||||
"append_to_response": "videos,watch/providers,similar",
|
||||
},
|
||||
)
|
||||
})
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
|
||||
return
|
||||
@@ -111,7 +119,7 @@ func (r *Router) GetMovieCredits(c *gin.Context) {
|
||||
c.Status(400)
|
||||
return
|
||||
}
|
||||
content, err := r.cs.MovieCredits(c.Param("id"))
|
||||
content, err := r.tmdb.MovieCredits(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
|
||||
return
|
||||
@@ -126,13 +134,13 @@ func (r *Router) GetTvDetails(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
// 1. Get details
|
||||
content, err := r.cs.TvDetails(
|
||||
c.Param("id"),
|
||||
c.MustGet("userCountry").(string),
|
||||
map[string]string{
|
||||
content, err := r.tmdb.ShowDetails(tmdb.ShowDetailsOptions{
|
||||
ID: c.Param("id"),
|
||||
Country: c.MustGet("userCountry").(string),
|
||||
Params: map[string]string{
|
||||
"append_to_response": "videos,watch/providers,similar,external_ids,keywords",
|
||||
},
|
||||
)
|
||||
})
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
|
||||
return
|
||||
@@ -169,7 +177,7 @@ func (r *Router) GetTvCredits(c *gin.Context) {
|
||||
c.Status(400)
|
||||
return
|
||||
}
|
||||
content, err := r.cs.TvCredits(c.Param("id"))
|
||||
content, err := r.tmdb.ShowCredits(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
|
||||
return
|
||||
@@ -184,7 +192,7 @@ func (r *Router) GetSeasonDetails(c *gin.Context) {
|
||||
c.Status(400)
|
||||
return
|
||||
}
|
||||
content, err := r.cs.SeasonDetails(c.Param("id"), c.Param("num"))
|
||||
content, err := r.tmdb.SeasonDetails(c.Param("id"), c.Param("num"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
|
||||
return
|
||||
@@ -221,7 +229,7 @@ func (r *Router) GetPerson(c *gin.Context) {
|
||||
c.Status(400)
|
||||
return
|
||||
}
|
||||
content, err := r.cs.PersonDetails(c.Param("id"))
|
||||
content, err := r.tmdb.PersonDetails(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
|
||||
return
|
||||
@@ -235,7 +243,7 @@ func (r *Router) GetPersonCredits(c *gin.Context) {
|
||||
c.Status(400)
|
||||
return
|
||||
}
|
||||
content, err := r.cs.PersonCredits(c.Param("id"))
|
||||
content, err := r.tmdb.PersonCredits(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
|
||||
return
|
||||
@@ -264,7 +272,7 @@ func (r *Router) GetPersonCredits(c *gin.Context) {
|
||||
}
|
||||
|
||||
func (r *Router) GetRegions(c *gin.Context) {
|
||||
re, err := r.cs.Regions()
|
||||
re, err := r.tmdb.Regions()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
|
||||
return
|
||||
|
||||