Compare commits

...

181 Commits

Author SHA1 Message Date
IRHM fa34f1ead1 v4.2.1 CHANGELOG 2026-08-04 02:01:51 +01:00
IRHM cefed53c7f v4.2.1 CHANGELOG 2026-08-04 02:00:29 +01:00
IRHM 0d8b050615 v4.2.1 2026-08-04 01:36:44 +01:00
IRHM 63988f833f v4.2.1-dev1 2026-08-04 01:12:56 +01:00
IRHM e391d5dc69 (fix) ProvidersList: Duplicate key error. 2026-08-04 00:11:20 +00:00
IRHM cba3d11f64 v4.2.0 CHANGELOG 2026-08-03 09:02:17 +01:00
IRHM 5d95aa4b41 v4.2.0 2026-08-03 08:39:05 +01:00
IRHM 41dff624bb README: Add link to FEATURES document. 2026-08-03 07:40:44 +01:00
IRHM 39a77b4428 v4.2.0-dev2 2026-08-03 07:05:06 +01:00
IRHM 9b74728afb SeasonsListEpisode: Fix info box alignment
Also fixed the episode rating text getting cut off at certain dimensions by enforcing its minimum width at which a double digit rating is still visible (eg 7.1)
2026-08-03 07:04:06 +01:00
IRHM 113ccbbbfd v4.2.0-dev1 2026-08-03 03:30:47 +01:00
IRHM 87033f423d upgrade server dependencies 2026-08-03 02:25:54 +00:00
IRHM 3a52a9a592 Update FEATURES.md 2026-08-03 01:14:02 +00:00
IRHM 9b39617650 search: Add filters help button opening a modal with examples 2026-08-03 01:14:02 +00:00
IRHM dd1503846d igdb: SearchOptions: Add note comment 2026-08-03 01:14:02 +00:00
IRHM 92edb75de9 Games: Support searching with Year or FirstYear filters 2026-08-03 01:14:02 +00:00
IRHM dc2b9a1a63 tmdb: Remove olf *WithWatched structs
These are not used and are a remnant from before the server restructure (it was another solution i was cooking up, but didn't end up going with).
2026-08-03 01:14:02 +00:00
IRHM 7b65c8af0f tmdb: Strip TMDB prefix from all struct names
This prefix is a remnant from when the structs where in the "main" package (from before the server refactor).
2026-08-03 01:14:02 +00:00
IRHM cf3168d59c content: GetOrCacheContent: Use Movie/ShowDetails funcs instead of manually using APIRequest func
Because this makes more sense to reuse the logic and also because APIRequest is now only locally accessible in the tmdb package, to stop me from using anywhere else, should always use an exposed function from the package so it can be reused.
2026-08-03 01:14:02 +00:00
IRHM fb1017f551 tmdb: Make req local, Movie/Show details funcs now accept struct options 2026-08-03 01:14:02 +00:00
IRHM bff354fcc3 organize tmdb api request logic into tmdb package AND support inline search filters 2026-08-03 01:14:02 +00:00
IRHM 0be6fdb346 content: Improve search function formatting 2026-08-03 01:14:02 +00:00
IRHM a73651808e Update CHANGELOG.md 2026-08-01 03:48:44 +00:00
IRHM 9da0913d48 Add Status & ReleaseDateLast to Media, show end year for tv shows 2026-08-01 03:48:44 +00:00
IRHM 0a38171836 doc: installation/for-development: update outdated commands
we switched to using make a while ago, forgot to update this doc
2026-07-30 22:50:38 +01:00
IRHM d009528388 Update CHANGELOG.md 2026-07-30 21:33:41 +00:00
IRHM cd34ecba61 changelog: correct the new stuff and put it under new instead of changed 2026-07-30 21:33:41 +00:00
IRHM 769e30c9c7 import: Support rating column decimals 2026-07-30 21:33:41 +00:00
IRHM ba961bf5c3 Update CHANGELOG.md 2026-07-30 21:33:41 +00:00
IRHM efddcaed07 doc: importing/text-file: Update to show support for providing a rating 2026-07-30 21:33:41 +00:00
IRHM 76fdbe3cd0 import: Remove "Try refreshing" text from the successfully imported notification
It is no longer very pertinent since all watched data isn't stored in the browser. When we redirect the user to their list, fresh data is already fetched.
2026-07-30 21:33:41 +00:00
IRHM f4b7f66104 import->text list: Support providing a rating in square brackets 2026-07-30 21:33:41 +00:00
IRHM 12ceb13bcb import: Add rating column (validated to be 0-10) and set import item state to FAILED if request fails 2026-07-30 21:33:41 +00:00
IRHM 5a5ae0ad83 Show Aired Date for episodes. 2026-07-30 03:46:29 +00:00
IRHM 05e24e42c6 Show air date with toRelativeDate, hide star when unaired and no votes, make airDate logic a bit more robust 2026-07-30 03:32:32 +00:00
mkarpats e5d93fd8a2 feat: Display air date for unaired episodes
- Show air date for episodes that are in the future.
2026-07-30 03:32:32 +00:00
IRHM bf5d44f404 fix lock closed color dark theme 2026-07-30 02:42:35 +00:00
IRHM 5abbb47fbf only show PosterImage in media pages if we have a extPosterPath 2026-07-30 02:42:35 +00:00
IRHM 40b54c1065 Fix crew each to use unique key 2026-07-30 02:42:35 +00:00
IRHM 3967a3f13f api: Update prod baseURL to be absolute
Only an absolute baseURL will work with our new Reqer class.
2026-07-30 02:42:35 +00:00
IRHM 1f4b917661 docker-compose.dev.yml: Change container name and port to be different than prod container test 2026-07-30 02:42:35 +00:00
IRHM 2202b11e39 fix all linting issues and upgrade the rest of devDependencies
now i should probably test the whole app waaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaauuuuuuuuuugugghghghghghghghghg
2026-07-30 02:42:35 +00:00
IRHM d32a1ecb39 format files (new prettier version changes some formatting)
I'm upset that the textarea closing tag is being put on the same line instead of new lined, but I couldn't figure out what changed, so I'll cry in silence and hope it gets fixed one day.
2026-07-30 02:42:35 +00:00
IRHM 347113be68 ESLint: Migrate to flat config 2026-07-30 02:42:35 +00:00
IRHM 68150b38ec fix lint script - only look in src folder 2026-07-30 02:42:35 +00:00
IRHM dc9e7e9309 test-pr-server: Correct go-version-file path? 2026-07-30 02:42:35 +00:00
IRHM 6457146214 Workflows: test-pr-server: Set go-version-file for setup-go action. 2026-07-30 02:42:35 +00:00
IRHM baba8c8c60 Dockerfile: Upgrade node steps to use version 24. 2026-07-30 02:42:35 +00:00
IRHM 31ddcacf47 Workflows: Upgrade action versions and use node 24. 2026-07-30 02:42:35 +00:00
IRHM be94f1d2b7 Replace axios with native Fetch API & some maintenance 2026-07-30 02:42:35 +00:00
IRHM d7449642ba v4.1.1 changelog 2026-07-26 03:26:00 +01:00
IRHM dbc8b74893 v4.1.1 2026-07-26 02:47:48 +01:00
IRHM 9d5e489675 plex: Stop after 10 redirects
Since the default CheckRedirect has been replaced with ours, we won't get the default protection of erroring after 10 redirects, so i've copied that back in from the std implementation
2026-07-26 01:27:30 +00:00
tonghuaroot 4e6e71687b fix(plex): strip X-Plex-Token on cross-host redirect
The Plex integration used bare http.Client values with no CheckRedirect
policy, so they followed redirects automatically. net/http strips the
standard sensitive headers on a cross-host redirect but not custom-named
headers, so the Plex token carried in X-Plex-Token was forwarded verbatim
to any host the configured PLEX_HOST redirected to, disclosing the
credential.

Route all Plex outbound calls through a shared client whose CheckRedirect
policy deletes X-Plex-Token when the redirect target host differs from the
original request host. Includes a regression test.

Signed-off-by: tonghuaroot <tonghuaroot@gmail.com>
2026-07-26 01:27:30 +00:00
IRHM 8c8d604bc6 v4.1.1-dev1 2026-07-26 01:34:45 +01:00
IRHM 39b82335eb Plex: Add Accept: "application/json" header so plex returns json again
I think the plex api default used to be JSON, which is why it worked, but I guess they changed it to XML. Adding this header asks for JSON response again.
2026-07-26 00:33:23 +00:00
IRHM 217be719e4 Revert "README: Open demo/track links in new tab"
This reverts commit 0da32164a3.
2026-07-21 09:38:20 +01:00
IRHM 0da32164a3 README: Open demo/track links in new tab 2026-07-21 09:36:49 +01:00
IRHM db72d05d79 README: Add instructions to demo instance login
I'm sure the extra clarity may be appreciated
2026-07-21 09:31:49 +01:00
IRHM 88a7542064 update readme and contributing text 2026-07-21 09:20:33 +01:00
IRHM 19c773976d CHANGELOG: v4.1.0 2026-07-19 14:40:44 +01:00
IRHM a16c769273 v4.1.0 2026-07-19 14:15:42 +01:00
IRHM f022dc702c v4.1.0-dev1 2026-07-18 13:05:20 +01:00
IRHM c2f72dbd9c Remove dependabot.yml. 2026-07-18 12:58:30 +01:00
IRHM d777630e84 CHANGELOG: Add credit to SeasonsListEpisode change 2026-07-18 12:51:03 +01:00
IRHM f5bfa29877 SeasonsListEpisode: Show spoilers when status is set to FINISHED and allow changing status while spoilers are hidden
Based on PR by goestav: https://github.com/sbondCo/Watcharr/pull/1055

Different in these ways:
- Using $derived here for `ws` variable
- Using z-index to allow status button to be clicked while spoilers are hidden
- Don't hide spoilers again (if they are shown) when episode is deleted

Also refactored `handleStatusClick()` a bit by removing the redundant `ws` lookup (it can now just use `we` set at the top of the component).

Co-Authored-By: Goestav <27970303+goestav@users.noreply.github.com>
2026-07-18 11:48:52 +00:00
IRHM 9b64932af1 watched_refine: refineFilterStatus: Remove parenthesis around WHERE query.
It looks like GORM already adds the parenthesis around this for us in the final query, so ours was unnecessary
2026-07-18 09:50:53 +00:00
IRHM bf0594c1e8 Fix Include Previously Watched regression and update profile stats to not use the setting
Index also added to

Fixes https://github.com/sbondCo/Watcharr/issues/1027
2026-07-18 09:50:53 +00:00
IRHM fee82df59d CHANGELOG: v4.0.1 2026-07-16 10:29:15 +01:00
IRHM 61382de4d2 v4.0.1 2026-07-16 10:07:58 +01:00
IRHM e65ba9d1d9 v4.0.1-dev1 2026-07-16 09:40:47 +01:00
IRHM 6654d85448 testing workflow - no longer testing workflow cuz it works now yippee 2026-07-16 08:36:22 +00:00
IRHM eabdb47cfa testing workflow - gofmt 2026-07-16 08:36:22 +00:00
IRHM 643ca0fd38 testing workflow - go test 2026-07-16 08:36:22 +00:00
IRHM a08b19675a test-pr-server.yml: Set working directory to server to fix commands not running against our go code 2026-07-16 08:36:22 +00:00
IRHM 38fba0ac10 Watched: Also log the error on the "failed to restore existing watched entry" log. 2026-07-16 08:36:22 +00:00
IRHM f23552c170 Use an svg for the favicon and change its fill to white for dark themed browsers. 2026-07-16 08:36:22 +00:00
IRHM 448fdd9df3 SpinnerTiny: Fix circle animation appearing to skip 2026-07-16 08:36:22 +00:00
IRHM ca428327e2 Move notifications to its own component. 2026-07-16 08:36:22 +00:00
IRHM f7cca74a41 SpinnerTiny: Use svg instead of the css border trick to create the spinner fixing it looking more like a horseshoe than a circle on different browser scales (also added animation on the svg circle).
also: Fix color being wrong on dark theme.

svg fix inspired by mui :)
2026-07-16 08:36:22 +00:00
IRHM 86286b967f workflows/test-pr-server: Add test step 2026-07-16 08:36:22 +00:00
IRHM 8243838bfb Update CHANGELOG.md 2026-07-11 03:55:10 +01:00
IRHM 5bebb754ed v4.0.0 2026-07-11 03:28:19 +01:00
IRHM c8920c911d migrate: Change debug log to info
and add an info migration not been applied before log.
2026-07-11 03:27:31 +01:00
IRHM dd0bae137f migrations: Remove comment TODO
Should be okay with them there.
2026-07-10 22:08:04 +01:00
IRHM d5baee0df7 v4.0.0-dev1 2026-07-10 21:42:03 +01:00
IRHM 764a25be6c Changelog: Add youtube-nocookie change 2026-07-10 21:36:15 +01:00
IRHM c019162994 Update CHANGELOG.md 2026-07-10 20:30:23 +00:00
IRHM 05f9813be8 image: validate: Don't log whole image config 2026-07-10 20:30:23 +00:00
IRHM f285d1a8f4 image: Move new download/save methods to a Saver struct 2026-07-10 20:30:23 +00:00
IRHM 4cc9bd3edb make image module way more robust
- Create a better (more) re-usable flow for downloading images to disk and inserting images into the db
- Validate images properly by reading them fully and using DecodeConfig
- Fix some security issues by re-encoding images
- Always outputs one format `jpeg`, which keeps everything "normalized" and adds compression to images (mainly user uploads which might be big).
2026-07-10 20:30:23 +00:00
IRHM 34f7f54e72 fix: Add headers to requests for files in img/ folder to prevent stored xss attacks
A modern browser will see these headers and protect the user by not allowing any code to run.
2026-07-10 20:30:23 +00:00
hilmer 3fe2d2b155 Fix(ViewTrailerButton): Use youtube-nocookie.com 2026-07-05 17:49:12 +00:00
IRHM 3461a4ec74 db: Add duration to log for optimization queries 2026-07-05 17:39:42 +00:00
IRHM 475c9b6ab4 CHANGELOG: Add link for unreleased 2026-07-05 17:39:42 +00:00
IRHM 325666c30d CHANGELOG: Add credit to unreleased change 2026-07-05 17:39:42 +00:00
IRHM 92816b02a0 doc: Backup: Also note that watcharr.db-wal should be backed up along with the .db file since v3. 2026-07-05 17:39:42 +00:00
IRHM 363c648964 changelog/README: Fix the link to changelog... 2026-07-05 17:39:42 +00:00
IRHM 2f929e99d5 Move all old github release notes into new CHANGELOG
Having the changelog file is one more step to no vendor lock-in. It's also more easily searched through and in a standard format everyone is probably used to.

Just so you know, this was painful and I wanted nothing but death for myself throughout this whole process.
2026-07-05 17:39:42 +00:00
IRHM f14be89680 Update CHANGELOG.md 2026-07-05 17:39:42 +00:00
IRHM ecd027f603 Create CHANGELOG.md 2026-07-05 17:39:42 +00:00
IRHM f80f237143 plays support for frontend
soz did this so long ago
2026-07-05 17:39:42 +00:00
IRHM dbfc354353 GetWatchedPage: Put filter scope on one line 2026-07-05 17:39:42 +00:00
IRHM 28a6d85672 Update watched.go 2026-07-05 17:39:42 +00:00
IRHM b861cfcec3 separate watched_refine funcs 2026-07-05 17:39:42 +00:00
IRHM 08e0021535 refineSort: Filter by user_id AND use count_as_play instead of doing text search for LastFinished sort 2026-07-05 17:39:42 +00:00
IRHM b3bf111f82 Replace Fatal log with more direct Error and os.Exit 2026-07-05 17:39:42 +00:00
IRHM 23ed5ffca8 Add separator log for log files so a new server starting is easier to find/notice 2026-07-05 17:39:42 +00:00
IRHM cc9f246c9a update watched_util_test with new model name 2026-07-05 17:39:42 +00:00
IRHM 75d75248e1 Remove AddActivity endpoint
it isn't used and is only a way for others to potentially add activity to other peoples watched entries since user owning the watched entry is not validated on the endpoint.

Co-Authored-By: Dreddy <24421368+dredsen@users.noreply.github.com>
2026-07-05 17:39:42 +00:00
IRHM c34a0878b2 New Deref helper for using pointers safely with default values 2026-07-05 17:39:42 +00:00
IRHM 681212566b activity: Change AddRequest name to Props. Add CountAsPlay param to AddActivity()
and some formatting
2026-07-05 17:39:42 +00:00
IRHM df37de00e1 manually validate WatchedUpdateRequest struct and add plays count to watcheddto 2026-07-05 17:39:42 +00:00
IRHM fc900d8e93 db: Optimize when opening and new optimize task ran every 24hr server is running to keep it running best 2026-07-05 17:39:42 +00:00
IRHM 57ce143ebe migrate db to WAL journal_mode 2026-07-05 17:39:42 +00:00
IRHM 3eb2810a31 db: Configure sqlite connection when open. Currently set synchronous to FULL
(did this work a long time ago now so commits are in weird order)
2026-07-05 17:39:42 +00:00
IRHM b8598ba404 Remove deleted_at columns for watched episode/season tables
We don't use these columns and won't in the foreseeable future. Query speed seems be to be faster now that we aren't filtering for the extra deleted_at cols.
2026-07-05 17:39:42 +00:00
IRHM 579428d86b migrate: Backfill media plays data from existing activity 2026-07-05 17:39:42 +00:00
IRHM 4da8730b6f Activity: Add CountAsPlay property 2026-07-05 17:39:42 +00:00
IRHM e980a1f70e db: Create custom migrations support 2026-07-05 17:39:42 +00:00
IRHM f73105e9c7 v3.0.2-dev1 2026-03-19 01:30:26 +00:00
IRHM 755b08b746 Nav: Fix logo link being clickable through whole left side of nav
The logo link on nav to go to home page was clickable through the whole left side of the nav, now it is only clickable over the actual link text.
2026-03-19 01:29:16 +00:00
IRHM 5e412f67b9 Status: Fix button sizes now that icons have a width/height set 2026-03-19 01:29:16 +00:00
IRHM 4ee38a2625 Icon: Fix status icons not having width and height properties not set 2026-03-19 01:29:16 +00:00
IRHM dc6ead0fb3 fix safari: Shrikhand font
The font-style in the @font-face declaration was set to italic, but we use the font without using that style, which Safari is very strict about and wont match.
2026-03-19 01:29:16 +00:00
IRHM a12faf8e72 v3.0.1 2026-03-09 11:14:19 +00:00
IRHM eb1b8b86c7 v3.0.1-dev2 2026-03-09 10:48:51 +00:00
IRHM dca1acbbd8 Modal: Specify color
Fixes WatchedDeleteModal for light theme because of inherited css from content pages and this is the easiest fix for now
2026-03-09 10:47:24 +00:00
IRHM 664caa6ba2 v3.0.1-dev1 2026-03-09 09:14:26 +00:00
IRHM a425abcdf2 Poster: Grayscale poster if deleted from watched list through poster button
After deleting from your watched list through the poster, we didn't have any real indication to the user that this poster is for a deleted entry (other than the notification and removing the watched status from poster).

Now we grayscale and blur the poster slightly so it's more obvious that it is a deleted entry and won't be there next time you refresh.
2026-03-09 09:12:06 +00:00
IRHM 13b15e03d0 Poster: Add check for watched before calling removeWatched 2026-03-09 09:12:06 +00:00
IRHM 3b4a5a27e6 Add confirmation modal when deleting from your list
to avoid accidental data loss (thoughts, rating status)
2026-03-09 08:46:03 +00:00
IRHM 13bd37c32c doc: Fix old license being referenced and update some of the simple features list on the homepage. 2026-03-09 07:01:22 +00:00
IRHM 2d6d3c005c Activity: Fix automation icon not showing for mobile 2026-03-09 07:01:22 +00:00
IRHM f72f950871 Icon: Fix 'sparkles' svg path on dark theme by using currentColor fill for the path 2026-03-09 07:01:22 +00:00
IRHM e4e015daf8 age->GetAge: If we don't have a birthday skip processing
Otherwise eg: we get current year - 1 as someones age if their birthday isn't listed on tmdb
2026-03-09 07:01:22 +00:00
IRHM 3db89f3214 SpinnerTiny: Fix color for dark theme 2026-03-09 03:34:57 +00:00
IRHM d379d3f147 igdb: Fix some logs, only log req on Debug because it could be sensitive 2026-03-09 03:34:57 +00:00
IRHM ac8d8769af import: Support games importing
Fixing watcharr import from watcharr export not importing users games.

Also works if user edits the table in import/process to change the type of something to a game (and multi results works too).

Added warning message if user tries importing a watcharr export that has games when `!serverFeatures.games`
2026-03-09 03:34:57 +00:00
IRHM 7a7bd4f566 jellyfin sync: Fix addWatched params formatting 2026-03-06 18:33:12 +00:00
IRHM ca82a36d23 sync: Update err soft deleted comments 2026-03-06 18:33:12 +00:00
IRHM 1e6a97202b tag: GetTagPage: Remove debug call 2026-03-06 18:33:12 +00:00
IRHM 0e54a8c44a sync: Fix already on list handling by using new add watched func AND no longer auto restore soft deleted records
no longer auto restoring soft deleted records means if the user (soft) deletes a show (default behavior), the next sync job wont add it back.
2026-03-06 18:33:12 +00:00
IRHM 5c4c7be115 import: Fix already on list handling by using new add watched func 2026-03-06 18:33:12 +00:00
IRHM f458eec732 watched: abide by new api in router 2026-03-06 18:33:12 +00:00
IRHM 8ad2208162 watched: Restore can be skipped with flag and now returns a new error if watched just plain exists 2026-03-06 18:33:12 +00:00
IRHM 28c373173b v3.0.0 2026-03-04 09:08:01 +00:00
ImgBotApp d637e04ba4 [ImgBot] Optimize images
*Total -- 12,324.41kb -> 10,332.72kb (16.16%)

/screenshot/discover-page.png -- 1,064.08kb -> 804.68kb (24.38%)
/screenshot/content-details-page.png -- 665.72kb -> 510.47kb (23.32%)
/screenshot/content-details-page-dark.png -- 674.65kb -> 519.95kb (22.93%)
/screenshot/user-profile.png -- 75.25kb -> 60.43kb (19.69%)
/screenshot/person-page.png -- 1,362.18kb -> 1,096.48kb (19.51%)
/screenshot/retired-04-03-26/content-details-page-dark.png -- 487.52kb -> 393.40kb (19.31%)
/screenshot/retired-04-03-26/content-details-page.png -- 342.39kb -> 278.55kb (18.65%)
/screenshot/homepage-poster-change-status.png -- 1,048.82kb -> 899.79kb (14.21%)
/screenshot/homepage-poster-hover.png -- 1,064.36kb -> 913.21kb (14.2%)
/screenshot/retired-04-03-26/discover-page.png -- 900.18kb -> 777.06kb (13.68%)
/screenshot/homepage.png -- 1,126.26kb -> 989.01kb (12.19%)
/screenshot/devices-mock.png -- 2,379.62kb -> 2,092.85kb (12.05%)
/screenshot/homepage-dark.png -- 1,133.39kb -> 996.83kb (12.05%)

Signed-off-by: ImgBotApp <ImgBotHelp@gmail.com>
2026-03-04 08:57:22 +00:00
IRHM 5fb92daf0c WatchedDto: Add comment to thoughts 2026-03-04 08:49:43 +00:00
IRHM 7f4da2d90e v3.0.0-dev5 2026-03-04 08:41:45 +00:00
IRHM 199a97e3a7 (fix) Thoughts modal not closing after clicking close first time because contentChanged funcs no longer return bool
so updated the funcs to return bools
2026-03-04 08:37:02 +00:00
IRHM af04698625 (fix) Add thoughts to watchedDto for Content Page responses 2026-03-04 08:22:09 +00:00
IRHM a9f928a44c doc: Homepage: Add person page image and update the rest to latest version
Updating v to reset anyones cache
2026-03-04 07:57:15 +00:00
IRHM 485408390b new screens for content, person & discover pages 2026-03-04 07:52:11 +00:00
IRHM 2bad7bc272 docs: Update workflows to use nodejs v20 2026-03-04 07:34:23 +00:00
IRHM 8d0642086c doc: importing/trakt: Add section on the optional api key field 2026-03-04 07:30:09 +00:00
IRHM 3b0b99ad9a doc: Update all deps 2026-03-04 07:29:52 +00:00
IRHM c16e0af3b2 v3.0.0-dev4 2026-03-04 06:54:57 +00:00
IRHM e0f49f25b2 (bug) filter/sort: Scroll to top of page after changing 2026-03-04 06:53:36 +00:00
IRHM 7561b59037 v3.0.0-dev3 2026-03-04 03:46:48 +00:00
IRHM 72932f7acd search: Fix from-my-list-msg width responsiveness 2026-03-04 03:45:28 +00:00
IRHM e7751807f6 search: Disable MediaTypeFilter if showingResultsFrom 2026-03-04 03:45:28 +00:00
IRHM cb97aa3914 search->searchMyList: Add a lil commento 2026-03-04 03:45:28 +00:00
IRHM d1e9a60beb watched: Remove leftover debug call on query 2026-03-04 03:45:28 +00:00
IRHM 0a09e71af7 search: Improve 'do a full search' text 2026-03-04 03:45:28 +00:00
IRHM 404b7c680f search: Return resp directly when we fetched the data FromMyList
to avoid extra unnecessary db queries
2026-03-04 03:45:28 +00:00
IRHM 9bb4f3f948 (feat) Search your own list for results before external search 2026-03-04 03:45:28 +00:00
IRHM 52bb995937 Replace PageError with just Error component and make it look nicer 2026-03-04 03:45:28 +00:00
IRHM 624a3b1bbf v3.0.0-dev2 2026-03-03 18:23:00 +00:00
IRHM a314231780 search: multi: Only get games for first page 2026-03-03 18:21:17 +00:00
IRHM ba6ae06a5f search: Keep the searchbar truly centered 2026-03-03 18:21:17 +00:00
IRHM fc4d65ccbc tv seasons: Fix release date 2026-03-03 18:21:17 +00:00
IRHM d5f8644554 Poster: Fix details-shown class not added when img errors when loading 2026-03-03 18:21:17 +00:00
IRHM 4b0abd13cc Poster: Fix creating poster urls with undefined extPosterPath
This fixes the details-shown class not being added because were constructing a string with undefined at the end
2026-03-03 18:21:17 +00:00
IRHM c62c2cdfc0 Update twitch config and fix possible undefined issues 2026-03-03 18:21:17 +00:00
IRHM 8955cacee6 search: Don't attempt game search if twitch is not configured 2026-03-03 18:21:17 +00:00
IRHM 8fbf4ddc6d config: Create TwitchEnabled func 2026-03-03 18:21:17 +00:00
IRHM 70f59697d3 Dockerfile: Add comment to server copy command 2026-03-01 22:38:51 +00:00
IRHM 22f77aa142 build: Fix dockerfile server job not copying in packages 2026-03-01 22:38:01 +00:00
IRHM 532d3f49c7 v3.0.0-dev1 2026-03-01 22:20:28 +00:00
momi 3ff325cda9 Merge pull request #1019 from sbondCo/list-pagination-2
Watcharr v3.0.0
2026-03-01 22:16:19 +00:00
265 changed files with 29203 additions and 21335 deletions
+2
View File
@@ -0,0 +1,2 @@
server/data/
server/Makefile
-15
View File
@@ -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
-27
View File
@@ -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,
},
};
+2
View File
@@ -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! -->
-27
View File
@@ -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"
+6 -6
View File
@@ -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
+7 -7
View File
@@ -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
+4 -4
View File
@@ -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:
+3 -3
View File
@@ -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
+13 -3
View File
@@ -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: |
+3 -3
View File
@@ -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
+2
View File
@@ -1 +1,3 @@
engine-strict=true
ignore-scripts=true
min-release-age=14
+1912
View File
File diff suppressed because it is too large Load Diff
+7 -1
View File
@@ -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!
+7 -6
View File
@@ -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 -2
View File
@@ -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
+15 -2
View File
@@ -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/>.
Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 284 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 273 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 878 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 360 KiB

+5
View File
@@ -0,0 +1,5 @@
## Changelog Data
Changelog images, etc go in this folder.
[View the real changelog for Watcharr.](../CHANGELOG.md)
+6 -1
View File
@@ -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>)]
+14 -1
View File
@@ -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.
+7 -5
View File
@@ -17,7 +17,7 @@ This section assumes you will be forking the repo on Github, of course you can a
![Fork button](./img/forking-repo.png)
2. Get the code by cloning your fork
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):
+1 -1
View File
@@ -35,7 +35,7 @@ Backing up this way is discouraged because new important files could be added la
If you don't care about the warning not to backup this way, here are the "important" files that you can single out for backup:
- `watcharr.db` 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).
+17164 -14662
View File
File diff suppressed because it is too large Load Diff
+10 -10
View File
@@ -14,17 +14,17 @@
"write-heading-ids": "docusaurus write-heading-ids"
},
"dependencies": {
"@docusaurus/core": "3.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"
}
}
+7 -8
View File
@@ -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.
</>
),
},
+11 -6
View File
@@ -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>
);
+2 -2
View File
@@ -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
+60
View File
@@ -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",
},
],
},
},
);
+3390 -3255
View File
File diff suppressed because it is too large Load Diff
+23 -23
View File
@@ -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"
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 488 KiB

After

Width:  |  Height:  |  Size: 520 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 342 KiB

After

Width:  |  Height:  |  Size: 510 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 MiB

After

Width:  |  Height:  |  Size: 2.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 900 KiB

After

Width:  |  Height:  |  Size: 805 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 MiB

After

Width:  |  Height:  |  Size: 997 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 MiB

After

Width:  |  Height:  |  Size: 900 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 MiB

After

Width:  |  Height:  |  Size: 913 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 MiB

After

Width:  |  Height:  |  Size: 989 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 393 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 279 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 777 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 75 KiB

After

Width:  |  Height:  |  Size: 60 KiB

+1 -1
View File
@@ -1 +1 @@
3.0.0
4.2.1
+6
View File
@@ -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
+8 -1
View File
@@ -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) {
+151 -3
View File
@@ -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
}
+8
View File
@@ -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"`
}
+15 -1
View File
@@ -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
View File
@@ -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"`
+1 -1
View File
@@ -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"`
+1 -1
View File
@@ -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"`
+11
View File
@@ -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
}
+103
View File
@@ -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
}
+137
View File
@@ -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
},
},
}
+19 -2
View File
@@ -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
}
+1 -1
View File
@@ -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 {
+49 -3
View File
@@ -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 {
+7
View File
@@ -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:
+9 -1
View File
@@ -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 {
+59 -4
View File
@@ -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.
+45 -13
View File
@@ -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
-17
View File
@@ -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")
+57 -406
View File
@@ -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
}
+31 -23
View File
@@ -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

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