Compare commits

...

223 Commits

Author SHA1 Message Date
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
IRHM 4e40a9fdb5 config: Fix generateConfig not setting our cfg var
Altered the read func to return a ServerConfig pointer instead of taking one in
2026-03-01 22:12:27 +00:00
IRHM 81a67404d3 Fix setup
authProvider wasn't being passed in
2026-03-01 21:47:29 +00:00
IRHM 307f5324f0 image->DownloadAndInsertImage: Replace fatal log with err response 2026-03-01 21:05:34 +00:00
IRHM 4a922df7e4 user->UploadUserAvatar: Replace fatal log with err response 2026-03-01 21:03:45 +00:00
IRHM d89252c4fe Dockerfile: Update backend base image to golang 1.25
going to update to 1.26 another day
2026-03-01 20:58:41 +00:00
IRHM 749808cd70 Dockerfile: Fix COPY requiring trailing slash on dest dir 2026-03-01 20:57:34 +00:00
IRHM 0e4249ee42 AddWatched: Keep support for the 'contentId' property for now
Instead of completely removing it, I've added it back so third party scripts can migrate to the new property 'tmdbId'.

I realised I don't want to break any ones experience, this should allow for a painfree path to migration.
2026-03-01 20:44:26 +00:00
IRHM ce264cbf4a TraktImport: Add a log for when a custom api key is provided 2026-03-01 20:27:51 +00:00
IRHM 47388d327d Setting: Remove margin.
if a margin is wanted, we can add it outside the component on a wrapper element.
2026-03-01 20:21:49 +00:00
IRHM 26dfad19bc TraktImport: Renew default api-key and support bringing your own key
Resolves #1014
2026-03-01 20:21:11 +00:00
IRHM dce22cf8e8 profile: Mark 'Include Previously Watched' as due to be removed
and ask for feedback if anyone actually uses this or prefers it off.

Incase people do actually find this setting useful, I'm leaving it intact and not creating a db migration to drop it yet until I hear any feedback.. otherwise I'll just delete it in one of the updates after 3.0.
2026-03-01 19:24:42 +00:00
IRHM 230ea306ce Create safe dtos for get Arr servers public 2026-03-01 01:03:31 +00:00
IRHM 36159f5792 tag: Update page to work as others do 2026-02-27 15:54:35 +00:00
IRHM 50c265de24 tag: Fix GetTagPage returning whole watched list if tag is empty 2026-02-27 15:54:22 +00:00
IRHM d408cee754 tag: Update response to match other watched responses (Media) 2026-02-27 15:53:34 +00:00
IRHM 24f5ea19f5 UpdateWatchedLastViewedSeason: improve format 2026-02-27 15:18:52 +00:00
IRHM 9c26b6b1d7 TestGetLatestWatchedInTv
made a lil test, should probably make more these when i have time
2026-02-26 22:21:33 +00:00
IRHM 7f1c2f2e26 watched: move public list response to its own type
If we add stuff that should never be on a public list to the other type, we can't leak it now on public ones.
2026-02-26 21:43:42 +00:00
IRHM b2c24761e0 Move watching season logic to server, move to master WatchedDto, ...
Remove WatchedList component and create PosterLists directly on watched list and other users list pages.

Get Watched endpoints now return Media with watched inside them, same structure as search, etc. This makes the client logic easier and means we can always expect the same data response no matter how we request data.

Fix race cond in paginatedLoader & abort previous request inside reset func.
2026-02-26 21:33:19 +00:00
IRHM 65d5a581f8 game: Add itchio provider 2026-02-26 03:10:18 +00:00
IRHM 9c17a5fbe7 SeasonsListEpisode: Remove bindable from watchedItem prop 2026-02-25 23:01:30 +00:00
IRHM c9b3f26dfe tv: fix SeasonsList
using derived to make a web request = slap on hand

and it was causing a bug where it would request the season twice after selecting another tv series from the similar list
2026-02-25 22:59:41 +00:00
IRHM e54a99cedd tv: Add similar results 2026-02-25 22:07:16 +00:00
IRHM d4faaa2e85 Create ExpandableText component from Bio and use it on all content pages 2026-02-25 22:03:48 +00:00
IRHM 5cb0a6c666 games: Display steam/gog providers 2026-02-25 20:16:12 +00:00
IRHM 0ac70349b4 style: Fix mask for PageBackdrop on dark theme 2026-02-24 19:50:09 +00:00
IRHM 181ce99746 norm.scss: Use global blocks unformly
Use the global blocks everywhere without having an argument.

Simpler using this everywhere instead of mix and matching + it will work when we have styles underneath so we dont have to keep adding global tag in each selector inside a global tag
2026-02-24 19:29:29 +00:00
IRHM 42dd90579f fix import typing 2026-02-24 17:27:15 +00:00
IRHM ad51f36a0e ExportList modal 2026-02-24 17:25:07 +00:00
IRHM 0d4fc8a9df fix arr component errors 2026-02-24 04:52:11 +00:00
IRHM 0921282de6 WatchedList: New Date Released sort option
Implements #1016
2026-02-24 02:08:27 +00:00
IRHM e785a9a92b content/page.scss: Improve responsiveness 2026-02-24 01:55:08 +00:00
IRHM 2e6acf12e4 person: remove duplicate styles in page 2026-02-24 01:54:47 +00:00
IRHM 94c43b1aac Make dto for person response and add age 2026-02-24 00:33:18 +00:00
IRHM c900ea7f0a fix person page and update styling 2026-02-24 00:01:12 +00:00
IRHM e8ec1c36d1 use Poster component for games too, add watched works for games too in one endpoint
use media in content pages, remove canvas from dom after img loaded in poster, fix filter menu buttons active style, view trailer btn is a component now, show justwatch attribution (didnt realise we had to until i saw the api docs to check providers data), no longer need to use copier for detail responses, move and make tranformproviders more resilient
2026-02-22 19:59:27 +00:00
IRHM e454f6845b Discover->FilterDropDown: Keep disabled until user selects a content filter
I think it may be less confusing this way to users, since on the main multi page there is only the trending filter, so when they change the content filter it may not be obvious that more options are added, this way it is disabled until there are options that do something for the type of content selected.
2026-02-18 16:58:06 +00:00
IRHM 86735e5093 make pagetitle more responsive for mobile for discovery page 2026-02-18 16:42:35 +00:00
IRHM bd049e75e2 discover: add comment to DiscoverMulti 2026-02-17 20:56:41 +00:00
IRHM 69a66e2183 discover games - trending and upcoming support 2026-02-17 20:50:32 +00:00
IRHM bf6f87246b discover page rework
adding games back later, got the new page working 1000x better for movies, tv and people (new!).

Some slight refactoring to other stuff I touched when getting the discover package up and running.
2026-02-16 23:49:18 +00:00
IRHM 85bb71758e game: Remove search endpoints 2026-02-15 10:42:19 +00:00
IRHM 333912c694 search: Fix back btn not updating query and dont search if no query 2026-02-15 10:38:20 +00:00
IRHM 0c287e0bfa search: Fix restore of search query not being decoded 2026-02-15 10:25:27 +00:00
IRHM e9a7898be5 content pages redesign of details section and separated some parts into components to reduce duplication 2026-02-14 22:54:41 +00:00
IRHM bdf7e0199d scss comment typo 2026-02-14 21:18:06 +00:00
IRHM b6def6f43d Replace import with use for sass and reduce css output bundle by only prepending partials
- Moved main scss files to src/styles.
- Instead of prepending all our global styles in svelte.config.js, we now only prepend our sass logic that doesn't build to css, which reduces the output css massively by avoiding duplicative imports. Our norm.scss is now imported in the root +layout file.
- Update sass package
- Renamed mixins and vars scss files to start with an underscore, which indicates they are partial files
2026-02-14 21:17:05 +00:00
IRHM dbb96177e8 watched: Refactor AddWatched and move restoration logic to new func 2026-02-11 06:33:34 +00:00
IRHM 42ac57b0a6 movie: Fix updateWatched call 2026-02-11 06:20:53 +00:00
IRHM c421f63977 GetWatchedPage: Return with a new DTO type that includes Media 2026-02-10 09:27:44 +00:00
IRHM 91a2aa9648 content pages: Show details div at 100% width always
Fixes case where we have no overview text that stretches the div out to 100% usually, so width is very small
2026-02-09 13:24:47 +00:00
IRHM f12e7d8f17 Title: Only show release year if we have it 2026-02-09 13:23:45 +00:00
IRHM f77bc1c125 tmdb: Correct ExtPosterPaths for people 2026-02-09 13:14:21 +00:00
IRHM da2a7e3952 search: correct logs 2026-02-09 13:07:43 +00:00
IRHM e5a0609f5b content: Add mem caching to SearchPeople 2026-02-09 13:06:40 +00:00
IRHM 1f216e512c content: Remove search endpoints
main search endpoint to be used instead
2026-02-09 13:06:22 +00:00
IRHM bff92b8bce logging: AddSource to logs 2026-02-09 12:49:33 +00:00
IRHM f7898326f0 igdb: add mem caching 2026-02-09 12:49:01 +00:00
IRHM efbb1078d6 search: correct logs 2026-02-08 11:14:18 +00:00
IRHM d25692577d search by igdb id or url/slug 2026-02-08 11:12:29 +00:00
IRHM 01619e1da0 search by external id or by url 2026-02-08 10:48:15 +00:00
IRHM 7008e69a90 search: Reactively access type search param 2026-02-07 11:04:35 +00:00
IRHM e666d5f332 search and media type in decent place 2026-02-07 01:02:34 +00:00
IRHM 897cc8a044 search service wip 2026-02-02 23:16:18 +00:00
IRHM 6db6149e6b pagination: Change 'q' and 'l' query parameters into 'query' and 'limit'
I don't want this api to become a confusing behemoth so lets use full words where it makes sense.

'p' and 'l' also didn't fit in with our other query params that are already just the full word like 'type', etc.
2026-01-29 19:43:57 +00:00
IRHM 1310c6e996 watched->GetPublicWatched: Replace panic with error reponse
some good old legacy code ;()
2026-01-29 17:48:34 +00:00
IRHM 5ea51c7257 content: fix nil pointer deref 2026-01-29 17:46:17 +00:00
IRHM ec280dbc20 support games getting watched data 2026-01-29 17:42:45 +00:00
IRHM d454b9ff57 Create reusable paginated loader helper and use it for main list loading
This helper will stop us having so much "duplicated" logic for loading pages of data
2026-01-26 16:26:27 +00:00
IRHM 978aab0804 tags: Get tag page endpoint
Support added to our main GetWatchedPage service so we can use it in our tags service
2026-01-26 16:24:00 +00:00
IRHM 0d648372b8 Fix SeasonsList and SeasonsListEpisode 2026-01-05 03:45:58 +00:00
IRHM 9d25406652 watched_refine: Fix alpha sort 2026-01-04 02:10:27 +00:00
IRHM 68d15dbd5c watched_refine: Sort pinned items to top 2026-01-03 21:07:11 +00:00
IRHM 69d6f44cc5 loadWatchedList: Set page/maxpage vars before results.len check
This fixed spamming of get page requests when resizing, etc for next page when the list is empty (because max page wont be set to 0)
2026-01-02 23:48:57 +00:00
IRHM a996ab9767 WatchedList: Show only error when no results and error, update no results because filters message 2026-01-02 23:47:53 +00:00
IRHM 4b48d849a5 getWatchedPage: Preload watched Seasons and Episodes
Because the UI currently relies on this information for displaying the Last Watched extra detail for posters.

At some point, it'd likely be best that that logic is migrated to the backend, but for now doesn't really matter.
2026-01-02 23:04:08 +00:00
IRHM 941fab4b0e fix some formatting 2026-01-02 23:02:40 +00:00
IRHM ce845b5bdb server: getWatchedPage: Remove debug from query 2026-01-02 22:45:20 +00:00
IRHM 693904a1ba server: GetWatched: Implement filters 2026-01-01 21:34:15 +00:00
IRHM 53306bad48 server: Upgrade gin 2026-01-01 20:56:54 +00:00
IRHM 26bcf3491f tag: Add spinner while getting tag
im a 10x engineer got damn
2025-11-24 02:51:05 +00:00
IRHM 8f4cf90589 tags working 2025-11-23 21:10:48 +00:00
IRHM 727a8244f4 watched: Remove comment where watchedRefine is used, no longer true 2025-11-20 00:06:15 +00:00
IRHM a1810a1f75 store->updateSortAndFiltersForQueryParams: Make logic more robust and only add properties if they will have a value 2025-11-19 23:57:49 +00:00
IRHM 808cd50599 SortMenu->sortClicked: If mode is empty, reset activeSort 2025-11-19 23:54:54 +00:00
IRHM bfd404cdce SortMenu->sortClicked: Remove unused modeType parameter and related unused logic 2025-11-19 23:54:21 +00:00
IRHM 927b04acaf watched_refine: Fix query for watchedSortLastFinished sort
The query works as intended now (i think), gonna test it more later.

Not sure if performance has improved much, but without adjusting how our data looks I'm not sure how it could be solved. Going to worry about this specific sorts performance later though if it arises as an issue (its only a few ms more in my dev env on 1000 watched items, testing on beta site will give me a better idea since it has a lot more records).
2025-11-19 23:25:59 +00:00
IRHM 3384e6f8b5 server: Update gorm 2025-11-19 22:15:43 +00:00
IRHM a73e99f2dc main: Add version to startup slog
unlike the startup graphic, this will actually be logged to file so it can be referenced
2025-11-19 22:15:10 +00:00
IRHM 7d5427e656 Fix watched list loading forever if zero results 2025-11-16 02:36:18 +00:00
IRHM 14b6be0d64 tag: Create GetTag 2025-11-16 02:23:34 +00:00
IRHM 391534dc77 fix Activity and ActivityEditor 2025-11-16 01:45:12 +00:00
IRHM 142fef5f43 fix person view and add watched data 2025-11-16 00:45:42 +00:00
IRHM e28aea4497 Make: Fix version target by stopping newline from echo into VERSION file 2025-11-14 20:13:52 +00:00
IRHM 05855571e1 contentRouter: Add error checks to all addedtocontent calls 2025-11-14 19:52:05 +00:00
IRHM a1b35fa70b search: Show multi search errors with the specific request that failed 2025-11-14 19:51:34 +00:00
IRHM e69bf8c2ab addedtocontent->AddList: Check 's' length before any other logic 2025-11-14 19:32:57 +00:00
IRHM 407e6a5a35 addedtocontent: Return errors from all funcs 2025-11-14 19:32:27 +00:00
IRHM 64404eb3a8 addedtocontent: Remove unused WatchedAddedToContent struct 2025-11-14 19:22:50 +00:00
IRHM 7dc956ff89 contentRouter->GetSearchByExternalId: Add watched data to response
Likely will never hit a case where the frontend will need this, but added anyways incase anyone making third party scripts want this functionality in the future
2025-11-14 19:15:22 +00:00
IRHM 1ed24be195 content->SearchByExternalId: Add cache to func level 2025-11-14 19:14:15 +00:00
IRHM ba5e690a3d Addable: Change GetMediaType return type to ContentType 2025-11-14 18:58:48 +00:00
IRHM 581cbb9917 tmdb: Fix TMDBMovieDetailsBase type methods 2025-11-14 18:54:59 +00:00
IRHM 7395b3b034 watched data for content requests 2025-11-14 03:19:40 +00:00
IRHM 234120f6eb Create FEATURES.md 2025-11-14 02:59:30 +00:00
IRHM 4596c34ffd season: Fix routes 2025-11-14 02:58:48 +00:00
IRHM 2e53997f9e (refactor) Move db from service function parameters to service structs
Now that we have everything encapsulated in Services, we can move the db parameters of each function into the service struct itself which:
1. Simplified calling and reduces us passing around the db in random funcs that just pass it to a service func
2. probably other stuff
3. looks nicer now
2025-11-07 00:46:07 +00:00
IRHM fd309c44bb Make: Disable git commit for npm version command 2025-11-06 22:48:42 +00:00
IRHM 40ec711f71 Create Makefile for updating version numbers 2025-11-06 22:44:44 +00:00
IRHM ad643e6641 main: Embed version and show it in startup log 2025-11-06 22:44:19 +00:00
IRHM 62e0911b85 main: Move startup art one line over, looks a bit better in my terminal 2025-11-06 20:54:23 +00:00
IRHM 8320d379f7 beautiful startup art 2025-11-06 01:13:41 +00:00
IRHM 29a207ed10 fix tag import 2025-11-05 01:52:43 +00:00
IRHM df3ac430da LICENSE: We are now part of the gpl gang
couldn't decide between v2 and v3, but i don't think any downsides of v3 apply to our app here so v3 seems safest
2025-11-05 01:50:04 +00:00
IRHM 14eba564cb uniformize feature and plex routers 2025-10-26 18:12:56 +00:00
IRHM 37a37b83c1 servicize tag 2025-10-26 18:07:24 +00:00
IRHM 1a6aa30d67 move image, task, job mods up a folder
because this differenciates them better from the more user-facing features inside the 'features' folder.
2025-10-26 18:03:39 +00:00
IRHM f2f2cf4d23 arr init all struct props 2025-10-26 17:38:22 +00:00
IRHM bf7a001f26 servicize imprt 2025-10-26 17:35:37 +00:00
IRHM cff7debdad servicize follow 2025-10-26 17:32:48 +00:00
IRHM 8a271122e9 servicize user 2025-10-26 17:29:47 +00:00
IRHM 9019413d81 servicize profile 2025-10-26 17:14:26 +00:00
IRHM 4775505653 servicize activity 2025-10-26 17:10:34 +00:00
IRHM cbdf926392 main: Move img static ep to below router starts again 2025-10-25 18:27:59 +01:00
IRHM 66e2d6a41d PageError: Correct if on error detail para
So it only shows the para when there is actually an error to show
2025-10-25 18:16:43 +01:00
IRHM e3029ff558 plug in existing services
i say "plug in" because that sounds cool, im just initializing them and the routers (the ones I have made so far)
2025-10-25 18:11:11 +01:00
IRHM 8f2a76e9a8 (wip) server restructure/refactor 2025-10-24 18:37:20 +01:00
IRHM 61fa88167c game watched data 2025-07-27 20:44:07 +01:00
IRHM 84e86cc256 movie page 2025-07-19 14:10:03 +01:00
IRHM 1a56660523 FilterMenu: Fix type btn overflow and style to be pills 2025-07-19 13:28:51 +01:00
IRHM 7b24ff619d wip: Watched sorting, fixed watcheds loader 2025-07-19 13:28:51 +01:00
IRHM 2f17d9fcea fix search person (use PaginatedRequest) 2025-07-19 13:28:51 +01:00
IRHM bb0d89b25f add watched to discover data and fix search pagination 2025-07-19 13:28:51 +01:00
IRHM ddebe11ddc getWatchedItemsByTmdbIds: Update log to comment out all watcheds 2025-07-19 13:28:51 +01:00
IRHM f3f182a26c getWatched: return err instead of panicking 2025-07-19 13:28:51 +01:00
IRHM 031ae7cf03 Support poster adding/removing watched, and make watched prop bindable to update parent data too 2025-07-19 13:28:51 +01:00
IRHM b094abe69b fix get watched caching and move addWatched to content stuff to functions 2025-07-19 13:28:51 +01:00
IRHM ed32101a76 removeWatched: Make notify call success when successfully removed 2025-07-19 13:28:51 +01:00
IRHM 43da0f82d2 Update WatchedList.svelte 2025-07-19 13:28:51 +01:00
IRHM 26eadb10b3 forgot what i did but progressed 2025-07-19 13:28:51 +01:00
IRHM f9dd7c6c73 infScroll: Add callback isloading requirement for implementing in comment 2025-07-19 13:28:51 +01:00
IRHM 78b7f85bd0 infScroll: Create dataLoaded func for ensuring full page of data is present after page loads 2025-07-19 13:28:51 +01:00
IRHM 4285a51d5a Create go-cache GetCache helper func
Easier to use this method so we can simply pass a pointer of our var in and let it do everything for us, relieves us of our manual type assertion duty everywhere we get from cache.
2025-07-19 13:28:51 +01:00
IRHM 0546faeb6c tv: remove old comment 2025-07-19 13:28:51 +01:00
IRHM 345a28fcc1 wip: getting show watched data in request 2025-07-19 13:28:51 +01:00
IRHM b1d5da0451 wip: content: move watched entry to inside content object
instead of separating both, should be easier to work with this way and enable it to work for search results without complex mapping etc to find related watched entries
2025-07-19 13:28:51 +01:00
IRHM 0115b3f238 wip: content: returning watched along with tv response 2025-07-19 13:28:51 +01:00
IRHM 9be0420534 main page: show spinner while loading next list page 2025-07-19 13:28:51 +01:00
IRHM 4748e891db watched list pagination in ui 2025-07-19 13:28:51 +01:00
IRHM 6e4356ca0a search: Use infScroll 2025-07-19 13:28:51 +01:00
IRHM 14c54ce92d Create infScroll helper with reusable logic
based on the infinite scroll code from search page
2025-07-19 13:28:51 +01:00
IRHM 5ed2650a39 finalize PaginationResponse, get count in watchedpage 2025-07-19 13:28:51 +01:00
IRHM c1e81cbab4 watched: Create getWatchedPage for paginated response 2025-07-19 13:28:51 +01:00
IRHM a0ab7d8413 v2.1.1 2025-07-15 23:21:29 +01:00
IRHM 282255dbea 2.1.1-dev3 2025-07-15 22:44:24 +01:00
JoshF fa69639123 fix bug on return from blurhash.Encode (#922) 2025-07-15 21:41:30 +00:00
JoshF e177562c5a fix Twitch init error logging bug (#921) 2025-07-15 21:35:40 +00:00
IRHM 6d0203c6e1 2.1.1-dev2 2025-07-14 23:30:58 +01:00
IRHM 45921a0c94 StarRating: Still save rating if scroll change is less than 10px in either direction
This fixes firefox mobile.

Chromium on mobile stops the page from scrolling with a grace area while dragging the stars, but firefox doesn't do this, which breaks the (if scrolled dont save logic), so added the 10px grace into logic.

Future fix could be to stop the scrolling to mimic chromium behaviour for firefox mobile too, but that sound hard. Maybe firefox can fix this.
2025-07-14 23:30:32 +01:00
IRHM 18ab577662 StarRating: Fix rating change saved twice on chromium mobile when a star is clicked
without being dragged first.
2025-07-14 23:28:12 +01:00
IRHM acb388e271 2.1.1-dev1 2025-07-14 18:53:15 +01:00
IRHM d7dafc8d67 import: Remove returning of only the perfect matches if more than 1
Just had an epiphany that it'd be better to return all results in this case, the frontend still sorts for best matches to be shown first, but then we keep all other options incase the users import data had a slight typo that matched other content etc.
2025-07-14 18:52:33 +01:00
IRHM 77f73bd03b 2.1.1-dev 2025-07-14 18:46:56 +01:00
Mr a47952e61d StarRating: Ignore star presses if scroll position changes from start to end of click (#916)
* StarRating: Ignore star presses if scroll position changes from start to end of click

This should help us avoid accidental clicks of stars being saved when the user is just trying to scroll down the page.

* StarRating: Make scrollLocAtStart a normal variable

doesnt need to be $state
2025-07-13 18:42:34 +00:00
Mr 72f8ddc8e6 import: Perfect matching now takes Year into account if provided, avoiding muli result responses (#915)
perfect matches are also collected (before only one was allowed to perfect match) and all are returned if multiple

#914
2025-07-13 15:59:52 +00:00
IRHM 6a53066b72 v2.1.0 2025-05-18 19:03:30 +01:00
IRHM 9ebc46d7d4 2.1.0-dev1 2025-05-18 17:52:13 +01:00
IRHM 0456eefe3b FaceMenu: Increase width to 140px
So the version string doesn't need to overflow when it includes the `-dev` affix
2025-05-18 17:51:10 +01:00
IRHM 3b85331f3b 2.1.0-dev 2025-05-18 17:45:45 +01:00
Mr 56fe1152c5 Search shortcut & add missing keys that search handler should ignore (#886)
* (fix) handleSearch: Add missing keys that we should ignore

* (new) Create global keybing handler, ctrl+s search bind

* focusSearch: Add try/catch
2025-05-18 16:38:06 +00:00
dependabot[bot] 699f19badb ui: bump typescript from 5.7.2 to 5.8.3 (#865)
* ui: bump typescript from 5.7.2 to 5.8.3

Bumps [typescript](https://github.com/microsoft/TypeScript) from 5.7.2 to 5.8.3.
- [Release notes](https://github.com/microsoft/TypeScript/releases)
- [Changelog](https://github.com/microsoft/TypeScript/blob/main/azure-pipelines.release-publish.yml)
- [Commits](https://github.com/microsoft/TypeScript/commits)

---
updated-dependencies:
- dependency-name: typescript
  dependency-version: 5.8.3
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

* dep: bump typescript-eslint to 8.32.1

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: IRHM <37304121+IRHM@users.noreply.github.com>
2025-05-18 16:03:35 +00:00
dependabot[bot] e415f77e5a ui: bump eslint-config-prettier from 9.1.0 to 10.1.2 (#872)
Bumps [eslint-config-prettier](https://github.com/prettier/eslint-config-prettier) from 9.1.0 to 10.1.2.
- [Release notes](https://github.com/prettier/eslint-config-prettier/releases)
- [Changelog](https://github.com/prettier/eslint-config-prettier/blob/main/CHANGELOG.md)
- [Commits](https://github.com/prettier/eslint-config-prettier/compare/v9.1.0...v10.1.2)

---
updated-dependencies:
- dependency-name: eslint-config-prettier
  dependency-version: 10.1.2
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-05-18 15:54:06 +00:00
dependabot[bot] 124323cc59 ui: bump sass from 1.83.0 to 1.86.3 (#867)
Bumps [sass](https://github.com/sass/dart-sass) from 1.83.0 to 1.86.3.
- [Release notes](https://github.com/sass/dart-sass/releases)
- [Changelog](https://github.com/sass/dart-sass/blob/main/CHANGELOG.md)
- [Commits](https://github.com/sass/dart-sass/compare/1.83.0...1.86.3)

---
updated-dependencies:
- dependency-name: sass
  dependency-version: 1.86.3
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-05-18 15:52:41 +00:00
dependabot[bot] ee716a9dc8 ui: bump @typescript-eslint/eslint-plugin from 8.19.0 to 8.30.1 (#874)
Bumps [@typescript-eslint/eslint-plugin](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/eslint-plugin) from 8.19.0 to 8.30.1.
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.30.1/packages/eslint-plugin)

---
updated-dependencies:
- dependency-name: "@typescript-eslint/eslint-plugin"
  dependency-version: 8.30.1
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-05-18 15:41:21 +00:00
dependabot[bot] c4694e577f ui: bump prettier-plugin-svelte from 3.3.2 to 3.3.3 (#773)
Bumps [prettier-plugin-svelte](https://github.com/sveltejs/prettier-plugin-svelte) from 3.3.2 to 3.3.3.
- [Changelog](https://github.com/sveltejs/prettier-plugin-svelte/blob/master/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/prettier-plugin-svelte/commits)

---
updated-dependencies:
- dependency-name: prettier-plugin-svelte
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-05-18 15:39:39 +00:00
dependabot[bot] d8f914ddca ui: bump axios from 1.7.9 to 1.8.4 (#855)
Bumps [axios](https://github.com/axios/axios) from 1.7.9 to 1.8.4.
- [Release notes](https://github.com/axios/axios/releases)
- [Changelog](https://github.com/axios/axios/blob/v1.x/CHANGELOG.md)
- [Commits](https://github.com/axios/axios/compare/v1.7.9...v1.8.4)

---
updated-dependencies:
- dependency-name: axios
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-05-18 15:33:58 +00:00
dependabot[bot] 4d145d593b ui: bump vite from 6.0.7 to 6.2.6 (#873)
Bumps [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) from 6.0.7 to 6.2.6.
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/v6.2.6/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v6.2.6/packages/vite)

---
updated-dependencies:
- dependency-name: vite
  dependency-version: 6.2.6
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-05-17 18:59:28 +00:00
dependabot[bot] 889aa30150 ui: bump @sveltejs/kit from 2.16.0 to 2.20.6 (#875)
Bumps [@sveltejs/kit](https://github.com/sveltejs/kit/tree/HEAD/packages/kit) from 2.16.0 to 2.20.6.
- [Release notes](https://github.com/sveltejs/kit/releases)
- [Changelog](https://github.com/sveltejs/kit/blob/main/packages/kit/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/kit/commits/@sveltejs/kit@2.20.6/packages/kit)

---
updated-dependencies:
- dependency-name: "@sveltejs/kit"
  dependency-version: 2.20.6
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-05-17 18:51:40 +00:00
IRHM 490192b386 chore: ui: fix formatting in import 2025-05-17 19:50:55 +01:00
dependabot[bot] 9a9cf1e3fb server: bump github.com/go-co-op/gocron/v2 in /server (#842)
Bumps [github.com/go-co-op/gocron/v2](https://github.com/go-co-op/gocron) from 2.14.2 to 2.16.1.
- [Release notes](https://github.com/go-co-op/gocron/releases)
- [Commits](https://github.com/go-co-op/gocron/compare/v2.14.2...v2.16.1)

---
updated-dependencies:
- dependency-name: github.com/go-co-op/gocron/v2
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-05-17 18:39:46 +00:00
dependabot[bot] 300b063b9a server: bump github.com/golang-jwt/jwt/v5 from 5.2.1 to 5.2.2 in /server (#846)
Bumps [github.com/golang-jwt/jwt/v5](https://github.com/golang-jwt/jwt) from 5.2.1 to 5.2.2.
- [Release notes](https://github.com/golang-jwt/jwt/releases)
- [Changelog](https://github.com/golang-jwt/jwt/blob/main/VERSION_HISTORY.md)
- [Commits](https://github.com/golang-jwt/jwt/compare/v5.2.1...v5.2.2)

---
updated-dependencies:
- dependency-name: github.com/golang-jwt/jwt/v5
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-05-17 18:36:44 +00:00
IRHM 99be784453 server: Upgrade to go 1.24 2025-05-17 19:33:07 +01:00
dependabot[bot] 2f6cf1c0db server: bump golang.org/x/crypto from 0.32.0 to 0.37.0 in /server (#863)
Bumps [golang.org/x/crypto](https://github.com/golang/crypto) from 0.32.0 to 0.37.0.
- [Commits](https://github.com/golang/crypto/compare/v0.32.0...v0.37.0)

---
updated-dependencies:
- dependency-name: golang.org/x/crypto
  dependency-version: 0.37.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-05-17 18:26:49 +00:00
dependabot[bot] 23e686385c server: bump github.com/gin-contrib/cors from 1.7.3 to 1.7.5 in /server (#864)
Bumps [github.com/gin-contrib/cors](https://github.com/gin-contrib/cors) from 1.7.3 to 1.7.5.
- [Release notes](https://github.com/gin-contrib/cors/releases)
- [Changelog](https://github.com/gin-contrib/cors/blob/master/.goreleaser.yaml)
- [Commits](https://github.com/gin-contrib/cors/compare/v1.7.3...v1.7.5)

---
updated-dependencies:
- dependency-name: github.com/gin-contrib/cors
  dependency-version: 1.7.5
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-05-17 18:22:03 +00:00
Antonio Sarro cbe445b7d9 feat(theme): add system preference handling to theme configuration (#822)
* feat(theme): add system preference handling to theme configuration

* Moved theme logic to new file, renamed vars, move system theme btn to top

- Moved `system` theme button to top (since its default).
- Moved theme logic to new `theme.ts` file & renamed some variables.
- Store: Revert change that sets updateStore=true when rehydrating theme (not necessary since we update store manually)

---------

Co-authored-by: IRHM <37304121+IRHM@users.noreply.github.com>
2025-05-17 18:12:22 +00:00
Iván Iglesias 087071a8af Support for importing ryot 8 files (#862)
- media renamed to metadata
- shows now support overall score
2025-05-17 17:01:34 +00:00
jigglycrumb a0a74e8cdc feat: improve imdb import (#880)
Makes the IMDb importer more robust by identifying more media types like Direct-to-Video movies, TV Mini Series and more which are all not regconized and thus skipped by the current importer.

It also makes a tiny UI change by adding the year of the imported movie to the "Multiple Results Found" dialog, which makes identifying the actually imported movie more easy and should help to reduce mismatches.
2025-05-17 16:48:52 +00:00
Mr a16769e0db doc: Add text-file, trakt, watcharr pages for importing. (#883)
* doc: Add text-file, trakt, watcharr pages for importing.

* doc: importing/watcharr: Fix backup guide link
2025-05-11 19:47:56 +00:00
231 changed files with 34648 additions and 26107 deletions
+2
View File
@@ -0,0 +1,2 @@
server/data/
server/Makefile
+1 -1
View File
@@ -24,7 +24,7 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 18
node-version: 20
cache: npm
- name: Install dependencies
+1 -1
View File
@@ -19,7 +19,7 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 18
node-version: 20
cache: npm
- name: Install dependencies
+6 -5
View File
@@ -1,12 +1,13 @@
#
# Backend
#
FROM golang:1.22-alpine AS server
FROM golang:1.25-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
@@ -33,7 +34,7 @@ FROM node:20-alpine AS runner
COPY --from=server /server/watcharr /
COPY --from=ui /app/build /ui
COPY --from=ui /app/package.json /app/package-lock.json /ui
COPY --from=ui /app/package.json /app/package-lock.json /ui/
# Install just the prod dependencies for final step.
# We --ignore-scripts, to stop the `prepare` script from auto-
+57
View File
@@ -0,0 +1,57 @@
# Watcharr Features
A basic top-level view of the features included in Watcharr.
When the word `watched` is used, assume it can be `played` for games too.
Have a look at when this document was last updated, it may have missing features.
- Watched List
- Supported Content:
- Movies
- TV Shows / Anime
- Seasons
- Episodes
- Games
- Filtering
- Sorting
- Pinning
- Thoughts (for writing a review, etc)
- Activity (detailed list of modifications made to each watched item)
- Importing from other services
- Content detail pages
- Basic overview
- Watch trailer
- Available streaming providers in your region
- Cast
- Similar content
- Person detail pages
- Basic overview
- All credits (movies & tv they appear in or worked on)
- Searching for content
- Custom tags
- Discovery page
- Following other users
- Simple user stats (movies watched, time spent watching, etc)
- User Settings
- Dark & Light themes
- Privacy
- Hide Spoilers
- Rating System
- Out of 5
- Out of 10
- Out of 100
- Rating Step
- And more generic settings..
- Server dashboard
- Basic stats
- Configuration editing
- User management (including permissions)
- Jellyfin Integration
- Auth
- 'Play On Jellyfin' buttons
- Plex Integration
- Trusted Header Authentication (for auth via proxy)
- Basic Sonarr & Radarr integration
- Let users Request content (users can be given an auto approve permission)
- Manage content requests
+670 -17
View File
@@ -1,21 +1,674 @@
MIT License
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (c) 2023 IRHM
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
Preamble
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+16
View File
@@ -0,0 +1,16 @@
.PHONY: dev version
dev:
./node_modules/.bin/vite dev
dev_host:
./node_modules/.bin/vite dev --host
# Don't judge me.
version:
@$(eval VER := $(filter-out $@,$(MAKECMDGOALS)))
@echo "Updating version to $(VER)"
echo -n "$(VER)" > ./server/VERSION
npm version $(VER) --git-tag-version false
%:
@:
+4
View File
@@ -72,6 +72,10 @@ 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.
# License
This project is licensed under the GPLv3 license. You should see the [LICENSE](LICENSE) file located in the root folder of this project for the full license text, if not, see <https://www.gnu.org/licenses/>.
# Contributing
Please continue to our [contributing guide](CONTRIBUTING.md).
+1 -1
View File
@@ -1,5 +1,5 @@
---
sidebar_position: 1
sidebar_position: 2
---
# MyAnimeList
+30
View File
@@ -0,0 +1,30 @@
---
sidebar_position: 1
---
# Text File (.txt list)
:::info Backup?
You may consider a backup of your server before starting any import. They are not easily reversible, though we do our best to ensure they are accurate and bug free!
:::
The text file (.txt) import is of an arbitrary format (the one I used for years before creating Watcharr).
Hopefully it is useful for others with similar files or in scenarios where its the easiest to generate for an import (though if possible, when generating a backup from another service data manually, matching a Watcharr export would enable keeping more data).
## Format
Each line is a new entry. The name of the content (show/movie) must be provided, 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.
```
<name> [(<year>)]
```
## An example
```
The Terminator (1984)
Breaking Bad
A Fistful of Dollars
Reacher (2022)
```
+29
View File
@@ -0,0 +1,29 @@
---
sidebar_position: 3
---
# Trakt
:::info Backup?
You may consider a backup of your server before starting any import. They are not easily reversible, though we do our best to ensure they are accurate and bug free!
:::
**Note:** Your Trakt profile must be public _during_ this process. You are free to private it again once it completes.
1. Provide your Trakt username in the text box.
2. (Optional) [Provide your own api key](#optional-api-key).
3. Press `Start Import`.
This will be a long process, possibly a couple hours depending on how large of a Trakt history you have. If you think it has frozen or isn't working, try checking your server logs to see if it is doing anything.
### (Optional) API Key
This step is optional because Watcharr comes built in with its own API Key that it can use for your import, however, if you encounter any issues where imports cannot start or keep failing and you see any `403` errors in your server logs, providing your own key may fix the problem.
#### Getting an API Key
1. [Visit this link to create a new Trakt API App](https://trakt.tv/oauth/applications/new).
2. Fill out all required fields (`Name` and `Redirect uri`) with any random data.
1. You can set the `Redirect uri` to any value the input accepts since we don't use it (eg: `http://localhost`)
3. Click `Save App`.
4. You should now be redirected to your new app. Copy the `Client ID` into the `API Key` textbox in Watcharr.
+16
View File
@@ -0,0 +1,16 @@
---
sidebar_position: 0
---
# Watcharr
:::info Backup?
You may consider a backup of your server before starting any import. They are not easily reversible, though we do our best to ensure they are accurate and bug free!
:::
:::warning May not be what you want
Watcharr import/export is a feature intended for end users. If you are the server admin, it is recommended that you copy your server files directly to any new server you are creating (it'll be much faster and easier). [See backup guide](/docs/server_config/backup).
:::
1. Provide the Watcharr export file (that you generated from your profile page).
2. Review the import table, if everything looks good, start the import.
+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"
}
}
+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>
);
+400 -311
View File
File diff suppressed because it is too large Load Diff
+12 -12
View File
@@ -1,6 +1,7 @@
{
"name": "watcharr",
"version": "2.0.2",
"license": "GPL-3.0-only",
"version": "3.0.0",
"private": true,
"scripts": {
"dev": "vite dev",
@@ -10,32 +11,31 @@
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"prepare": "svelte-kit sync",
"lint": "prettier --check . && eslint .",
"format": "prettier --write .",
"server": "cd ./server && MODE=DEV go run ."
"format": "prettier --write ."
},
"devDependencies": {
"@sveltejs/adapter-node": "^5.2.12",
"@sveltejs/kit": "^2.16.0",
"@sveltejs/kit": "^2.21.0",
"@types/papaparse": "^5.3.15",
"@typescript-eslint/eslint-plugin": "^8.18.2",
"@typescript-eslint/parser": "^8.18.2",
"@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": "^9.1.0",
"eslint-config-prettier": "^10.1.2",
"eslint-plugin-svelte": "^2.45.1",
"prettier": "^3.4.2",
"prettier-plugin-svelte": "^3.2.6",
"sass": "^1.83.0",
"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.7.2",
"vite": "^6.0.7"
"typescript": "^5.8.3",
"vite": "^6.3.5"
},
"type": "module",
"dependencies": {
"axios": "^1.7.4",
"axios": "^1.9.0",
"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

+8
View File
@@ -0,0 +1,8 @@
run:
MODE=DEV go run .
plainrun:
go run .
test:
go test ./...
+1
View File
@@ -0,0 +1 @@
3.0.0
-130
View File
@@ -1,130 +0,0 @@
package main
import (
"errors"
"log/slog"
"time"
"gorm.io/gorm"
)
type ActivityType string
// _AUTO activities are for when logic updates something for the user (automations basically).
var (
ADDED_WATCHED ActivityType = "ADDED_WATCHED"
REMOVED_WATCHED ActivityType = "REMOVED_WATCHED"
RATING_CHANGED ActivityType = "RATING_CHANGED"
STATUS_CHANGED ActivityType = "STATUS_CHANGED"
STATUS_CHANGED_AUTO ActivityType = "STATUS_CHANGED_AUTO"
THOUGHTS_CHANGED ActivityType = "THOUGHTS_CHANGED"
THOUGHTS_REMOVED ActivityType = "THOUGHTS_REMOVED"
IMPORTED_WATCHED ActivityType = "IMPORTED_WATCHED"
IMPORTED_WATCHED_JF ActivityType = "IMPORTED_WATCHED_JF"
IMPORTED_WATCHED_PLEX ActivityType = "IMPORTED_WATCHED_PLEX"
IMPORTED_RATING ActivityType = "IMPORTED_RATING" // Imported rating, but with no rating acts as original import of content to old platform (where they are importing from) activity
IMPORTED_ADDED_WATCHED ActivityType = "IMPORTED_ADDED_WATCHED" // Imported watched date, so we can save the original watch dates of content from users old platform (where they are importing from).
IMPORTED_ADDED_WATCHED_JF ActivityType = "IMPORTED_ADDED_WATCHED_JF"
IMPORTED_ADDED_WATCHED_PLEX ActivityType = "IMPORTED_ADDED_WATCHED_PLEX"
SEASON_ADDED ActivityType = "SEASON_ADDED"
SEASON_ADDED_AUTO ActivityType = "SEASON_ADDED_AUTO"
SEASON_ADDED_JF ActivityType = "SEASON_ADDED_JF"
SEASON_ADDED_PLEX ActivityType = "SEASON_ADDED_PLEX"
SEASON_REMOVED ActivityType = "SEASON_REMOVED"
SEASON_RATING_CHANGED ActivityType = "SEASON_RATING_CHANGED"
SEASON_STATUS_CHANGED ActivityType = "SEASON_STATUS_CHANGED"
SEASON_STATUS_CHANGED_AUTO ActivityType = "SEASON_STATUS_CHANGED_AUTO"
EPISODE_ADDED ActivityType = "EPISODE_ADDED"
EPISODE_ADDED_JF ActivityType = "EPISODE_ADDED_JF"
EPISODE_ADDED_PLEX ActivityType = "EPISODE_ADDED_PLEX"
EPISODE_REMOVED ActivityType = "EPISODE_REMOVED"
EPISODE_RATING_CHANGED ActivityType = "EPISODE_RATING_CHANGED"
EPISODE_STATUS_CHANGED ActivityType = "EPISODE_STATUS_CHANGED"
)
type Activity struct {
GormModel
// ID of user this activity is linked to, so it can be easily
// secured (users can only view their own activities).
UserID uint `json:"-" gorm:"not null"`
// ID of watched list item this activity is linked to.
WatchedID uint `json:"watchedId" gorm:"not null"`
// Type of activity.
Type ActivityType `json:"type" gorm:"not null"`
// Holds custom data (ex, if rating changed, this can
// hold new rating - if status changed, this will hold that).
Data string `json:"data" gorm:"not null"`
// Custom date for the activity, that the user can define.
CustomDate *time.Time `json:"customDate,omitempty"`
}
type ActivityAddRequest struct {
WatchedID uint `json:"watchedId" binding:"required"`
Type ActivityType `json:"type" binding:"required"`
Data string `json:"data" binding:"required"`
CustomDate *time.Time `json:"customDate,omitempty"`
}
type ActivityUpdateRequest struct {
CustomDate time.Time `json:"customDate" binding:"required"`
}
func getActivity(db *gorm.DB, userId uint, watchedId uint) ([]Activity, error) {
activity := new([]Activity)
res := db.Model(&Activity{}).Where("user_id = ? AND watched_id = ?", userId, watchedId).Find(&activity)
if res.Error != nil {
slog.Error("Failed getting activity from database", "error", res.Error.Error())
return []Activity{}, errors.New("failed getting activity")
}
return *activity, nil
}
func addActivity(db *gorm.DB, userId uint, ar ActivityAddRequest) (Activity, error) {
if ar.WatchedID == 0 {
return Activity{}, errors.New("watchedId must be set to add an activity")
}
activity := Activity{UserID: userId, WatchedID: ar.WatchedID, Type: ar.Type, Data: ar.Data, CustomDate: ar.CustomDate}
res := db.Create(&activity)
if res.Error != nil {
slog.Error("Error adding activity to database", "error", res.Error.Error())
return Activity{}, errors.New("failed adding new activity to database")
}
slog.Debug("Adding activity", "added_activity", activity)
return activity, nil
}
func updateActivity(db *gorm.DB, userId uint, id uint, activityUpdateRequest ActivityUpdateRequest) error {
if id == 0 {
return errors.New("id must be set to update an activity")
}
if activityUpdateRequest.CustomDate.IsZero() {
return errors.New("customDate must be set to update an activity")
}
res := db.Model(&Activity{}).Where("user_id = ? AND id = ?", userId, id).Update("custom_date", activityUpdateRequest.CustomDate)
if res.Error != nil {
slog.Error("Error updating activity in database", "error", res.Error.Error())
return errors.New("failed updating activity in database")
}
if res.RowsAffected < 1 {
slog.Error("No activities were updated. This may be because the activity doesn't exist or is not owned by the calling user.")
return errors.New("failed updating activity in database")
}
slog.Debug("Updating activity", "updated_activity", id)
return nil
}
func deleteActivity(db *gorm.DB, userId uint, id uint) error {
if id == 0 {
return errors.New("an id must be provided to delete an activity")
}
res := db.Where("user_id = ?", userId).Delete(&Activity{}, id)
if res.Error != nil {
slog.Error("Error deleting activity in database", "error", res.Error.Error())
return errors.New("failed deleting activity in database")
}
if res.RowsAffected < 1 {
slog.Error("No activities were deleted. This may be because the activity doesn't exist or is not owned by the calling user.")
return errors.New("failed deleting activity from database")
}
return nil
}
-206
View File
@@ -1,206 +0,0 @@
package main
import (
"errors"
"log/slog"
"github.com/sbondCo/Watcharr/arr"
)
type ArrSettings struct {
Name string `json:"name,omitempty"`
Host string `json:"host,omitempty"`
Key string `json:"key,omitempty"`
}
type SonarrSettings struct {
ArrSettings
QualityProfile int `json:"qualityProfile,omitempty"`
RootFolder int `json:"rootFolder,omitempty"`
LanguageProfile int `json:"languageProfile,omitempty"`
AutomaticSearch bool `json:"automaticSearch"`
// TODO eventually separate profiles and root for anime content (i can see diff language profile being useful)
}
func (s *SonarrSettings) safe() SonarrSettings {
s.Key = ""
return *s
}
type RadarrSettings struct {
ArrSettings
QualityProfile int `json:"qualityProfile,omitempty"`
RootFolder int `json:"rootFolder,omitempty"`
AutomaticSearch bool `json:"automaticSearch"`
}
func (s *RadarrSettings) safe() RadarrSettings {
s.Key = ""
return *s
}
type ArrTestParams struct {
Host string `json:"host,omitempty"`
Key string `json:"key,omitempty"`
}
type SonarrTestResponse struct {
QualityProfiles []arr.QualityProfile `json:"qualityProfiles"`
RootFolders []arr.RootFolder `json:"rootFolders"`
LanguageProfiles []arr.LanguageProfile `json:"languageProfiles"`
}
type RadarrTestResponse struct {
QualityProfiles []arr.QualityProfile `json:"qualityProfiles"`
RootFolders []arr.RootFolder `json:"rootFolders"`
LanguageProfiles []arr.LanguageProfile `json:"languageProfiles"`
}
// Response given to users with PERM_REQUEST_CONTENT - should never include sensitive info
func testSonarr(p ArrTestParams) (SonarrTestResponse, error) {
sonarr := arr.New(arr.SONARR, &p.Host, &p.Key)
qps, err := sonarr.GetQualityProfiles()
if err != nil {
slog.Error("testSonarr failed to get quality profiles!", "error", err)
return SonarrTestResponse{}, errors.New("failed to get quality profiles")
}
rfs, err := sonarr.GetRootFolders()
if err != nil {
slog.Error("testSonarr failed to get root folders!", "error", err)
return SonarrTestResponse{}, errors.New("failed to get root folders")
}
lps, err := sonarr.GetLangaugeProfiles()
if err != nil {
slog.Error("testSonarr failed to get language profiles!", "error", err)
return SonarrTestResponse{}, errors.New("failed to get language profiles")
}
return SonarrTestResponse{QualityProfiles: qps, RootFolders: rfs, LanguageProfiles: lps}, nil
}
// Response given to users with PERM_REQUEST_CONTENT - should never include sensitive info
func testRadarr(p ArrTestParams) (RadarrTestResponse, error) {
radarr := arr.New(arr.RADARR, &p.Host, &p.Key)
qps, err := radarr.GetQualityProfiles()
if err != nil {
slog.Error("testRadarr failed to get quality profiles!", "error", err)
return RadarrTestResponse{}, errors.New("failed to get quality profiles")
}
rfs, err := radarr.GetRootFolders()
if err != nil {
slog.Error("testRadarr failed to get root folders!", "error", err)
return RadarrTestResponse{}, errors.New("failed to get root folders")
}
return RadarrTestResponse{QualityProfiles: qps, RootFolders: rfs}, nil
}
// TODO any way to simplify (deduplicate/reuse) these methods (and the whole file tbh) would be very good
// Add sonarr server to config
func addSonarr(s SonarrSettings) error {
for _, v := range Config.SONARR {
if v.Name == s.Name {
// Server exists with this name...
return errors.New("server with that name already exists")
}
}
Config.SONARR = append(Config.SONARR, s)
writeConfig()
return nil
}
// Edit sonarr server in config
func editSonarr(s SonarrSettings) error {
for i, v := range Config.SONARR {
if v.Name == s.Name {
Config.SONARR[i] = s
writeConfig()
return nil
}
}
return errors.New("can't edit server that does not exist")
}
func rmSonarr(name string) error {
for i, v := range Config.SONARR {
if v.Name == name {
Config.SONARR = append(Config.SONARR[:i], Config.SONARR[i+1:]...)
writeConfig()
return nil
}
}
return errors.New("can't remove a server that does not exist")
}
func getSonarr(name string) (SonarrSettings, error) {
for i, v := range Config.SONARR {
if v.Name == name {
return Config.SONARR[i], nil
}
}
return SonarrSettings{}, errors.New("server not found")
}
// Get list of sonarr servers without api keys.
// Regular users with access to adding to sonarr will request this.
func getSonarrsSafe() []SonarrSettings {
s := []SonarrSettings{}
for _, v := range Config.SONARR {
s = append(s, v.safe())
}
return s
}
// Add radarr server to config
func addRadarr(s RadarrSettings) error {
for _, v := range Config.RADARR {
if v.Name == s.Name {
// Server exists with this name...
return errors.New("server with that name already exists")
}
}
Config.RADARR = append(Config.RADARR, s)
writeConfig()
return nil
}
// Edit radarr server in config
func editRadarr(s RadarrSettings) error {
for i, v := range Config.RADARR {
if v.Name == s.Name {
Config.RADARR[i] = s
writeConfig()
return nil
}
}
return errors.New("can't edit server that does not exist")
}
func rmRadarr(name string) error {
for i, v := range Config.RADARR {
if v.Name == name {
Config.RADARR = append(Config.RADARR[:i], Config.RADARR[i+1:]...)
writeConfig()
return nil
}
}
return errors.New("can't remove a server that does not exist")
}
func getRadarr(name string) (RadarrSettings, error) {
for i, v := range Config.RADARR {
if v.Name == name {
return Config.RADARR[i], nil
}
}
return RadarrSettings{}, errors.New("server not found")
}
// Get list of radarr servers without api keys.
// Regular users with access to adding to radarr will request this.
func getRadarrsSafe() []RadarrSettings {
s := []RadarrSettings{}
for _, v := range Config.RADARR {
s = append(s, v.safe())
}
return s
}
+64
View File
@@ -0,0 +1,64 @@
package cache
import (
"log/slog"
"reflect"
"strconv"
"github.com/robfig/go-cache"
)
// Extension of the `.Get` method for `go-cache`.
// This method will simplify our usage so we don't need
// to type assert everywhere, this method will handle
// everything related to getting the value from cache.
// Returns `true` if `rv` was set to the cached value.
// Returns `false` if we couldn't get anything from cache.
func GetCache(c *cache.Cache, k string, rv any) bool {
if val, found := c.Get(k); found {
v := reflect.ValueOf(rv)
if v.Type().Kind() == reflect.Ptr && v.Elem().CanSet() {
v.Elem().Set(reflect.ValueOf(val))
slog.Debug("cachefunc: Cache found.", "key", k)
return true
}
slog.Error("cachefunc: Cache not set", "key", k)
return false
}
slog.Debug("cachefunc: Cache not found", "key", k)
return false
}
// Create a cache key for our in-mem cache.
//
// `name` should be the name of the function response we are caching.
//
// `...u` can be any amount of values that will make this key unique.
// Currently supports types:
// - `string`
// - `map[string]string`
// - `int`
func CreateCacheKey(name string, u ...any) string {
str := name
appnd := func(s string) {
str += "-" + s
}
for _, v := range u {
switch vv := v.(type) {
case string:
appnd(vv)
case map[string]string:
for k, e := range vv {
appnd(k + "_" + e)
}
case int:
appnd(strconv.Itoa(vv))
default:
// This should never happen, but incase of unknown
// value passed, hopefully this should make it easier
// to catch in logs.
str = str + "KEYTYPEERR"
}
}
return str
}
+24
View File
@@ -0,0 +1,24 @@
package cfgmodel
type ArrSettings struct {
Name string `json:"name,omitempty"`
Host string `json:"host,omitempty"`
Key string `json:"key,omitempty"`
}
type SonarrSettings struct {
ArrSettings
QualityProfile int `json:"qualityProfile,omitempty"`
RootFolder int `json:"rootFolder,omitempty"`
LanguageProfile int `json:"languageProfile,omitempty"`
AutomaticSearch bool `json:"automaticSearch"`
// TODO eventually separate profiles and root for anime
// content (i can see diff language profile being useful)
}
type RadarrSettings struct {
ArrSettings
QualityProfile int `json:"qualityProfile,omitempty"`
RootFolder int `json:"rootFolder,omitempty"`
AutomaticSearch bool `json:"automaticSearch"`
}
+135 -177
View File
@@ -1,4 +1,4 @@
package main
package config
import (
"encoding/json"
@@ -9,8 +9,10 @@ import (
"path"
"time"
"github.com/sbondCo/Watcharr/game"
"gorm.io/gorm"
"github.com/sbondCo/Watcharr/config/cfgmodel"
"github.com/sbondCo/Watcharr/logging"
"github.com/sbondCo/Watcharr/media/igdb"
"github.com/sbondCo/Watcharr/util"
)
var DataPath = func() string {
@@ -21,6 +23,24 @@ var DataPath = func() string {
return path
}()
type TrustedHeaderAuthSetting struct {
// Required: Should header auth be enabled?
// This bool exists so header auth can be toggled
// easily without having to remove configuration.
// To be actually enabled, HEADER_NAME must also
// be set.
Enabled bool `json:"enabled"`
// Required: What is the name of the trusted header
// that will contain the logged in users username?
HeaderName string `json:"headerName"`
// Should the frontend attempt auto login if
// trusted header auth is enabled.
AutoLogin bool `json:"autoLogin"`
// Where can we redirect the user to logout
// of the auth service?
LogoutUrl string `json:"logoutUrl"`
}
type ServerConfig struct {
// Used to sign JWT tokens. Make sure to make
// it strong, just like a very long, complicated password.
@@ -28,6 +48,7 @@ type ServerConfig struct {
// Default country for new users. This is used to set the default
// region to get correct content streaming providers.
// TODO Enforce iso_3166_1 validity (same as tmdb)
DEFAULT_COUNTRY string `json:",omitempty"`
// Optional: Point to your Jellyfin install
@@ -58,9 +79,9 @@ type ServerConfig struct {
// VERY DANGEROUS if access is not controlled correctly!
HEADER_AUTH TrustedHeaderAuthSetting `json:",omitempty"`
SONARR []SonarrSettings `json:",omitempty"`
RADARR []RadarrSettings `json:",omitempty"`
TWITCH game.IGDB `json:",omitempty"`
SONARR []cfgmodel.SonarrSettings `json:",omitempty"`
RADARR []cfgmodel.RadarrSettings `json:",omitempty"`
TWITCH igdb.IGDB `json:",omitzero"`
// Optional: Schedule for tasks.
TASK_SCHEDULE map[string]int `json:",omitempty"`
@@ -90,7 +111,7 @@ func (c *ServerConfig) GetSafe() ServerConfig {
DEBUG: c.DEBUG,
SONARR: c.SONARR, // Dont act safe, this contains sonarr api key, needed for config
RADARR: c.RADARR, // Dont act safe, this contains radarr api key, needed for config
TWITCH: game.IGDB{
TWITCH: igdb.IGDB{
ClientID: c.TWITCH.ClientID,
ClientSecret: c.TWITCH.ClientSecret,
}, // Dont act safe, this contains twitch secrets, needed for config
@@ -126,47 +147,117 @@ func (c *ServerConfig) Get(s string) (ServerConfigGetByName, error) {
return ServerConfigGetByName{}, errors.New("invalid setting")
}
var (
// Our server config.. `readConfig` will overwrite from watcharr.json cfg file.
Config = ServerConfig{}
)
// Read config file
// Calls generateConfig if file doesn't exist
func readConfig() error {
cfg, err := os.Open(path.Join(DataPath, "watcharr.json"))
// Update server config property
func (c *ServerConfig) UpdateConfig(k string, v any) error {
slog.Debug("updateConfig", "k", k, "v", v)
if v == nil {
return errors.New("invalid value")
}
if k == "JELLYFIN_HOST" {
c.JELLYFIN_HOST = v.(string)
} else if k == "USE_EMBY" {
c.USE_EMBY = v.(bool)
} else if k == "SIGNUP_ENABLED" {
c.SIGNUP_ENABLED = v.(bool)
} else if k == "TMDB_KEY" {
c.TMDB_KEY = v.(string)
} else if k == "DEBUG" {
c.DEBUG = v.(bool)
logging.SetLevel(c.DEBUG)
} else if k == "DEFAULT_COUNTRY" {
c.DEFAULT_COUNTRY = v.(string)
} else {
return errors.New("invalid setting")
}
err := c.Write()
if err != nil {
if os.IsNotExist(err) {
slog.Info("Config file doesn't exist... generating.")
if err = generateConfig(); err == nil {
return nil
}
}
return err
slog.Error("updateConfig: Failed to write updated config!", "error", err)
return errors.New("failed to write config")
}
defer cfg.Close()
jsonParser := json.NewDecoder(cfg)
if err = jsonParser.Decode(&Config); err != nil {
return err
}
initFromConfig()
return nil
}
// Ensure required config is provided
func initFromConfig() error {
if Config.JWT_SECRET == "" {
log.Fatal("JWT_SECRET missing from config!")
// Write current Config to file
func (c *ServerConfig) Write() error {
barej, err := json.MarshalIndent(*c, "", "\t")
if err != nil {
return err
}
return os.WriteFile(path.Join(DataPath, "watcharr.json"), barej, 0755)
}
func (c *ServerConfig) SaveTwitchConfig(newt igdb.IGDB) error {
// If existing client id and secret are same.. just return here
if (c.TWITCH.ClientID != nil && newt.ClientID != nil && c.TWITCH.ClientSecret != nil && newt.ClientSecret != nil) &&
*c.TWITCH.ClientID == *newt.ClientID && *c.TWITCH.ClientSecret == *newt.ClientSecret {
slog.Info("SaveTwitchConfig: New ClientID and ClientSecret match old ClientID and ClientSecret.. ignoring request to update.")
return nil
}
// Update our config
c.TWITCH.ClientID = newt.ClientID
c.TWITCH.ClientSecret = newt.ClientSecret
c.TWITCH.AccessToken = ""
c.TWITCH.AccessTokenExpires = time.Time{}
// Try to init again
err := c.TWITCH.Init()
if err != nil {
slog.Error("SaveTwitchConfig failed to initialize TWITCH", "error", err)
return errors.New("initialization with credentials failed")
}
err = c.Write()
if err != nil {
slog.Error("SaveTwitchConfig failed to write config", "error", err)
return errors.New("failed to save config")
}
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) {
cfgFile, err := os.Open(path.Join(DataPath, "watcharr.json"))
if err != nil {
if os.IsNotExist(err) {
slog.Info("Config file doesn't exist... generating.")
if genCfg, err := generateConfig(); err == nil {
return genCfg, nil
}
}
return nil, err
}
defer cfgFile.Close()
c := new(ServerConfig)
dec := json.NewDecoder(cfgFile)
if err = dec.Decode(c); err != nil {
return nil, err
}
initFromConfig(c)
return c, nil
}
// Ensure required config is provided
func initFromConfig(c *ServerConfig) {
if c.JWT_SECRET == "" {
log.Fatal("JWT_SECRET missing from config!")
}
}
// Generate new barebones watcharr.json config file.
// Generates a JWT_SECRET and set default config.
func generateConfig() error {
key, err := generateString(64)
func generateConfig() (*ServerConfig, error) {
key, err := util.GenerateString(64)
if err != nil {
return err
return nil, err
}
cfg := ServerConfig{
JWT_SECRET: key,
@@ -176,150 +267,17 @@ func generateConfig() error {
}
barej, err := json.MarshalIndent(cfg, "", "\t")
if err != nil {
return err
return nil, err
}
Config = cfg
return os.WriteFile(path.Join(DataPath, "watcharr.json"), barej, 0755)
return &cfg, os.WriteFile(path.Join(DataPath, "watcharr.json"), barej, 0755)
}
// Update server config property
func updateConfig(k string, v any) error {
slog.Debug("updateConfig", "k", k, "v", v)
if v == nil {
return errors.New("invalid value")
}
if k == "JELLYFIN_HOST" {
Config.JELLYFIN_HOST = v.(string)
} else if k == "USE_EMBY" {
Config.USE_EMBY = v.(bool)
} else if k == "SIGNUP_ENABLED" {
Config.SIGNUP_ENABLED = v.(bool)
} else if k == "TMDB_KEY" {
Config.TMDB_KEY = v.(string)
} else if k == "DEBUG" {
Config.DEBUG = v.(bool)
setLoggingLevel()
} else if k == "DEFAULT_COUNTRY" {
Config.DEFAULT_COUNTRY = v.(string)
} else {
return errors.New("invalid setting")
}
err := writeConfig()
// Get server config.
// Reads from config file.
func Get() (*ServerConfig, error) {
cfg, err := read()
if err != nil {
slog.Error("updateConfig: Failed to write updated config!", "error", err)
return errors.New("failed to write config")
return nil, err
}
return nil
}
// Write current Config to file
func writeConfig() error {
barej, err := json.MarshalIndent(Config, "", "\t")
if err != nil {
return err
}
return os.WriteFile(path.Join(DataPath, "watcharr.json"), barej, 0755)
}
type ServerFeatures struct {
Sonarr bool `json:"sonarr"`
Radarr bool `json:"radarr"`
Games bool `json:"games"`
}
// Get enabled server functionality from Config.
// Mainly so the frontend can store this once and know
// which btns should be shown, etc.
func getEnabledFeatures(userPerms int) ServerFeatures {
var f ServerFeatures
if Config.TWITCH.ClientID != nil && Config.TWITCH.ClientSecret != nil {
f.Games = true
}
if hasPermission(userPerms, PERM_REQUEST_CONTENT) {
if len(Config.SONARR) > 0 {
f.Sonarr = true
}
if len(Config.RADARR) > 0 {
f.Radarr = true
}
}
return f
}
func saveTwitchConfig(c game.IGDB) error {
// If existing client id and secret are same.. just return here
if (Config.TWITCH.ClientID != nil && c.ClientID != nil && Config.TWITCH.ClientSecret != nil && c.ClientSecret != nil) &&
*Config.TWITCH.ClientID == *c.ClientID && *Config.TWITCH.ClientSecret == *c.ClientSecret {
slog.Info("saveTwitchConfig: New ClientID and ClientSecret match old ClientID and ClientSecret.. ignoring request to update.")
return nil
}
// Update our config
Config.TWITCH.ClientID = c.ClientID
Config.TWITCH.ClientSecret = c.ClientSecret
Config.TWITCH.AccessToken = ""
Config.TWITCH.AccessTokenExpires = time.Time{}
// Try to init again
err := Config.TWITCH.Init()
if err != nil {
slog.Error("saveTwitchConfig failed to initialize TWITCH", "error", err)
return errors.New("initialization with credentials failed")
}
err = writeConfig()
if err != nil {
slog.Error("saveTwitchConfig failed to write config", "error", err)
return errors.New("failed to save config")
}
return nil
}
type ServerStats struct {
Users int64 `json:"users"`
PrivateUsers int64 `json:"privateUsers"`
WatchedMovies int64 `json:"watchedMovies"`
WatchedShows int64 `json:"watchedShows"`
WatchedSeasons int64 `json:"watchedSeasons"`
MostWatchedMovie Content `json:"mostWatchedMovie"`
MostWatchedShow Content `json:"mostWatchedShow"`
Activities int64 `json:"activities"`
}
// Collect and return server stats
// I cant sql so this the best yall gettin
func getServerStats(db *gorm.DB) ServerStats {
stats := ServerStats{}
resp := db.Model(&User{}).Count(&stats.Users).Where("private = 1").Count(&stats.PrivateUsers)
if resp.Error != nil {
slog.Error("getServerStats - Users query failed", "error", resp.Error)
}
resp = db.Model(&WatchedSeason{}).Count(&stats.WatchedSeasons)
if resp.Error != nil {
slog.Error("getServerStats - WatchedSeasons query failed", "error", resp.Error)
}
resp = db.Model(&Activity{}).Count(&stats.Activities)
if resp.Error != nil {
slog.Error("getServerStats - Activities query failed", "error", resp.Error)
}
resp = db.Joins("JOIN contents ON contents.id = watcheds.content_id AND contents.type = ?", "tv").Find(&Watched{}).Count(&stats.WatchedShows)
if resp.Error != nil {
slog.Error("getServerStats - WatchedShows query failed", "error", resp.Error)
}
resp = db.Joins("JOIN contents ON contents.id = watcheds.content_id AND contents.type = ?", "movie").Find(&Watched{}).Count(&stats.WatchedMovies)
if resp.Error != nil {
slog.Error("getServerStats - WatchedMovies query failed", "error", resp.Error)
}
var w Watched
resp = db.Model(&Watched{}).Select("content_id, COUNT(*) AS mag").Joins("JOIN contents ON contents.type = ? AND contents.id = watcheds.content_id", "tv").Group("content_id").Order("mag DESC").Preload("Content").First(&w)
if resp.Error != nil {
slog.Error("getServerStats - MostWatchedShow query failed", "error", resp.Error)
} else {
stats.MostWatchedShow = *w.Content
}
resp = db.Model(&Watched{}).Select("content_id, COUNT(*) AS mag").Joins("JOIN contents ON contents.type = ? AND contents.id = watcheds.content_id", "movie").Group("content_id").Order("mag DESC").Preload("Content").First(&w)
if resp.Error != nil {
slog.Error("getServerStats - MostWatchedMovie query failed", "error", resp.Error)
} else {
stats.MostWatchedMovie = *w.Content
}
return stats
return cfg, nil
}
-485
View File
@@ -1,485 +0,0 @@
package main
import (
"encoding/json"
"errors"
"log/slog"
"path"
"strconv"
"time"
"github.com/gin-contrib/cache/persistence"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
type ContentType string
const (
MOVIE ContentType = "movie"
SHOW ContentType = "tv"
// Show episode
SHOW_EPISODE ContentType = "tv_episode"
)
var ContentStore = persistence.NewInMemoryStore(time.Hour * 24)
// For storing cached content, so we can serve the basic local data for watched list to work
type Content struct {
ID int `json:"id" gorm:"primaryKey;autoIncrement"`
TmdbID int `json:"tmdbId" gorm:"uniqueIndex:contentidtotypeidx;not null"`
Title string `json:"title"`
PosterPath string `json:"poster_path"`
Overview string `json:"overview"`
Type ContentType `json:"type" gorm:"uniqueIndex:contentidtotypeidx;not null"`
ReleaseDate *time.Time `json:"release_date,omitempty"`
Popularity float32 `json:"popularity"`
VoteAverage float32 `json:"vote_average"`
VoteCount uint32 `json:"vote_count"`
ImdbID string `json:"imdb_id"`
Status string `json:"status"`
Budget uint32 `json:"budget"`
Revenue uint32 `json:"revenue"`
Runtime uint32 `json:"runtime"`
NumberOfEpisodes uint32 `json:"numberOfEpisodes"`
NumberOfSeasons uint32 `json:"numberOfSeasons"`
}
// onlyUpdate - If we should only update existing row if exists, or false to create/update if not exist.
func saveContent(db *gorm.DB, c *Content, onlyUpdate bool) error {
slog.Info("Saving content to db", "id", c.TmdbID, "title", c.Title)
if c.TmdbID == 0 || c.Title == "" || c.Type == "" {
slog.Error("saveContent: content missing id, title or type!", "id", c.TmdbID, "title", c.Title, "type", c.Type)
return errors.New("content missing id or title")
}
var res *gorm.DB
if onlyUpdate {
// We only want to update an existing row, if it exists.
res = db.Model(&Content{}).Where("type = ? AND tmdb_id = ?", c.Type, c.TmdbID).Updates(c)
if res.Error != nil {
slog.Error("saveContent: Error updating content in database", "error", res.Error.Error())
return errors.New("failed to update cached content in database")
}
} else {
// On conflict, update existing row with details incase any were updated/missing.
res = db.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "tmdb_id"}, {Name: "type"}},
DoUpdates: clause.AssignmentColumns([]string{
"title",
"poster_path",
"overview",
"release_date",
"popularity",
"vote_average",
"vote_count",
"imdb_id",
"status",
"budget",
"revenue",
"runtime",
"number_of_episodes",
"number_of_seasons",
}),
}).Create(&c)
if res.Error != nil {
// Error if anything but unique contraint error
if res.Error != gorm.ErrDuplicatedKey {
slog.Error("saveContent: Error creating content in database", "error", res.Error.Error())
return errors.New("failed to cache content in database")
}
}
}
// If row created, download the image
if res.RowsAffected > 0 {
slog.Debug("saveContent: Downloading poster.")
err := download("https://image.tmdb.org/t/p/w500"+c.PosterPath, path.Join(DataPath, "img", c.PosterPath), false)
if err != nil {
slog.Error("saveContent: Failed to download content image!", "error", err.Error())
}
}
return nil
}
func cacheContentTv(db *gorm.DB, content TMDBShowDetails, onlyUpdate bool) (Content, error) {
slog.Debug("cacheContentTv", "content", content)
var (
releaseDate time.Time
runtime uint32
)
var dateFormat = "2006-01-02"
releaseDate, err := time.Parse(dateFormat, content.FirstAirDate)
if err != nil {
slog.Error("Failed to parse tv release date", "error", err)
}
if len(content.EpisodeRunTime) > 0 {
runtime = uint32(content.EpisodeRunTime[0])
}
c := Content{
TmdbID: content.ID,
Title: content.Name,
Overview: content.Overview,
PosterPath: content.PosterPath,
Type: SHOW,
ReleaseDate: &releaseDate,
Popularity: content.Popularity,
VoteAverage: content.VoteAverage,
VoteCount: content.VoteCount,
Status: content.Status,
Runtime: runtime,
NumberOfEpisodes: content.NumberOfEpisodes,
NumberOfSeasons: content.NumberOfSeasons,
}
err = saveContent(db, &c, onlyUpdate)
if err != nil {
slog.Error("cacheContentTv: Failed to save content!", "error", err)
return Content{}, errors.New("failed to save content")
}
return c, nil
}
func cacheContentMovie(db *gorm.DB, content TMDBMovieDetails, onlyUpdate bool) (Content, error) {
var (
releaseDate time.Time
)
var dateFormat = "2006-01-02"
// Get details from movie/show response and fill out needed vars
releaseDate, err := time.Parse(dateFormat, content.ReleaseDate)
if err != nil {
slog.Error("Failed to parse movie release date", "error", err)
}
c := Content{
TmdbID: content.ID,
Title: content.Title,
Overview: content.Overview,
PosterPath: content.PosterPath,
Type: MOVIE,
ReleaseDate: &releaseDate,
Popularity: content.Popularity,
VoteAverage: content.VoteAverage,
VoteCount: content.VoteCount,
ImdbID: content.ImdbID,
Status: content.Status,
Budget: content.Budget,
Revenue: content.Revenue,
Runtime: content.Runtime,
}
err = saveContent(db, &c, onlyUpdate)
if err != nil {
slog.Error("cacheContentMovie: Failed to save content!", "error", err)
return Content{}, errors.New("failed to save content")
}
return c, nil
}
// Get content from our cache, or cache it if it doesn't exist.
func getOrCacheContent(db *gorm.DB, contentType ContentType, tmdbId int) (Content, error) {
var content Content
// Look in db for content.
db.Where("type = ? AND tmdb_id = ?", contentType, tmdbId).Find(&content)
// Create content if not found from our db.
if content == (Content{}) {
slog.Debug("Content not in db, fetching...", "type", contentType, "tmdbId", tmdbId)
resp, err := tmdbAPIRequest("/"+string(contentType)+"/"+strconv.Itoa(tmdbId), map[string]string{})
if err != nil {
slog.Error("getOrCacheContent: content tmdb api request failed", "error", err)
return Content{}, errors.New("failed to find requested media")
}
if contentType == "movie" {
c := new(TMDBMovieDetails)
err := json.Unmarshal([]byte(resp), &c)
if err != nil {
slog.Error("Failed to unmarshal movie details", "error", err)
return Content{}, errors.New("failed to process movie details response")
}
content, err = cacheContentMovie(db, *c, false)
if err != nil {
slog.Error("getOrCacheContent: failed to cache movie content", "type", contentType, "content_id", tmdbId, "err", err)
return Content{}, errors.New("failed to cache content")
}
} else {
c := new(TMDBShowDetails)
err := json.Unmarshal(resp, &c)
if err != nil {
slog.Error("Failed to unmarshal tv details", "error", err)
return Content{}, errors.New("failed to process tv details response")
}
content, err = cacheContentTv(db, *c, false)
if err != nil {
slog.Error("getOrCacheContent: failed to cache tv content", "type", contentType, "content_id", tmdbId, "err", err)
return Content{}, errors.New("failed to cache content")
}
}
}
return content, nil
}
// Getting only region needed from api is not a feature yet
// https://trello.com/c/75tR4cpF/106-add-watch-provider-region-filtering
// When it is, this can be removed for that instead.
func transformProviders(c *interface{}, country string) {
slog.Debug("transformProviders called", "country", country)
if cmap, ok := (*c).(map[string]interface{}); ok {
if rmap, ok := cmap["results"].(map[string]interface{}); ok {
if val, ok := rmap[country]; ok {
slog.Debug("transformProviders: Found country.. overwriting whole object", "new_obj", val)
if rvmap, ok := val.(map[string]interface{}); ok {
rvmap["country"] = country
}
*c = val
} else {
slog.Warn("transformProviders: Couldn't find country..", "country", country)
}
} else {
slog.Warn("transformProviders: Couldn't find results property..")
}
} else {
slog.Error("transformProviders: Assertion failed")
}
}
func searchContent(query string, pageNum int) (TMDBSearchMultiResponse, error) {
resp := new(TMDBSearchMultiResponse)
if pageNum == 0 {
pageNum = 1
}
err := tmdbRequest("/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 TMDBSearchMultiResponse{}, errors.New("failed to complete multi search request")
}
return *resp, nil
}
func searchMovies(query string, pageNum int) (TMDBSearchMoviesResponse, error) {
resp := new(TMDBSearchMoviesResponse)
if pageNum == 0 {
pageNum = 1
}
err := tmdbRequest("/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 TMDBSearchMoviesResponse{}, errors.New("failed to complete movie search request")
}
for i := range resp.Results {
resp.Results[i].MediaType = "movie"
}
return *resp, nil
}
func searchTv(query string, pageNum int) (TMDBSearchShowsResponse, error) {
resp := new(TMDBSearchShowsResponse)
if pageNum == 0 {
pageNum = 1
}
err := tmdbRequest("/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 TMDBSearchShowsResponse{}, errors.New("failed to complete tv search request")
}
for i := range resp.Results {
resp.Results[i].MediaType = "tv"
}
return *resp, nil
}
func searchPeople(query string, pageNum int) (TMDBSearchPeopleResponse, error) {
resp := new(TMDBSearchPeopleResponse)
if pageNum == 0 {
pageNum = 1
}
err := tmdbRequest("/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 TMDBSearchPeopleResponse{}, errors.New("failed to complete people search request")
}
for i := range resp.Results {
resp.Results[i].MediaType = "person"
}
return *resp, nil
}
// Search for content by an external id (imdb, etc).
// Defaults to imdb if no source if provided (probably most common).
func searchByExternalId(id string, source string) (TMDBSearchMultiResponse, error) {
resp := new(TMDBFindByExternalIdResponse)
if source == "" {
source = "imdb"
}
err := tmdbRequest("/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 TMDBSearchMultiResponse{}, errors.New("failed to complete find/external_id request")
}
comb := []TMDBSearchMultiResults{}
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 TMDBSearchMultiResponse{TMDBSearchResponse: TMDBSearchResponse[TMDBSearchMultiResults]{
Results: comb,
TotalResults: len(comb),
// Just providing these so we don't break frontend pagination logic.
TotalPages: 1,
Page: 1,
}}, nil
}
func movieDetails(db *gorm.DB, id string, country string, rParams map[string]string) (TMDBMovieDetails, error) {
resp := new(TMDBMovieDetails)
err := tmdbRequest("/movie/"+id, rParams, &resp)
if err != nil {
slog.Error("Failed to complete movie details request!", "error", err.Error())
return TMDBMovieDetails{}, errors.New("failed to complete movie details request")
}
transformProviders(&resp.WatchProviders, country)
go cacheContentMovie(db, *resp, true)
return *resp, nil
}
func movieCredits(id string) (TMDBContentCredits, error) {
resp := new(TMDBContentCredits)
err := tmdbRequest("/movie/"+id+"/credits", map[string]string{}, &resp)
if err != nil {
slog.Error("Failed to complete movie cast request!", "error", err.Error())
return TMDBContentCredits{}, errors.New("failed to complete movie cast request")
}
return *resp, nil
}
func tvDetails(db *gorm.DB, id string, country string, rParams map[string]string) (TMDBShowDetails, error) {
resp := new(TMDBShowDetails)
err := tmdbRequest("/tv/"+id, rParams, &resp)
if err != nil {
slog.Error("Failed to complete tv details request!", "error", err.Error())
return TMDBShowDetails{}, errors.New("failed to complete tv details request")
}
transformProviders(&resp.WatchProviders, country)
go cacheContentTv(db, *resp, true)
return *resp, nil
}
func tvCredits(id string) (TMDBContentCredits, error) {
resp := new(TMDBContentCredits)
err := tmdbRequest("/tv/"+id+"/credits", map[string]string{}, &resp)
if err != nil {
slog.Error("Failed to complete tv cast request!", "error", err.Error())
return 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 seasonDetails(tvId string, seasonNumber string) (TMDBSeasonDetails, error) {
var cacheKey = "contentstore-seasondetails-" + tvId + "-" + seasonNumber
resp := new(TMDBSeasonDetails)
if err := ContentStore.Get(cacheKey, &resp); err != nil {
if err != persistence.ErrCacheMiss {
slog.Error("seasonDetails: Cache failed for some reason", "error", err)
}
} else {
slog.Debug("seasonDetails: Returning cache.")
return *resp, nil
}
err := tmdbRequest("/tv/"+tvId+"/season/"+seasonNumber, map[string]string{}, &resp)
if err != nil {
slog.Error("seasonDetails: Failed to complete season details request!", "error", err.Error())
return TMDBSeasonDetails{}, errors.New("failed to complete season details request")
}
if err := ContentStore.Set(cacheKey, resp, time.Hour*24); err != nil {
slog.Error("seasonDetails: Failed to set cache!", "error", err)
}
return *resp, nil
}
func personDetails(id string) (TMDBPersonDetails, error) {
resp := new(TMDBPersonDetails)
err := tmdbRequest("/person/"+id, map[string]string{}, &resp)
if err != nil {
slog.Error("Failed to complete person details request!", "error", err.Error())
return TMDBPersonDetails{}, errors.New("failed to complete person details request")
}
return *resp, nil
}
func personCredits(id string) (TMDBPersonCombinedCredits, error) {
resp := new(TMDBPersonCombinedCredits)
err := tmdbRequest("/person/"+id+"/combined_credits", map[string]string{}, &resp)
if err != nil {
slog.Error("Failed to complete person details request!", "error", err.Error())
return TMDBPersonCombinedCredits{}, errors.New("failed to complete person details request")
}
return *resp, nil
}
func discoverMovies() (TMDBDiscoverMovies, error) {
resp := new(TMDBDiscoverMovies)
err := tmdbRequest("/discover/movie", map[string]string{"page": "1"}, &resp)
if err != nil {
slog.Error("Failed to complete discover movies request!", "error", err.Error())
return TMDBDiscoverMovies{}, errors.New("failed to complete discover movies request")
}
return *resp, nil
}
func discoverTv() (TMDBDiscoverShows, error) {
resp := new(TMDBDiscoverShows)
err := tmdbRequest("/discover/tv", map[string]string{"page": "1"}, &resp)
if err != nil {
slog.Error("Failed to complete discover tv request!", "error", err.Error())
return TMDBDiscoverShows{}, errors.New("failed to complete discover tv request")
}
return *resp, nil
}
func allTrending() (TMDBTrendingAll, error) {
resp := new(TMDBTrendingAll)
err := tmdbRequest("/trending/all/day", map[string]string{}, &resp)
if err != nil {
slog.Error("Failed to complete all trending request!", "error", err.Error())
return TMDBTrendingAll{}, errors.New("failed to complete all trending request")
}
return *resp, nil
}
func upcomingMovies() (TMDBUpcomingMovies, error) {
resp := new(TMDBUpcomingMovies)
err := tmdbRequest("/movie/upcoming", map[string]string{"page": "1"}, &resp)
if err != nil {
slog.Error("Failed to complete upcoming movies request!", "error", err.Error())
return TMDBUpcomingMovies{}, errors.New("failed to complete upcoming movies request")
}
return *resp, nil
}
// Theres no upcoming endpoint for tv ;( - using discover with future dates
func upcomingTv() (TMDBUpcomingShows, error) {
resp := new(TMDBUpcomingShows)
dFmt := "2006-01-02"
mind := time.Now().Format(dFmt)
maxd := time.Now().AddDate(0, 0, 15).Format(dFmt)
err := tmdbRequest("/discover/tv", map[string]string{"page": "1", "first_air_date.gte": mind, "first_air_date.lte": maxd, "sort_by": "popularity.desc", "with_type": "2|3"}, &resp)
if err != nil {
slog.Error("Failed to complete upcoming tv request!", "error", err.Error())
return TMDBUpcomingShows{}, errors.New("failed to complete upcoming tv request")
}
return *resp, nil
}
func regions() (TMDBRegions, error) {
resp := new(TMDBRegions)
err := tmdbRequest("/watch/providers/regions", map[string]string{}, &resp)
if err != nil {
slog.Error("Failed to complete regions request!", "error", err.Error())
return TMDBRegions{}, errors.New("failed to complete regions request")
}
return *resp, nil
}
+42
View File
@@ -0,0 +1,42 @@
package database
import (
"path"
"github.com/sbondCo/Watcharr/config"
"github.com/sbondCo/Watcharr/database/entity"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
// Create a new database connection.
func New() (*gorm.DB, error) {
// Open the database.
db, err := gorm.Open(
sqlite.Open(path.Join(config.DataPath, "watcharr.db")),
&gorm.Config{TranslateError: true},
)
if err != nil {
return nil, err
}
// Perform auto migration.
err = db.AutoMigrate(
&entity.User{},
&entity.UserServices{},
&entity.Content{},
&entity.Watched{},
&entity.WatchedSeason{},
&entity.WatchedEpisode{},
&entity.Activity{},
&entity.Token{},
&entity.Follow{},
&entity.Image{},
&entity.Game{},
&entity.ArrRequest{},
&entity.Tag{},
)
if err != nil {
return nil, err
}
return db, nil
}
+14
View File
@@ -0,0 +1,14 @@
package dbmodel
import (
"time"
"gorm.io/gorm"
)
type GormModel struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
}
+57
View File
@@ -0,0 +1,57 @@
package entity
import (
"time"
"github.com/sbondCo/Watcharr/database/dbmodel"
)
type ActivityType string
// _AUTO activities are for when logic updates something for the user (automations basically).
var (
ADDED_WATCHED ActivityType = "ADDED_WATCHED"
REMOVED_WATCHED ActivityType = "REMOVED_WATCHED"
RATING_CHANGED ActivityType = "RATING_CHANGED"
STATUS_CHANGED ActivityType = "STATUS_CHANGED"
STATUS_CHANGED_AUTO ActivityType = "STATUS_CHANGED_AUTO"
THOUGHTS_CHANGED ActivityType = "THOUGHTS_CHANGED"
THOUGHTS_REMOVED ActivityType = "THOUGHTS_REMOVED"
IMPORTED_WATCHED ActivityType = "IMPORTED_WATCHED"
IMPORTED_WATCHED_JF ActivityType = "IMPORTED_WATCHED_JF"
IMPORTED_WATCHED_PLEX ActivityType = "IMPORTED_WATCHED_PLEX"
IMPORTED_RATING ActivityType = "IMPORTED_RATING" // Imported rating, but with no rating acts as original import of content to old platform (where they are importing from) activity
IMPORTED_ADDED_WATCHED ActivityType = "IMPORTED_ADDED_WATCHED" // Imported watched date, so we can save the original watch dates of content from users old platform (where they are importing from).
IMPORTED_ADDED_WATCHED_JF ActivityType = "IMPORTED_ADDED_WATCHED_JF"
IMPORTED_ADDED_WATCHED_PLEX ActivityType = "IMPORTED_ADDED_WATCHED_PLEX"
SEASON_ADDED ActivityType = "SEASON_ADDED"
SEASON_ADDED_AUTO ActivityType = "SEASON_ADDED_AUTO"
SEASON_ADDED_JF ActivityType = "SEASON_ADDED_JF"
SEASON_ADDED_PLEX ActivityType = "SEASON_ADDED_PLEX"
SEASON_REMOVED ActivityType = "SEASON_REMOVED"
SEASON_RATING_CHANGED ActivityType = "SEASON_RATING_CHANGED"
SEASON_STATUS_CHANGED ActivityType = "SEASON_STATUS_CHANGED"
SEASON_STATUS_CHANGED_AUTO ActivityType = "SEASON_STATUS_CHANGED_AUTO"
EPISODE_ADDED ActivityType = "EPISODE_ADDED"
EPISODE_ADDED_JF ActivityType = "EPISODE_ADDED_JF"
EPISODE_ADDED_PLEX ActivityType = "EPISODE_ADDED_PLEX"
EPISODE_REMOVED ActivityType = "EPISODE_REMOVED"
EPISODE_RATING_CHANGED ActivityType = "EPISODE_RATING_CHANGED"
EPISODE_STATUS_CHANGED ActivityType = "EPISODE_STATUS_CHANGED"
)
type Activity struct {
dbmodel.GormModel
// ID of user this activity is linked to, so it can be easily
// secured (users can only view their own activities).
UserID uint `json:"-" gorm:"not null"`
// ID of watched list item this activity is linked to.
WatchedID uint `json:"watchedId" gorm:"not null"`
// Type of activity.
Type ActivityType `json:"type" gorm:"not null"`
// Holds custom data (ex, if rating changed, this can
// hold new rating - if status changed, this will hold that).
Data string `json:"data" gorm:"not null"`
// Custom date for the activity, that the user can define.
CustomDate *time.Time `json:"customDate,omitempty"`
}
+40
View File
@@ -0,0 +1,40 @@
package entity
import "time"
type ArrRequestStatus string
const (
// Pending approval from an admin.
ARR_REQUEST_PENDING ArrRequestStatus = "PENDING"
// Request has been approved and should be added to sonarr/radarr.
ARR_REQUEST_APPROVED ArrRequestStatus = "APPROVED"
ARR_REQUEST_AUTO_APPROVED ArrRequestStatus = "AUTO_APPROVED"
// Request has been denied, not adding content.
ARR_REQUEST_DENIED ArrRequestStatus = "DENIED"
// Content was found on sonarr/radarr already, nothing needs to be done.
ARR_REQUEST_FOUND ArrRequestStatus = "FOUND"
)
type ArrRequest struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
UserID uint `json:"-" gorm:"not null"`
User User `json:"-"`
// Username of `User`.
// We don't want to send back the entire user object, just their name.
// Not stored in DB, only used for our response from api.
Username string `json:"username" gorm:"-"`
ContentID *int `json:"-" gorm:"uniqueIndex:sn_to_cid;not null"`
Content *Content `json:"content,omitempty"`
// Server names are used as an identifier
ServerName string `json:"serverName" gorm:"uniqueIndex:sn_to_cid;not null"`
// Sonarr/Radarrs seriesId/movieId
ArrID int `json:"arrId"`
// Tracked request status
Status ArrRequestStatus `json:"status" gorm:"default:PENDING"`
// Full request made by user (arr.SonarrRequest / arr.RadarrRequest)
// so we know how to fulfil the request if approved.
RequestJson string `json:"requestJson"`
}
+77
View File
@@ -0,0 +1,77 @@
package entity
import (
"time"
"github.com/golang-jwt/jwt/v5"
)
type UserType uint8
var (
WATCHARR_USER UserType = 0
JELLYFIN_USER UserType = 1
PLEX_USER UserType = 2
// Registered via trusted header auth
PROXY_USER UserType = 3
)
// User Perms
// iota auto increments for us so when adding new
// perms, add to bottom as to not change other perm
// values.
const (
PERM_NONE int = 1 << iota
PERM_ADMIN
PERM_REQUEST_CONTENT
PERM_REQUEST_CONTENT_AUTO_APPROVE
)
// Holds third party service auth tokens for users.
// Each service may use the fields in their own way.
// Unique index applied between service name and clientID
// to ensure no duplicates (no need to apply it against
// user_id, no accounts should share an integration).
//
// Plex:
// - AuthToken : Used for requests against plex.tv
// - AuthToken2 : Used for requests against home plex server.
type UserServices struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
// Service/integration name
Name string `gorm:"uniqueIndex:svc_name_to_cltid;not null;" json:"-"`
// The users id on the third party service
ClientID string `gorm:"uniqueIndex:svc_name_to_cltid;not null;" json:"-"`
AuthToken string `gorm:"not null;" json:"-"`
// Second auth token, generic name so future services can use it without extra confusion.
// Ex: We require a second auth token for use with our local server for Plex.
AuthToken2 string `json:"-"`
UserID uint `gorm:"not null;" json:"-"`
}
type ArgonParams struct {
Memory uint32
Iterations uint32
Parallelism uint8
SaltLength uint32
KeyLength uint32
}
func GetPassArgonParams() *ArgonParams {
return &ArgonParams{
Memory: 64 * 1024,
Iterations: 3,
Parallelism: 2,
SaltLength: 16,
KeyLength: 32,
}
}
type TokenClaims struct {
UserID uint `json:"userId"`
Username string `json:"username"`
Type UserType `json:"type"`
jwt.RegisteredClaims
}
+52
View File
@@ -0,0 +1,52 @@
package entity
import (
"time"
"github.com/sbondCo/Watcharr/util"
)
type ContentType string
const (
MOVIE ContentType = "movie"
SHOW ContentType = "tv"
// Show episode
SHOW_EPISODE ContentType = "tv_episode"
)
// For storing cached content, so we can serve the basic local data for watched list to work
type Content struct {
ID int `json:"id" gorm:"primaryKey;autoIncrement"`
TmdbID int `json:"tmdbId" gorm:"uniqueIndex:contentidtotypeidx;not null"`
Title string `json:"title"`
PosterPath string `json:"poster_path"`
Overview string `json:"overview"`
Type ContentType `json:"type" gorm:"uniqueIndex:contentidtotypeidx;not null"`
ReleaseDate *time.Time `json:"release_date,omitempty"`
Popularity float32 `json:"popularity"`
VoteAverage float32 `json:"vote_average"`
VoteCount uint32 `json:"vote_count"`
ImdbID string `json:"imdb_id"`
Status string `json:"status"`
Budget uint32 `json:"budget"`
Revenue uint32 `json:"revenue"`
Runtime uint32 `json:"runtime"`
NumberOfEpisodes uint32 `json:"numberOfEpisodes"`
NumberOfSeasons uint32 `json:"numberOfSeasons"`
}
// NOTE: Can return empty string, so use only when we know that a valid option
// will be returned or we are okay with that.
func (c *Content) GetTypeSupportedMedia() util.SupportedMedia {
if c == nil {
return ""
}
switch c.Type {
case MOVIE:
return util.SupportedMediaMovie
case SHOW:
return util.SupportedMediaShow
}
return ""
}
+13
View File
@@ -0,0 +1,13 @@
package entity
import "time"
// Database struct, only internal.
type Follow struct {
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"-"`
UserID uint `gorm:"primaryKey:usr_id_to_followed_id;not null;check:user_id != followed_user_id" json:"-"`
User User `json:"-"`
FollowedUserID uint `gorm:"primaryKey:usr_id_to_followed_id;not null" json:"-"`
FollowedUser User `json:"-"`
}
+27
View File
@@ -0,0 +1,27 @@
package entity
import "time"
// For storing cached games, so we can serve the basic local data for watched list to work
type Game struct {
ID int `json:"id" gorm:"primaryKey;autoIncrement"`
UpdatedAt time.Time `json:"updatedAt"`
IgdbID int `json:"igdbId" gorm:"uniqueIndex;not null"`
Name string `json:"name"`
CoverID string `json:"coverId"`
Summary string `json:"summary"`
Storyline string `json:"storyline"`
// First release date
ReleaseDate *time.Time `json:"releaseDate,omitempty"`
Rating float64 `json:"rating"`
RatingCount int `json:"ratingCount"`
Status int `json:"status"`
Category int `json:"category"`
// Arrays turned to strings that may be useful
GameModes string `json:"gameModes"`
Genres string `json:"genres"`
Platforms string `json:"platforms"`
// Id to poster image row (cached game cover)
PosterID *uint `json:"-"`
Poster *Image `json:"poster,omitempty"`
}
+15
View File
@@ -0,0 +1,15 @@
package entity
import "time"
// For user uploaded images
type Image struct {
ID uint `gorm:"primarykey" json:"-"`
CreatedAt time.Time `json:"createdAt"`
Hash string `gorm:"uniqueIndex;not null" json:"-"`
BlurHash string `json:"blurHash"`
// Path constructable from hash alone, but I can't decide
// if I should have this or not so I figure it's easier
// to remove it later than to add it later....... -_-
Path string `gorm:"not null" json:"path"`
}
+17
View File
@@ -0,0 +1,17 @@
package entity
import "github.com/sbondCo/Watcharr/database/dbmodel"
type Tag struct {
dbmodel.GormModel
// ID of user that own this tag.
UserID uint `json:"-" gorm:"not null"`
// Name of the tag.
Name string `json:"name" gorm:"not null"`
// Hex of text color.
Color string `json:"color"`
// Hex of background color.
BgColor string `json:"bgColor"`
// All watched items.
Watched []Watched `json:"watched,omitempty" gorm:"many2many:watched_tags;"`
}
+17
View File
@@ -0,0 +1,17 @@
package entity
import "time"
type TokenType string
var (
TOKENTYPE_ADMIN TokenType = "ADMIN"
)
type Token struct {
ID uint `gorm:"primarykey"`
CreatedAt time.Time `json:"createdAt"`
Value string `gorm:"not null"`
Type TokenType `gorm:"not null"`
UserID uint `gorm:"not null"`
}
+85
View File
@@ -0,0 +1,85 @@
package entity
import (
"github.com/sbondCo/Watcharr/database/dbmodel"
)
// uniqueIndex applied between Username and UserType, so same usernames can exist, but only with different types.
// This is incase different users with same name from different services try to signup.
type User struct {
dbmodel.GormModel
Username string `gorm:"uniqueIndex:usr_name_to_type;not null" json:"username" binding:"required"`
Password string `gorm:"not null" json:"password" binding:"required"`
AvatarID uint `json:"-"`
Avatar Image `json:"avatar"`
Bio string `json:"bio"`
// The type of user/which auth service they originate from.
// Empty if from Watcharr, or the name of the service (eg. jellyfin)
Type UserType `gorm:"uniqueIndex:usr_name_to_type;not null;default:0" json:"type"`
// ID of user from the third party service, this will be used purely for lookup of user at signin.
ThirdPartyID string `json:"-"`
// Auth token from third party (jellyfin)
ThirdPartyAuth string `json:"-"`
// Users third party integrations (minus jellyfin for now)
UserServices []UserServices `json:"-"`
Watched []Watched
// All Tags
Tags []Tag `json:"-"`
// Users permissions
Permissions int `gorm:"default:1" json:"-"`
// All user settings cols, in another struct for reusability
UserSettings
}
func (u *User) GetSafe() PublicUser {
return PublicUser{
ID: u.ID,
Username: u.Username,
Avatar: u.Avatar,
Bio: u.Bio,
}
}
// This struct uses pointer to the values, so in update user settings,
// we can tell which setting is being updated (if not nil..).
type UserSettings struct {
// Is profile private
Private *bool `gorm:"default:false" json:"private"`
// Are watched list content thoughts public (profile must also be public is false)
PrivateThoughts *bool `gorm:"default:false" json:"privateThoughts"`
// If ui 'spoilers' should be shown
HideSpoilers *bool `gorm:"default:false" json:"hideSpoilers"`
// If user wants previously watched items to show in 'Finished' filter,
// even if the watched item state has since been changed.
// Also if user wants to show in watched stats.
IncludePreviouslyWatched *bool `gorm:"default:false" json:"includePreviouslyWatched"`
// User's country to get correct content streaming providers.
// TODO Enforce iso_3166_1 validity (same as tmdb)
Country *string `gorm:"default:'US'" json:"country"`
// Does the user want show, season and episode automations enabled.
AutomateShowStatuses *bool `gorm:"default:true" json:"automateShowStatuses"`
// Rating system user wants to use (frontend only).
// RatingSystem enum in frontend maxes out at 3, so just max=3 on this and we should be gut.
RatingSystem *int `json:"ratingSystem" binding:"omitempty,max=3"`
// Rating step for supported rating systems (frontend only, enum goes up to 2).
RatingStep *int `json:"ratingStep" binding:"omitempty,max=2"`
}
// Public user details for search results
type PublicUser struct {
ID uint `json:"id"`
Username string `json:"username"`
AvatarID uint `json:"-"`
Avatar Image `json:"avatar,omitzero"`
Bio string `json:"bio,omitempty"`
}
// Private user details, for returning users details to themselves
type PrivateUser struct {
Username string `json:"username"`
Type UserType `json:"type"`
Permissions int `json:"permissions"`
AvatarID uint `json:"-"`
Avatar Image `json:"avatar"`
Bio string `json:"bio"`
}
+36
View File
@@ -0,0 +1,36 @@
package entity
import "github.com/sbondCo/Watcharr/database/dbmodel"
type WatchedStatus string
const (
FINISHED WatchedStatus = "FINISHED"
WATCHING WatchedStatus = "WATCHING"
PLANNED WatchedStatus = "PLANNED"
HOLD WatchedStatus = "HOLD"
DROPPED WatchedStatus = "DROPPED"
)
type Watched struct {
dbmodel.GormModel
Status WatchedStatus `json:"status"`
// float so we can support decimal ratings.
// Ratings should still always be saved as out of 10.0,
// so they can be viewed with any ratings setting in the client.
Rating float64 `json:"rating" gorm:"type:numeric(2,1)"`
Thoughts string `json:"thoughts"`
Pinned bool `json:"pinned" gorm:"default:false;not null"`
UserID uint `json:"-" gorm:"uniqueIndex:usernctnidx;uniqueIndex:userngamidx"`
ContentID *int `json:"-" gorm:"uniqueIndex:usernctnidx"`
Content *Content `json:"content,omitempty"`
GameID *int `json:"-" gorm:"uniqueIndex:userngamidx"`
Game *Game `json:"game,omitempty"`
Activity []Activity `json:"activity"`
WatchedSeasons []WatchedSeason `json:"watchedSeasons,omitempty"` // For shows
WatchedEpisodes []WatchedEpisode `json:"watchedEpisodes,omitempty"` // For shows
Tags []Tag `json:"tags,omitempty" gorm:"many2many:watched_tags;"`
// The last season that was viewed by the user for this watched entry.
// Only applies to tv shows of course.
LastViewedSeason *int `json:"lastViewedSeason,omitempty"`
}
+19
View File
@@ -0,0 +1,19 @@
package entity
import "github.com/sbondCo/Watcharr/database/dbmodel"
// UniqueIndex applied between WatchedID, SeasonNum and EpisodeNum to avoid duplicates incase logic fails.
//
// Episodes on tmdb are only queried by season number + episode number, not possible via episode id,
// 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
UserID uint `json:"-" gorm:"not null"`
User User `json:"-"`
WatchedID uint `json:"-" gorm:"uniqueIndex:we_watched_to_ens;not null"`
SeasonNumber int `json:"seasonNumber" gorm:"uniqueIndex:we_watched_to_ens;not null"`
EpisodeNumber int `json:"episodeNumber" gorm:"uniqueIndex:we_watched_to_ens;not null"`
Status WatchedStatus `json:"status"`
Rating int8 `json:"rating"`
}
+14
View File
@@ -0,0 +1,14 @@
package entity
import "github.com/sbondCo/Watcharr/database/dbmodel"
// UniqueIndex applied between WatchedID and SeasonNumber to avoid duplicates incase logic fails.
type WatchedSeason struct {
dbmodel.GormModel
UserID uint `json:"-" gorm:"not null"`
User User `json:"-"`
WatchedID uint `json:"-" gorm:"uniqueIndex:ws_watched_to_season_num;not null"`
SeasonNumber int `json:"seasonNumber" gorm:"uniqueIndex:ws_watched_to_season_num;not null"`
Status WatchedStatus `json:"status"`
Rating int8 `json:"rating"`
}
+24
View File
@@ -0,0 +1,24 @@
package domain
import (
"time"
"github.com/sbondCo/Watcharr/database/entity"
)
type (
ActivityAddRequest struct {
WatchedID uint `json:"watchedId" binding:"required"`
Type entity.ActivityType `json:"type" binding:"required"`
Data string `json:"data" binding:"required"`
CustomDate *time.Time `json:"customDate,omitempty"`
}
ActivityUpdateRequest struct {
CustomDate time.Time `json:"customDate" binding:"required"`
}
ActivityAddProvider interface {
AddActivity(userId uint, ar ActivityAddRequest) (entity.Activity, error)
}
)
+23
View File
@@ -0,0 +1,23 @@
package domain
import "time"
type ContentDetailsResponse struct {
Media
}
type PersonCreditsResponse struct {
Credits []Media `json:"credits,omitempty"`
}
type PersonDetailsResponse struct {
Name string `json:"name,omitempty"`
Birthday time.Time `json:"birthday,omitzero"`
Deathday time.Time `json:"deathday,omitzero"`
Age int `json:"age,omitempty"`
PlaceOfBirth string `json:"placeOfBirth,omitempty"`
KnownForDepartment string `json:"knownForDepartment,omitempty"`
Biography string `json:"biography,omitempty"`
ExtPosterPath string `json:"extPosterPath,omitempty"`
Homepage string `json:"homepage,omitempty"`
}
+57
View File
@@ -0,0 +1,57 @@
package domain
import (
"github.com/go-playground/validator/v10"
"github.com/sbondCo/Watcharr/util"
)
type DiscoverFilter string
const (
// Generic "What's Trending?" (all)
DiscoverFilterTrending DiscoverFilter = "trending"
// Popular stuff (basically trending but over months instead of just a day).
DiscoverFilterPopular DiscoverFilter = "popular"
// Upcoming content (all).
DiscoverFilterUpcoming DiscoverFilter = "upcoming"
// What's streaming (movies/tv).
DiscoverFilterStreaming DiscoverFilter = "streaming"
// What's in theatres (movies).
DiscoverFilterInTheatres DiscoverFilter = "intheatres"
)
type DiscoverRequest struct {
// The type of content we want to discover.
// Reusing the SearchType enum here, but if this needs to diverge,
// then make our own enum in this file.
Type SearchType `form:"type" binding:"validsearchtype"`
// A main filter.
// Not every `Type` of discover will support all Filters (service funcs
// will error individually based on what they support).
Filter DiscoverFilter `form:"filter" binding:"validdiscoverfilter"`
}
// Extra data that we provide to the Discover service func.
type DiscoverRequestMeta struct {
PageParams util.PaginationParams
Region string
}
type DiscoverResponse struct {
util.PaginationResponse[Media, util.None]
}
var ValidDiscoverFilter validator.Func = func(fl validator.FieldLevel) bool {
st, ok := fl.Field().Interface().(DiscoverFilter)
if ok {
switch st {
case DiscoverFilterTrending,
DiscoverFilterPopular,
DiscoverFilterUpcoming,
DiscoverFilterStreaming,
DiscoverFilterInTheatres:
return true
}
}
return false
}
+47
View File
@@ -0,0 +1,47 @@
package domain
import (
"time"
"github.com/sbondCo/Watcharr/database/entity"
)
type ImportResponseType string
var (
// Successful import
IMPORT_SUCCESS ImportResponseType = "IMPORT_SUCCESS"
// Import failed for reasons user cant fix
IMPORT_FAILED ImportResponseType = "IMPORT_FAILED"
// Import query returned multiple results, user must decide
IMPORT_MULTI ImportResponseType = "IMPORT_MULTI"
// Import query returned zero results, user must provide more info
IMPORT_NOTFOUND ImportResponseType = "IMPORT_NOTFOUND"
// Item already exists so couldn't import (unique constraint hit when adding)
IMPORT_EXISTS ImportResponseType = "IMPORT_EXISTS"
)
type ImportRequest struct {
Name string `json:"name"`
Year int `json:"year"`
TmdbID int `json:"tmdbId"`
Type entity.ContentType `json:"type"`
Rating float64 `json:"rating" binding:"max=10"`
RatingCustomDate *time.Time `json:"ratingCustomDate"`
Status entity.WatchedStatus `json:"status"`
Thoughts string `json:"thoughts"`
DatesWatched []time.Time `json:"datesWatched"`
Activity []entity.Activity `json:"activity"`
WatchedEpisodes []entity.WatchedEpisode `json:"watchedEpisodes"`
WatchedSeason []entity.WatchedSeason `json:"watchedSeasons"`
Tags []TagAddRequest `json:"tags"`
ImdbID string `json:"imdbId"`
}
type ImportResponse struct {
Type ImportResponseType `json:"type"`
Results []Media `json:"results,omitempty"`
Match Media `json:"match,omitzero"`
// On success this will be filled with the new watched entry
WatchedEntry entity.Watched `json:"watchedEntry,omitzero"`
}
+206
View File
@@ -0,0 +1,206 @@
// Types that we can use for all content types (movie, tv, game, everything).
// Data responses to the client can use these "uniform" types to make access
// easier.
package domain
import (
"log/slog"
"time"
"github.com/sbondCo/Watcharr/database/entity"
"github.com/sbondCo/Watcharr/util"
)
type MediaType string
const (
MediaTypeTMDBMovie MediaType = "tmdb_movie"
MediaTypeTMDBShow MediaType = "tmdb_tv"
MediaTypeTMDBPerson MediaType = "tmdb_person"
MediaTypeIGDBGame MediaType = "igdb_game"
)
type Media struct {
// The type of media.
Type MediaType `json:"type,omitempty"`
// The ids associated with this media.
IDs MediaIDs `json:"ids"`
// The name of the media.
Name string `json:"name,omitempty"`
// A description.
Summary string `json:"summary,omitempty"`
// The poster.
Poster *entity.Image `json:"poster,omitempty"`
// The external poster path.
ExtPosterPath string `json:"extPosterPath,omitempty"`
// The rating.
Rating uint `json:"rating,omitempty"`
// The amount of votes that made up the rating.
RatingCount uint `json:"ratingCount,omitempty"`
// Watched data.
Watched WatchedDto `json:"watched,omitzero"`
// Similar media.
Similar []Media `json:"similar,omitempty"`
// Release date / first air date.
ReleaseDate time.Time `json:"releaseDate,omitzero"`
// Videos (trailers, etc)
Videos []MediaVideo `json:"videos,omitempty"`
//
// Properties that are less important (not used for all responses).
//
// Backdrop path.
ExtBackdropPath string `json:"extBackdropPath,omitempty"`
// Genres.
Genres []MediaGenre `json:"genres,omitempty"`
// Media website.
Homepage string `json:"homepage,omitempty"`
// Media providers (eg Streaming sites, game markets)
Providers []MediaProvider `json:"providers,omitempty"`
// 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"`
//
// Properties only for movies/tv.
//
// Runtime.
Runtime uint `json:"runtime,omitempty"`
// Seasons.
Seasons []MediaSeason `json:"seasons,omitempty"`
// Simple bool for our RequestShow component since Sonarr can be given a
// series type (ideally the frontend doesn't need to do that, but for now it
// does.. if (son)arr code is refactored, can the client just pass very basic
// 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"`
//
// Properties only for Games
//
// Game modes.
GameModes []MediaGenre `json:"gameModes,omitempty"`
}
func (t Media) GetId() int {
switch t.Type {
case MediaTypeTMDBMovie,
MediaTypeTMDBShow:
return t.IDs.TMDB
case MediaTypeIGDBGame:
return t.IDs.IGDB
}
return -99
}
func (t Media) GetMediaType() util.SupportedMedia {
switch t.Type {
case MediaTypeTMDBMovie:
return util.SupportedMediaMovie
case MediaTypeTMDBShow:
return util.SupportedMediaShow
case MediaTypeIGDBGame:
return util.SupportedMediaGame
}
// Unsupported...
slog.Warn("GetMediaType: Requested, but unsupported type encountered.",
"type", t.Type)
return ""
}
type MediaIDs struct {
// The internal ID
// Watcharr uint
// For tmdb data
TMDB int `json:"tmdb,omitempty"`
IMDB string `json:"imdb,omitempty"`
Wikidata string `json:"wikidata,omitempty"`
TVDB int `json:"tvdb,omitempty"`
// For igdb data
IGDB int `json:"igdb,omitempty"`
}
type MediaGenre struct {
// ID of the genre on the external database.
ID uint `json:"id,omitempty"`
// Name of genre.
Name string `json:"name,omitempty"`
}
type MediaSeason struct {
// Season number (doesn't omit empty to keep support for season 0).
Number int `json:"number"`
// Season name.
Name string `json:"name,omitempty"`
// Season air date.
ReleaseDate time.Time `json:"releaseDate,omitzero"`
// Number of episodes in season.
EpisodeCount int `json:"episodeCount"`
}
// Create Media dto from Watched entity.
func NewMediaFromWatched(w *entity.Watched, watchedDto *WatchedDto) Media {
var media Media
if w.Content != nil {
media = NewMediaFromContent(w.Content)
} else if w.Game != nil {
media = NewMediaFromGame(w.Game)
}
media.Watched = *watchedDto
return media
}
// Converter for Content (tv/movie) entity to Media
func NewMediaFromContent(c *entity.Content) Media {
m := Media{
IDs: MediaIDs{
TMDB: c.TmdbID,
},
Name: c.Title,
Summary: c.Overview,
ExtPosterPath: c.PosterPath,
Rating: uint(c.VoteAverage),
RatingCount: uint(c.VoteCount),
Runtime: uint(c.Runtime),
}
switch c.Type {
case entity.MOVIE:
m.Type = MediaTypeTMDBMovie
case entity.SHOW:
m.Type = MediaTypeTMDBShow
}
if c.ReleaseDate != nil {
m.ReleaseDate = *c.ReleaseDate
}
return m
}
// Converter for Game entity to Media
func NewMediaFromGame(c *entity.Game) Media {
m := Media{
IDs: MediaIDs{
IGDB: c.IgdbID,
},
Type: MediaTypeIGDBGame,
Name: c.Name,
Summary: c.Summary,
Poster: c.Poster,
ExtPosterPath: c.CoverID,
Rating: uint(c.Rating),
RatingCount: uint(c.RatingCount),
}
if c.ReleaseDate != nil {
m.ReleaseDate = *c.ReleaseDate
}
return m
}
+19
View File
@@ -0,0 +1,19 @@
package domain
type MediaProviderType string
const (
MediaProviderTypeSub MediaProviderType = "sub"
MediaProviderTypeFree MediaProviderType = "free"
)
type MediaProvider struct {
// Name of the provider.
Name string `json:"name,omitempty"`
// The type of service provided by the provider.
Type MediaProviderType `json:"type,omitempty"`
// Link to watch.
// We can't get a direct link to content from tmdb, we are told to link
// to tmdb to support them instead and from there the user can see deep links.
Link string `json:"link,omitempty"`
}
+22
View File
@@ -0,0 +1,22 @@
package domain
type MediaVideoType string
const (
MediaVideoTypeTrailer MediaVideoType = "trailer"
MediaVideoTypeOther MediaVideoType = "other"
)
// A video (trailer, etc).
// Only supports YouTube for now, but if needed we can add a `site` attribute later.
type MediaVideo struct {
// Video ID for external platform.
ID string `json:"id,omitempty"`
// Video Name.
Name string `json:"name,omitempty"`
// Type of video.
Type MediaVideoType `json:"type,omitempty"`
// If this is the best video to present to the user first.
// (eg with our View Trailer button).
Best bool `json:"best,omitempty"`
}
+56
View File
@@ -0,0 +1,56 @@
package domain
import (
"github.com/go-playground/validator/v10"
"github.com/sbondCo/Watcharr/util"
)
type SearchType string
const (
// Search for **all available media types**.
SearchTypeMulti SearchType = "multi"
// Search for a **movie**.
SearchTypeMovie SearchType = "movie"
// Search for a **show**.
SearchTypeShow SearchType = "show"
// Search for a **person** (actor).
SearchTypePerson SearchType = "person"
// Search for a **game**.
SearchTypeGame SearchType = "game"
)
type SearchRequest struct {
// The type of content we are searching for.
// SearchTypeMulti encompasses all types of media in the results.
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, 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 {
st, ok := fl.Field().Interface().(SearchType)
if ok {
switch st {
case SearchTypeMulti,
SearchTypeMovie,
SearchTypeShow,
SearchTypePerson,
SearchTypeGame:
return true
}
}
return false
}
+9
View File
@@ -0,0 +1,9 @@
package domain
type (
TagAddRequest struct {
Name string `json:"name" binding:"required"`
Color string `json:"color"`
BgColor string `json:"bgColor"`
}
)
+37
View File
@@ -0,0 +1,37 @@
package domain
import (
"time"
"github.com/sbondCo/Watcharr/database/entity"
)
// User
type (
UserBioUpdateRequest struct {
NewBio string `json:"newBio" binding:"max=128"`
}
)
// User Manage
type (
// User details wanted for management views.
ManagedUser struct {
ID uint `json:"id"`
CreatedAt time.Time `json:"createdAt"`
Username string `json:"username"`
Type entity.UserType `json:"type"`
Permissions int `json:"permissions"`
Private bool `json:"private"`
}
UpdateUserRequest struct {
Permissions *int `json:"permissions"`
Type *entity.UserType `json:"type"`
}
UserManageProvider interface {
GetAll() ([]ManagedUser, error)
Manage(userId uint, ur UpdateUserRequest) error
}
)
+189
View File
@@ -0,0 +1,189 @@
package domain
import (
"time"
"github.com/sbondCo/Watcharr/database/entity"
"github.com/sbondCo/Watcharr/feature/watched/watchedutil"
"github.com/sbondCo/Watcharr/util"
)
type WatchedSort string
const (
WatchedSortDateAdded WatchedSort = "DATEADDED"
WatchedSortLastChanged WatchedSort = "LASTCHANGED"
WatchedSortLastFinished WatchedSort = "LASTFIN"
WatchedSortRating WatchedSort = "RATING"
WatchedSortAlphabetical WatchedSort = "ALPHA"
WatchedSortDateReleased WatchedSort = "DATERELEASED"
)
type SortDirection string
const (
WatchedSortDirAsc SortDirection = "asc"
WatchedSortDirDesc SortDirection = "desc"
)
// Get watched page request extra (GET) options.
// Since this is user input, validity of string types cannot be guaranteed.
type WatchedGetPageRequest struct {
// Sorting type.
Sort WatchedSort `form:"sort"`
// Sorting direction (asc or desc).
SortDir SortDirection `form:"sortDir,default=desc"`
// Filtering options.
FilterType []util.SupportedMedia `form:"type" collection_format:"csv"`
FilterStatus []entity.WatchedStatus `form:"status" collection_format:"csv"`
}
type WatchedGetPageExtraProps struct {
// Only get these watched ids.
WatchedIds []int
// Only get watched items where content matches this query.
Query string
}
type WatchedDto struct {
// Properties that always exist in every watched dto below.
ID uint `json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
Status entity.WatchedStatus `json:"status"`
Rating float64 `json:"rating"`
Pinned bool `json:"pinned"`
// 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"`
WatchedSeasons []entity.WatchedSeason `json:"watchedSeasons,omitempty"`
WatchedEpisodes []entity.WatchedEpisode `json:"watchedEpisodes,omitempty"`
Tags []entity.Tag `json:"tags,omitempty"`
LastViewedSeason *int `json:"lastViewedSeason,omitempty"`
}
// New dto with base properties that we have for all WatchedDtos.
// Note: If this is updated, ensure whatever uses this still makes sense.
func NewWatchedDtoWithBaseProps(w *entity.Watched) WatchedDto {
return WatchedDto{
ID: w.ID,
CreatedAt: w.CreatedAt,
UpdatedAt: w.UpdatedAt,
Status: w.Status,
Rating: w.Rating,
Pinned: w.Pinned,
}
}
func NewWatchedDtoForLists(w *entity.Watched) WatchedDto {
dto := NewWatchedDtoWithBaseProps(w)
if w.Content != nil && w.Content.Type == entity.SHOW {
dto.WatchingSeason = watchedutil.GetLatestWatchedInTv(
w.WatchedSeasons, w.WatchedEpisodes)
}
return dto
}
// For public lists showing other users watched data.
func NewWatchedDtoForPublicLists(w *entity.Watched) WatchedDto {
dto := NewWatchedDtoWithBaseProps(w)
if w.Content != nil && w.Content.Type == entity.SHOW {
dto.WatchingSeason = watchedutil.GetLatestWatchedInTv(
w.WatchedSeasons, w.WatchedEpisodes)
}
return dto
}
// A fuller dto with all details needed for a content details page.
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
return dto
}
// 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 {
v := &w[i]
d := NewWatchedDtoForLists(v)
r = append(r, NewMediaFromWatched(v, &d))
}
return r
}
// Get a public users list response.
type WatchedPublicGetPageResponse []Media
func NewWatchedPublicGetPageResponse(w []entity.Watched) WatchedPublicGetPageResponse {
r := WatchedPublicGetPageResponse{}
for i := range w {
v := &w[i]
d := NewWatchedDtoForPublicLists(v)
r = append(r, NewMediaFromWatched(v, &d))
}
return r
}
// Add a watched entry request
type WatchedAddRequest struct {
// Type of content we are adding to watched.
ContentType util.SupportedMedia `json:"contentType" binding:"required,oneof=movie tv game"`
// ID of content from tmdb (if ContentType is movie or tv).
TMDBID int `json:"tmdbId"`
// DEPRECATED!! This will be removed soon, I've left it in only so any third
// party scripts can migrate pain-free. This will work as if you have passed
// the id for `tmdbId`, please replace 'contentId' properties in requests
// with `tmdbId`.
Deprecated_ContentID int `json:"contentId"`
// ID of content from igdb (if ContentType is game).
IGDBID int `json:"igdbId"`
Status entity.WatchedStatus `json:"status"`
Rating float64 `json:"rating" binding:"max=10"`
Thoughts string `json:"thoughts"`
// Pass a watched date and we will set the CreatedAt (and initial UpdatedAt)
// properties for this watched entry to this specific date.
WatchedDate time.Time `json:"watchedDate,omitempty"`
}
// 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"`
RemoveThoughts bool `json:"removeThoughts"`
Pinned *bool `json:"pinned" binding:"required_without_all=Status Rating Thoughts RemoveThoughts"`
}
// Update response.
type WatchedUpdateResponse struct {
NewActivity entity.Activity `json:"newActivity"`
}
// Removal response.
type WatchedRemoveResponse struct {
NewActivity entity.Activity `json:"newActivity"`
}
+83
View File
@@ -0,0 +1,83 @@
package activity
import (
"errors"
"log/slog"
"github.com/sbondCo/Watcharr/database/entity"
"github.com/sbondCo/Watcharr/domain"
"gorm.io/gorm"
)
type Service struct {
db *gorm.DB
}
func NewService(db *gorm.DB) *Service {
return &Service{
db,
}
}
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)
if res.Error != nil {
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) {
if ar.WatchedID == 0 {
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}
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.Debug("Adding activity", "added_activity", activity)
return activity, nil
}
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")
}
if activityUpdateRequest.CustomDate.IsZero() {
return errors.New("customDate must be set to update an activity")
}
res := s.db.
Model(&entity.Activity{}).
Where("user_id = ? AND id = ?", userId, id).
Update("custom_date", activityUpdateRequest.CustomDate)
if res.Error != nil {
slog.Error("Error updating activity in database", "error", res.Error.Error())
return errors.New("failed updating activity in database")
}
if res.RowsAffected < 1 {
slog.Error("No activities were updated. This may be because the activity doesn't exist or is not owned by the calling user.")
return errors.New("failed updating activity in database")
}
slog.Debug("Updating activity", "updated_activity", id)
return nil
}
func (s *Service) DeleteActivity(userId uint, id uint) error {
if id == 0 {
return errors.New("an id must be provided to delete an activity")
}
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())
return errors.New("failed deleting activity in database")
}
if res.RowsAffected < 1 {
slog.Error("No activities were deleted. This may be because the activity doesn't exist or is not owned by the calling user.")
return errors.New("failed deleting activity from database")
}
return nil
}
+101
View File
@@ -0,0 +1,101 @@
package activity
import (
"log/slog"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"github.com/sbondCo/Watcharr/domain"
"github.com/sbondCo/Watcharr/feature/auth/authmiddleware"
"github.com/sbondCo/Watcharr/router"
)
type Router struct {
br *router.BaseRouter
service *Service
}
func NewRouter(br *router.BaseRouter, service *Service) *Router {
return &Router{
br,
service,
}
}
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)
}
func (r *Router) GetActivity(c *gin.Context) {
watchedId, err := strconv.ParseUint(c.Param("watchedId"), 10, 32)
if err != nil {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: "check watched id route param"})
return
}
userId := c.MustGet("userId").(uint)
activity, err := r.service.GetActivity(userId, uint(watchedId))
if err != nil {
c.JSON(http.StatusInternalServerError, router.ErrorResponse{Error: err.Error()})
return
}
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)
if err != nil {
c.Status(400)
return
}
var activityUpdateRequest domain.ActivityUpdateRequest
err = c.ShouldBindJSON(&activityUpdateRequest)
if err == nil {
err = r.service.UpdateActivity(userId, uint(id), activityUpdateRequest)
if err != nil {
c.JSON(http.StatusForbidden, router.ErrorResponse{Error: err.Error()})
return
}
c.Status(http.StatusOK)
return
}
c.AbortWithStatusJSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
}
func (r *Router) DeleteActivity(c *gin.Context) {
userId := c.MustGet("userId").(uint)
id, err := strconv.ParseUint(c.Param("id"), 10, 32)
if err != nil {
c.Status(400)
slog.Error("Could not process activity id when attempting a deletion", "error", err.Error(), "id", c.Param("id"))
return
}
err = r.service.DeleteActivity(userId, uint(id))
if err != nil {
c.JSON(http.StatusForbidden, router.ErrorResponse{Error: err.Error()})
return
}
c.Status(http.StatusOK)
}
+246
View File
@@ -0,0 +1,246 @@
package arr
import (
"errors"
"log/slog"
"github.com/sbondCo/Watcharr/arr"
"github.com/sbondCo/Watcharr/config"
"github.com/sbondCo/Watcharr/config/cfgmodel"
)
type (
ArrTestParams struct {
Host string `json:"host,omitempty"`
Key string `json:"key,omitempty"`
}
SonarrTestResponse struct {
QualityProfiles []arr.QualityProfile `json:"qualityProfiles"`
RootFolders []arr.RootFolder `json:"rootFolders"`
LanguageProfiles []arr.LanguageProfile `json:"languageProfiles"`
}
RadarrTestResponse struct {
QualityProfiles []arr.QualityProfile `json:"qualityProfiles"`
RootFolders []arr.RootFolder `json:"rootFolders"`
LanguageProfiles []arr.LanguageProfile `json:"languageProfiles"`
}
)
// Getting arr servers for public consumption!!!!
// Nothing sensitive to be included!
type arrSettingsPublicResponseBase struct {
Name string `json:"name"`
Host string `json:"host"`
QualityProfile int `json:"qualityProfile,omitempty"`
RootFolder int `json:"rootFolder,omitempty"`
AutomaticSearch bool `json:"automaticSearch"`
}
func newArrSettingsPublicResponseBaseSonarr(
cfg *cfgmodel.SonarrSettings,
) *arrSettingsPublicResponseBase {
return &arrSettingsPublicResponseBase{
Name: cfg.Name,
Host: cfg.Host,
QualityProfile: cfg.QualityProfile,
RootFolder: cfg.RootFolder,
AutomaticSearch: cfg.AutomaticSearch,
}
}
func newArrSettingsPublicResponseBaseRadarr(
cfg *cfgmodel.RadarrSettings,
) *arrSettingsPublicResponseBase {
return &arrSettingsPublicResponseBase{
Name: cfg.Name,
Host: cfg.Host,
QualityProfile: cfg.QualityProfile,
RootFolder: cfg.RootFolder,
AutomaticSearch: cfg.AutomaticSearch,
}
}
// Getting sonarr servers response for ALL USERS!
// Nothing sensitive to be included!
type SonarrSettingsPublicResponseResult struct {
arrSettingsPublicResponseBase
LanguageProfile int `json:"languageProfile,omitempty"`
}
func NewSonarrSettingsPublicResponse(
cfg *cfgmodel.SonarrSettings,
) SonarrSettingsPublicResponseResult {
base := newArrSettingsPublicResponseBaseSonarr(cfg)
return SonarrSettingsPublicResponseResult{
arrSettingsPublicResponseBase: *base,
LanguageProfile: cfg.LanguageProfile,
}
}
// Getting radarr servers response for ALL USERS!
// Nothing sensitive to be included!
type RadarrSettingsPublicResponseResult struct {
arrSettingsPublicResponseBase
}
func NewRadarrSettingsPublicResponse(
cfg *cfgmodel.RadarrSettings,
) RadarrSettingsPublicResponseResult {
base := newArrSettingsPublicResponseBaseRadarr(cfg)
return RadarrSettingsPublicResponseResult{
arrSettingsPublicResponseBase: *base,
}
}
// Response given to users with PERM_REQUEST_CONTENT - should never include sensitive info
func testSonarr(p ArrTestParams) (SonarrTestResponse, error) {
sonarr := arr.New(arr.SONARR, &p.Host, &p.Key)
qps, err := sonarr.GetQualityProfiles()
if err != nil {
slog.Error("testSonarr failed to get quality profiles!", "error", err)
return SonarrTestResponse{}, errors.New("failed to get quality profiles")
}
rfs, err := sonarr.GetRootFolders()
if err != nil {
slog.Error("testSonarr failed to get root folders!", "error", err)
return SonarrTestResponse{}, errors.New("failed to get root folders")
}
lps, err := sonarr.GetLangaugeProfiles()
if err != nil {
slog.Error("testSonarr failed to get language profiles!", "error", err)
return SonarrTestResponse{}, errors.New("failed to get language profiles")
}
return SonarrTestResponse{QualityProfiles: qps, RootFolders: rfs, LanguageProfiles: lps}, nil
}
// Response given to users with PERM_REQUEST_CONTENT - should never include sensitive info
func testRadarr(p ArrTestParams) (RadarrTestResponse, error) {
radarr := arr.New(arr.RADARR, &p.Host, &p.Key)
qps, err := radarr.GetQualityProfiles()
if err != nil {
slog.Error("testRadarr failed to get quality profiles!", "error", err)
return RadarrTestResponse{}, errors.New("failed to get quality profiles")
}
rfs, err := radarr.GetRootFolders()
if err != nil {
slog.Error("testRadarr failed to get root folders!", "error", err)
return RadarrTestResponse{}, errors.New("failed to get root folders")
}
return RadarrTestResponse{QualityProfiles: qps, RootFolders: rfs}, nil
}
// TODO any way to simplify (deduplicate/reuse) these
// methods (and the whole file tbh) would be very good
// Add sonarr server to config
func addSonarr(cfg *config.ServerConfig, s cfgmodel.SonarrSettings) error {
for _, v := range cfg.SONARR {
if v.Name == s.Name {
// Server exists with this name...
return errors.New("server with that name already exists")
}
}
cfg.SONARR = append(cfg.SONARR, s)
cfg.Write()
return nil
}
// Edit sonarr server in config
func editSonarr(cfg *config.ServerConfig, s cfgmodel.SonarrSettings) error {
for i, v := range cfg.SONARR {
if v.Name == s.Name {
cfg.SONARR[i] = s
cfg.Write()
return nil
}
}
return errors.New("can't edit server that does not exist")
}
func rmSonarr(cfg *config.ServerConfig, name string) error {
for i, v := range cfg.SONARR {
if v.Name == name {
cfg.SONARR = append(cfg.SONARR[:i], cfg.SONARR[i+1:]...)
cfg.Write()
return nil
}
}
return errors.New("can't remove a server that does not exist")
}
func getSonarr(cfg *config.ServerConfig, name string) (cfgmodel.SonarrSettings, error) {
for i, v := range cfg.SONARR {
if v.Name == name {
return cfg.SONARR[i], nil
}
}
return cfgmodel.SonarrSettings{}, errors.New("server not found")
}
// Get list of sonarr servers without api keys.
// Regular users with access to adding to sonarr will request this.
func getSonarrsSafe(cfg *config.ServerConfig) []SonarrSettingsPublicResponseResult {
s := []SonarrSettingsPublicResponseResult{}
for _, v := range cfg.SONARR {
s = append(s, NewSonarrSettingsPublicResponse(&v))
}
return s
}
// Add radarr server to config
func addRadarr(cfg *config.ServerConfig, s cfgmodel.RadarrSettings) error {
for _, v := range cfg.RADARR {
if v.Name == s.Name {
// Server exists with this name...
return errors.New("server with that name already exists")
}
}
cfg.RADARR = append(cfg.RADARR, s)
cfg.Write()
return nil
}
// Edit radarr server in config
func editRadarr(cfg *config.ServerConfig, s cfgmodel.RadarrSettings) error {
for i, v := range cfg.RADARR {
if v.Name == s.Name {
cfg.RADARR[i] = s
cfg.Write()
return nil
}
}
return errors.New("can't edit server that does not exist")
}
func rmRadarr(cfg *config.ServerConfig, name string) error {
for i, v := range cfg.RADARR {
if v.Name == name {
cfg.RADARR = append(cfg.RADARR[:i], cfg.RADARR[i+1:]...)
cfg.Write()
return nil
}
}
return errors.New("can't remove a server that does not exist")
}
func getRadarr(cfg *config.ServerConfig, name string) (cfgmodel.RadarrSettings, error) {
for i, v := range cfg.RADARR {
if v.Name == name {
return cfg.RADARR[i], nil
}
}
return cfgmodel.RadarrSettings{}, errors.New("server not found")
}
// Get list of radarr servers without api keys.
// Regular users with access to adding to radarr will request this.
func getRadarrsSafe(cfg *config.ServerConfig) []RadarrSettingsPublicResponseResult {
s := []RadarrSettingsPublicResponseResult{}
for _, v := range cfg.RADARR {
s = append(s, NewRadarrSettingsPublicResponse(&v))
}
return s
}
@@ -1,4 +1,4 @@
package main
package arr
import (
"errors"
@@ -7,6 +7,7 @@ import (
"time"
"github.com/sbondCo/Watcharr/arr"
"github.com/sbondCo/Watcharr/config"
)
type ArrDetailsResponse struct {
@@ -31,8 +32,8 @@ type SonarrDetailsResponse struct {
Items []SonarrDetailsResponseItem `json:"items"`
}
func getRadarrQueueDetails(serverName string, arrId string) (*ArrDetailsResponse, error) {
server, err := getRadarr(serverName)
func getRadarrQueueDetails(cfg *config.ServerConfig, serverName string, arrId string) (*ArrDetailsResponse, error) {
server, err := getRadarr(cfg, serverName)
if err != nil {
slog.Error("getRadarrQueueDetails: Failed to get server", "error", err)
return &ArrDetailsResponse{}, errors.New("failed to get server")
@@ -64,8 +65,8 @@ func getRadarrQueueDetails(serverName string, arrId string) (*ArrDetailsResponse
return &adr, nil
}
func getSonarrQueueDetails(serverName string, arrId string) (*SonarrDetailsResponse, error) {
server, err := getSonarr(serverName)
func getSonarrQueueDetails(cfg *config.ServerConfig, serverName string, arrId string) (*SonarrDetailsResponse, error) {
server, err := getSonarr(cfg, serverName)
if err != nil {
slog.Error("getSonarrQueueDetails: Failed to get server", "error", err)
return &SonarrDetailsResponse{}, errors.New("failed to get server")
@@ -119,14 +120,14 @@ func getSonarrQueueDetails(serverName string, arrId string) (*SonarrDetailsRespo
// Refresh download queues for our sonarr/radarr servers.
// If the queues don't refresh regularly, our queue detail
// calls will just always return the same info.
func refreshArrQueues() {
func RefreshArrQueues(cfg *config.ServerConfig) {
slog.Debug("refreshArrQueues: Refreshing queues for all configured arr servers.")
// We don't care about responses, errors will be logged by the RunCommand func.
for _, v := range Config.RADARR {
for _, v := range cfg.RADARR {
radarr := arr.New(arr.RADARR, &v.Host, &v.Key)
radarr.RunCommand("RefreshMonitoredDownloads")
}
for _, v := range Config.SONARR {
for _, v := range cfg.SONARR {
sonarr := arr.New(arr.SONARR, &v.Host, &v.Key)
sonarr.RunCommand("RefreshMonitoredDownloads")
}
@@ -1,54 +1,19 @@
package main
package arr
import (
"encoding/json"
"errors"
"log/slog"
"time"
"github.com/sbondCo/Watcharr/arr"
"github.com/sbondCo/Watcharr/config"
"github.com/sbondCo/Watcharr/database/entity"
"github.com/sbondCo/Watcharr/feature/auth/permission"
"gorm.io/gorm"
)
type ArrRequestStatus string
const (
// Pending approval from an admin.
ARR_REQUEST_PENDING ArrRequestStatus = "PENDING"
// Request has been approved and should be added to sonarr/radarr.
ARR_REQUEST_APPROVED ArrRequestStatus = "APPROVED"
ARR_REQUEST_AUTO_APPROVED ArrRequestStatus = "AUTO_APPROVED"
// Request has been denied, not adding content.
ARR_REQUEST_DENIED ArrRequestStatus = "DENIED"
// Content was found on sonarr/radarr already, nothing needs to be done.
ARR_REQUEST_FOUND ArrRequestStatus = "FOUND"
)
type ArrRequest struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
UserID uint `json:"-" gorm:"not null"`
User User `json:"-"`
// Username of `User`.
// We don't want to send back the entire user object, just their name.
// Not stored in DB, only used for our response from api.
Username string `json:"username" gorm:"-"`
ContentID *int `json:"-" gorm:"uniqueIndex:sn_to_cid;not null"`
Content *Content `json:"content,omitempty"`
// Server names are used as an identifier
ServerName string `json:"serverName" gorm:"uniqueIndex:sn_to_cid;not null"`
// Sonarr/Radarrs seriesId/movieId
ArrID int `json:"arrId"`
// Tracked request status
Status ArrRequestStatus `json:"status" gorm:"default:PENDING"`
// Full request made by user (arr.SonarrRequest / arr.RadarrRequest)
// so we know how to fulfil the request if approved.
RequestJson string `json:"requestJson"`
}
func deleteArrRequest(db *gorm.DB, id uint) error {
resp := db.Delete(&ArrRequest{ID: id})
resp := db.Delete(&entity.ArrRequest{ID: id})
if resp.Error != nil {
slog.Error("deleteArrRequest: Failed to remove from db", "error", resp.Error)
return errors.New("failed when removing request")
@@ -57,12 +22,12 @@ func deleteArrRequest(db *gorm.DB, id uint) error {
}
// Gets all requests.
func getArrRequests(db *gorm.DB) ([]ArrRequest, error) {
var req []ArrRequest
func getArrRequests(db *gorm.DB) ([]entity.ArrRequest, error) {
var req []entity.ArrRequest
resp := db.Preload("Content").Preload("User").Find(&req)
if resp.Error != nil {
slog.Error("getArrRequests: Failed to search for requests in db", "error", resp.Error)
return []ArrRequest{}, errors.New("failed to find requests")
return []entity.ArrRequest{}, errors.New("failed to find requests")
}
for i := range req {
req[i].Username = req[i].User.Username
@@ -70,57 +35,57 @@ func getArrRequests(db *gorm.DB) ([]ArrRequest, error) {
return req, nil
}
func getArrRequest(db *gorm.DB, requestId uint) (ArrRequest, error) {
var req ArrRequest
func getArrRequest(db *gorm.DB, requestId uint) (entity.ArrRequest, error) {
var req entity.ArrRequest
resp := db.Where("id = ?", requestId).Take(&req)
if resp.Error != nil {
slog.Error("getArrRequest: Failed to search for request in db", "error", resp.Error)
return ArrRequest{}, errors.New("failed to find request")
return entity.ArrRequest{}, errors.New("failed to find request")
}
return req, nil
}
func getArrRequestByTmdbId(db *gorm.DB, contentType ContentType, tmdbId int) (ArrRequest, error) {
var req ArrRequest
func getArrRequestByTmdbId(db *gorm.DB, contentType entity.ContentType, tmdbId int) (entity.ArrRequest, error) {
var req entity.ArrRequest
resp := db.Joins("JOIN contents ON contents.id = arr_requests.content_id AND contents.tmdb_id = ? AND contents.type = ?", tmdbId, contentType).Find(&req)
if resp.Error != nil {
slog.Error("getArrRequestByTmdbId: Failed to search for request in db", "error", resp.Error)
return ArrRequest{}, errors.New("failed to find request")
return entity.ArrRequest{}, errors.New("failed to find request")
}
return req, nil
}
func createArrRequest(db *gorm.DB, userId uint, serverName string, contentType ContentType, tmdbId int, reqJson string) (*ArrRequest, error) {
content, err := getOrCacheContent(db, contentType, tmdbId)
func createArrRequest(db *gorm.DB, cp ContentProvider, userId uint, serverName string, contentType entity.ContentType, tmdbId int, reqJson string) (*entity.ArrRequest, error) {
content, err := cp.GetOrCacheContent(contentType, tmdbId)
if err != nil {
slog.Error("createArrRequest: getOrCacheContent errored.")
return &ArrRequest{}, err
slog.Error("createArrRequest: GetOrCacheContent errored.")
return &entity.ArrRequest{}, err
}
req := ArrRequest{UserID: userId, ServerName: serverName, ContentID: &content.ID, RequestJson: reqJson}
req := entity.ArrRequest{UserID: userId, ServerName: serverName, ContentID: &content.ID, RequestJson: reqJson}
resp := db.Create(&req)
if resp.Error != nil {
slog.Error("createArrRequest: Failed when inserting request into db.", "error", err)
return &ArrRequest{}, errors.New("failed when adding request")
return &entity.ArrRequest{}, errors.New("failed when adding request")
}
return &req, nil
}
func createSonarrRequest(db *gorm.DB, userId uint, userPerms int, ur arr.SonarrRequest) (*ArrRequest, error) {
server, err := getSonarr(ur.ServerName)
func createSonarrRequest(cfg *config.ServerConfig, db *gorm.DB, cp ContentProvider, userId uint, userPerms int, ur arr.SonarrRequest) (*entity.ArrRequest, error) {
server, err := getSonarr(cfg, ur.ServerName)
if err != nil {
slog.Error("createSonarrRequest: Failed to get server", "error", err)
return &ArrRequest{}, errors.New("failed to get server")
return &entity.ArrRequest{}, errors.New("failed to get server")
}
reqJson, err := json.Marshal(ur)
if err != nil {
slog.Error("createRadarrRequest: Failed when marshalling json request", "error", err)
return &ArrRequest{}, errors.New("failed when processing request")
return &entity.ArrRequest{}, errors.New("failed when processing request")
}
// Since we create the request in the db now, we don't have to check for duplicates, a unique constraint will error us here if hit.
arrReq, err := createArrRequest(db, userId, ur.ServerName, SHOW, ur.TMDBID, string(reqJson[:]))
arrReq, err := createArrRequest(db, cp, userId, ur.ServerName, entity.SHOW, ur.TMDBID, string(reqJson[:]))
if err != nil {
slog.Error("createSonarrRequest: Failed when creating arr request", "error", err)
return &ArrRequest{}, errors.New("failed when creating request")
return &entity.ArrRequest{}, errors.New("failed when creating request")
}
sonarr := arr.New(arr.SONARR, &server.Host, &server.Key)
// 1. Lookup on Sonarr to check if the show has already been added (via method other than watcharr).
@@ -130,10 +95,14 @@ func createSonarrRequest(db *gorm.DB, userId uint, userPerms int, ur arr.SonarrR
found := lookupRes[0] // There should only be one result when looking up by id.
// If it has an ID, then it will have already been added to Sonarr.
if found.ID != 0 {
dbResp := db.Model(&ArrRequest{}).Where("id = ?", arrReq.ID).Update("arr_id", found.ID).Update("status", ARR_REQUEST_FOUND)
dbResp := db.
Model(&entity.ArrRequest{}).
Where("id = ?", arrReq.ID).
Update("arr_id", found.ID).
Update("status", entity.ARR_REQUEST_FOUND)
if dbResp.Error != nil {
slog.Error("createSonarrRequest: Failed to update request in db", "error", err)
return &ArrRequest{}, errors.New("content was requested, but we failed to update the db")
return &entity.ArrRequest{}, errors.New("content was requested, but we failed to update the db")
} else {
slog.Debug("createSonarrRequest: Result from lookup had an ID. Request in database has been updated with it.", "arr_id", found.ID)
arrReq.ArrID = found.ID
@@ -142,46 +111,50 @@ func createSonarrRequest(db *gorm.DB, userId uint, userPerms int, ur arr.SonarrR
}
}
// 2. If user has auto approve perms, add movie to sonarr.
if hasPermission(userPerms, PERM_REQUEST_CONTENT_AUTO_APPROVE) {
if permission.Has(userPerms, entity.PERM_REQUEST_CONTENT_AUTO_APPROVE) {
slog.Debug("createSonarrRequest: User has auto approve permission.. sending request to Sonarr.")
ur.AutomaticSearch = server.AutomaticSearch
resp, err := sonarr.AddContent(sonarr.BuildAddShowBody(ur))
if err != nil {
slog.Error("createSonarrRequest: Failed to add content", "error", err)
return &ArrRequest{}, errors.New("failed to add content")
return &entity.ArrRequest{}, errors.New("failed to add content")
}
dbResp := db.Model(&ArrRequest{}).Where("id = ?", arrReq.ID).Update("arr_id", resp["id"]).Update("status", ARR_REQUEST_AUTO_APPROVED)
dbResp := db.
Model(&entity.ArrRequest{}).
Where("id = ?", arrReq.ID).
Update("arr_id", resp["id"]).
Update("status", entity.ARR_REQUEST_AUTO_APPROVED)
if dbResp.Error != nil {
slog.Error("createSonarrRequest: Failed to update request in db", "error", err)
return &ArrRequest{}, errors.New("content was requested, but we failed to update the db")
return &entity.ArrRequest{}, errors.New("content was requested, but we failed to update the db")
}
arrId, ok := resp["id"].(float64)
if !ok {
slog.Error("createSonarrRequest: Failed to cast arr id as an int", "id", resp["id"])
return &ArrRequest{}, errors.New("failed to get arr id")
return &entity.ArrRequest{}, errors.New("failed to get arr id")
}
arrReq.ArrID = int(arrId)
arrReq.Status = ARR_REQUEST_AUTO_APPROVED
arrReq.Status = entity.ARR_REQUEST_AUTO_APPROVED
}
return arrReq, nil
}
func createRadarrRequest(db *gorm.DB, userId uint, userPerms int, ur arr.RadarrRequest) (*ArrRequest, error) {
server, err := getRadarr(ur.ServerName)
func createRadarrRequest(cfg *config.ServerConfig, db *gorm.DB, cp ContentProvider, userId uint, userPerms int, ur arr.RadarrRequest) (*entity.ArrRequest, error) {
server, err := getRadarr(cfg, ur.ServerName)
if err != nil {
slog.Error("createRadarrRequest: Failed to get server", "error", err)
return &ArrRequest{}, errors.New("failed to get server")
return &entity.ArrRequest{}, errors.New("failed to get server")
}
reqJson, err := json.Marshal(ur)
if err != nil {
slog.Error("createRadarrRequest: Failed when marshalling json request", "error", err)
return &ArrRequest{}, errors.New("failed when processing request")
return &entity.ArrRequest{}, errors.New("failed when processing request")
}
// Since we create the request in the db now, we don't have to check for duplicates, a unique constraint will error us here if hit.
arrReq, err := createArrRequest(db, userId, ur.ServerName, MOVIE, ur.TMDBID, string(reqJson[:]))
arrReq, err := createArrRequest(db, cp, userId, ur.ServerName, entity.MOVIE, ur.TMDBID, string(reqJson[:]))
if err != nil {
slog.Error("createRadarrRequest: Failed when creating arr request", "error", err)
return &ArrRequest{}, errors.New("failed when creating request")
return &entity.ArrRequest{}, errors.New("failed when creating request")
}
radarr := arr.New(arr.RADARR, &server.Host, &server.Key)
// 1. Lookup on Radarr to check if the movie has already been added (via method other than watcharr).
@@ -191,10 +164,14 @@ func createRadarrRequest(db *gorm.DB, userId uint, userPerms int, ur arr.RadarrR
found := lookupRes[0] // There should only be one result when looking up by id.
// If it has an ID, then it will have already been added to Radarr.
if found.ID != 0 {
dbResp := db.Model(&ArrRequest{}).Where("id = ?", arrReq.ID).Update("arr_id", found.ID).Update("status", ARR_REQUEST_FOUND)
dbResp := db.
Model(&entity.ArrRequest{}).
Where("id = ?", arrReq.ID).
Update("arr_id", found.ID).
Update("status", entity.ARR_REQUEST_FOUND)
if dbResp.Error != nil {
slog.Error("createRadarrRequest: Failed to update request in db", "error", err)
return &ArrRequest{}, errors.New("content was requested, but we failed to update the db")
return &entity.ArrRequest{}, errors.New("content was requested, but we failed to update the db")
} else {
slog.Debug("createRadarrRequest: Result from lookup had an ID. Request in database has been updated with it.", "arr_id", found.ID)
arrReq.ArrID = found.ID
@@ -203,31 +180,35 @@ func createRadarrRequest(db *gorm.DB, userId uint, userPerms int, ur arr.RadarrR
}
}
// 2. If user has auto approve perms, add movie to radarr.
if hasPermission(userPerms, PERM_REQUEST_CONTENT_AUTO_APPROVE) {
if permission.Has(userPerms, entity.PERM_REQUEST_CONTENT_AUTO_APPROVE) {
slog.Debug("createRadarrRequest: User has auto approve permission.. sending request to Radarr.")
ur.AutomaticSearch = server.AutomaticSearch
resp, err := radarr.AddContent(radarr.BuildAddMovieBody(ur))
if err != nil {
slog.Error("createRadarrRequest: Failed to add content", "error", err)
return &ArrRequest{}, errors.New("failed to add content")
return &entity.ArrRequest{}, errors.New("failed to add content")
}
dbResp := db.Model(&ArrRequest{}).Where("id = ?", arrReq.ID).Update("arr_id", resp["id"]).Update("status", ARR_REQUEST_AUTO_APPROVED)
dbResp := db.
Model(&entity.ArrRequest{}).
Where("id = ?", arrReq.ID).
Update("arr_id", resp["id"]).
Update("status", entity.ARR_REQUEST_AUTO_APPROVED)
if dbResp.Error != nil {
slog.Error("createRadarrRequest: Failed to update request in db", "error", err)
return &ArrRequest{}, errors.New("content was requested, but we failed to update the db")
return &entity.ArrRequest{}, errors.New("content was requested, but we failed to update the db")
}
arrId, ok := resp["id"].(float64)
if !ok {
slog.Error("createRadarrRequest: Failed to cast arr id as an int", "id", resp["id"])
return &ArrRequest{}, errors.New("failed to get arr id")
return &entity.ArrRequest{}, errors.New("failed to get arr id")
}
arrReq.ArrID = int(arrId)
arrReq.Status = ARR_REQUEST_AUTO_APPROVED
arrReq.Status = entity.ARR_REQUEST_AUTO_APPROVED
}
return arrReq, nil
}
func getRadarrRequestInfo(db *gorm.DB, requestId uint) (arr.MovieSerie, error) {
func getRadarrRequestInfo(cfg *config.ServerConfig, db *gorm.DB, requestId uint) (arr.MovieSerie, error) {
if requestId == 0 {
slog.Error("sonarr info: No request id provided")
return arr.MovieSerie{}, errors.New("no request id provided")
@@ -237,7 +218,7 @@ func getRadarrRequestInfo(db *gorm.DB, requestId uint) (arr.MovieSerie, error) {
slog.Error("radarr info: Failed to get server", "error", err)
return arr.MovieSerie{}, errors.New("failed to get server")
}
server, err := getRadarr(arrRequest.ServerName)
server, err := getRadarr(cfg, arrRequest.ServerName)
if err != nil {
slog.Error("radarr info: Failed to get server", "error", err)
return arr.MovieSerie{}, errors.New("failed to get server")
@@ -246,7 +227,7 @@ func getRadarrRequestInfo(db *gorm.DB, requestId uint) (arr.MovieSerie, error) {
resp, respStatusCode, err := radarr.GetContent(arrRequest.ArrID)
if err != nil {
slog.Error("radarr info: Failed to get info", "error", err)
if (arrRequest.Status == ARR_REQUEST_APPROVED || arrRequest.Status == ARR_REQUEST_AUTO_APPROVED) && respStatusCode == 404 {
if (arrRequest.Status == entity.ARR_REQUEST_APPROVED || arrRequest.Status == entity.ARR_REQUEST_AUTO_APPROVED) && respStatusCode == 404 {
slog.Error("radarr info: 404 returned.. content must've been removed.. removing request.")
err := deleteArrRequest(db, arrRequest.ID)
if err != nil {
@@ -260,7 +241,7 @@ func getRadarrRequestInfo(db *gorm.DB, requestId uint) (arr.MovieSerie, error) {
return resp, nil
}
func getSonarrRequestInfo(db *gorm.DB, requestId uint) (arr.MovieSerie, error) {
func getSonarrRequestInfo(cfg *config.ServerConfig, db *gorm.DB, requestId uint) (arr.MovieSerie, error) {
if requestId == 0 {
slog.Error("sonarr info: No request id provided")
return arr.MovieSerie{}, errors.New("no request id provided")
@@ -270,7 +251,7 @@ func getSonarrRequestInfo(db *gorm.DB, requestId uint) (arr.MovieSerie, error) {
slog.Error("sonarr info: Failed to get server", "error", err)
return arr.MovieSerie{}, errors.New("failed to get server")
}
server, err := getSonarr(arrRequest.ServerName)
server, err := getSonarr(cfg, arrRequest.ServerName)
if err != nil {
slog.Error("sonarr info: Failed to get server", "error", err)
return arr.MovieSerie{}, errors.New("failed to get server")
@@ -279,7 +260,7 @@ func getSonarrRequestInfo(db *gorm.DB, requestId uint) (arr.MovieSerie, error) {
resp, respStatusCode, err := sonarr.GetContent(arrRequest.ArrID)
if err != nil {
slog.Error("sonarr info: Failed to get info", "error", err)
if (arrRequest.Status == ARR_REQUEST_APPROVED || arrRequest.Status == ARR_REQUEST_AUTO_APPROVED) && respStatusCode == 404 {
if (arrRequest.Status == entity.ARR_REQUEST_APPROVED || arrRequest.Status == entity.ARR_REQUEST_AUTO_APPROVED) && respStatusCode == 404 {
slog.Error("sonarr info: 404 returned.. content must've been removed.. removing request.")
err := deleteArrRequest(db, arrRequest.ID)
if err != nil {
@@ -1,16 +1,21 @@
package main
package arr
import (
"errors"
"log/slog"
"github.com/sbondCo/Watcharr/arr"
"github.com/sbondCo/Watcharr/config"
"github.com/sbondCo/Watcharr/database/entity"
"gorm.io/gorm"
)
// Deny an arr request
func denyArrRequest(db *gorm.DB, id uint) error {
resp := db.Model(&ArrRequest{}).Where("id = ?", id).Update("status", ARR_REQUEST_DENIED)
resp := db.
Model(&entity.ArrRequest{}).
Where("id = ?", id).
Update("status", entity.ARR_REQUEST_DENIED)
if resp.Error != nil {
slog.Error("denyArrRequest: Failed to update status to denied", "error", resp.Error)
return errors.New("failed when updating request status")
@@ -19,14 +24,14 @@ func denyArrRequest(db *gorm.DB, id uint) error {
}
// Approve radarr movie
func approveRadarrRequest(db *gorm.DB, reqId uint, ur arr.RadarrRequest) (int, error) {
func approveRadarrRequest(cfg *config.ServerConfig, db *gorm.DB, reqId uint, ur arr.RadarrRequest) (int, error) {
_, err := getArrRequest(db, reqId)
if err != nil {
slog.Error("approveRadarrRequest: Failed to get request from db", "error", err)
return 0, errors.New("failed to get request")
}
// Get server in request
server, err := getRadarr(ur.ServerName)
server, err := getRadarr(cfg, ur.ServerName)
if err != nil {
slog.Error("approveRadarrRequest: Failed to get server", "error", err)
return 0, errors.New("failed to get server")
@@ -38,7 +43,11 @@ func approveRadarrRequest(db *gorm.DB, reqId uint, ur arr.RadarrRequest) (int, e
slog.Error("approveRadarrRequest: Failed to add content", "error", err)
return 0, errors.New("failed to add content")
}
dbResp := db.Model(&ArrRequest{}).Where("id = ?", reqId).Update("arr_id", resp["id"]).Update("status", ARR_REQUEST_APPROVED)
dbResp := db.
Model(&entity.ArrRequest{}).
Where("id = ?", reqId).
Update("arr_id", resp["id"]).
Update("status", entity.ARR_REQUEST_APPROVED)
if dbResp.Error != nil {
slog.Error("approveRadarrRequest: Failed to update request in db", "error", err)
return 0, errors.New("content was requested, but we failed to update the db")
@@ -52,14 +61,14 @@ func approveRadarrRequest(db *gorm.DB, reqId uint, ur arr.RadarrRequest) (int, e
}
// Approve sonarr movie
func approveSonarrRequest(db *gorm.DB, reqId uint, ur arr.SonarrRequest) (int, error) {
func approveSonarrRequest(cfg *config.ServerConfig, db *gorm.DB, reqId uint, ur arr.SonarrRequest) (int, error) {
_, err := getArrRequest(db, reqId)
if err != nil {
slog.Error("approveSonarrRequest: Failed to get request from db", "error", err)
return 0, errors.New("failed to get request")
}
// Get server in request
server, err := getSonarr(ur.ServerName)
server, err := getSonarr(cfg, ur.ServerName)
if err != nil {
slog.Error("approveSonarrRequest: Failed to get server", "error", err)
return 0, errors.New("failed to get server")
@@ -71,7 +80,11 @@ func approveSonarrRequest(db *gorm.DB, reqId uint, ur arr.SonarrRequest) (int, e
slog.Error("approveSonarrRequest: Failed to add content", "error", err)
return 0, errors.New("failed to add content")
}
dbResp := db.Model(&ArrRequest{}).Where("id = ?", reqId).Update("arr_id", resp["id"]).Update("status", ARR_REQUEST_APPROVED)
dbResp := db.
Model(&entity.ArrRequest{}).
Where("id = ?", reqId).
Update("arr_id", resp["id"]).
Update("status", entity.ARR_REQUEST_APPROVED)
if dbResp.Error != nil {
slog.Error("approveSonarrRequest: Failed to update request in db", "error", err)
return 0, errors.New("content was requested, but we failed to update the db")
+445
View File
@@ -0,0 +1,445 @@
package arr
import (
"log/slog"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"github.com/sbondCo/Watcharr/arr"
"github.com/sbondCo/Watcharr/config/cfgmodel"
"github.com/sbondCo/Watcharr/database/entity"
"github.com/sbondCo/Watcharr/feature/auth/authmiddleware"
"github.com/sbondCo/Watcharr/router"
)
// ContentProvider - Temporary, this ARR code at some point will
// be turned into services to conform with new code format, for now
// passing contentprovider through here.
type ContentProvider interface {
GetOrCacheContent(contentType entity.ContentType, tmdbId int) (entity.Content, error)
}
type Router struct {
br *router.BaseRouter
contentProvider ContentProvider
}
func NewRouter(br *router.BaseRouter, contentProvider ContentProvider) *Router {
return &Router{
br,
contentProvider,
}
}
func (r *Router) AddRoutes() {
// **NOTE:** Routes are manually given authmiddleware.AdminRequired or authmiddleware.PermRequired middleware.
// SONARR
{
s := r.br.Router.Group("/arr/son").Use(authmiddleware.AuthRequired(r.br.DB, r.br.Cfg))
// Routes are manually given authmiddleware.AdminRequired or authmiddleware.PermRequired middleware.
// Test configuration
s.POST("/test", authmiddleware.AdminRequired(), r.TestSonarr)
// Used to get config for specific server (quality profile, root folder, etc)
s.GET("/config/:name", authmiddleware.PermRequired(entity.PERM_REQUEST_CONTENT), r.GetSonarrServer)
// Add sonarr server into config
s.POST("/add", authmiddleware.AdminRequired(), r.AddSonarr)
// Edit sonarr servers config
s.POST("/edit", authmiddleware.AdminRequired(), r.UpdateSonarrServer)
// Remove sonarr server
s.POST("/rm/:name", authmiddleware.AdminRequired(), r.UpdateRemoveSonarrServer)
// Get safe config for all sonarr servers
s.GET("", authmiddleware.PermRequired(entity.PERM_REQUEST_CONTENT), r.GetSonarrsSafe)
// Request a show
s.POST("/request", authmiddleware.PermRequired(entity.PERM_REQUEST_CONTENT), r.CreateSonarrRequest)
s.GET("/request/:tmdbId", authmiddleware.PermRequired(entity.PERM_REQUEST_CONTENT), r.GetSonarrRequestByTmdbId)
s.POST("/request/approve/:id", authmiddleware.PermRequired(entity.PERM_ADMIN), r.UpdateApproveSonarrRequest)
s.GET("/status/:serverName/:arrId", authmiddleware.PermRequired(entity.PERM_REQUEST_CONTENT), r.GetSonarrQueueDetails)
s.GET("/info/:requestId", authmiddleware.PermRequired(entity.PERM_REQUEST_CONTENT), r.GetSonarrRequestInfo)
}
// RADARR
{
s := r.br.Router.Group("/arr/rad").Use(authmiddleware.AuthRequired(r.br.DB, r.br.Cfg))
// Routes are manually given authmiddleware.AdminRequired or authmiddleware.PermRequired middleware.
// Test configuration
s.POST("/test", authmiddleware.AdminRequired(), r.TestRadarr)
// Get config for specific server
s.GET("/config/:name", authmiddleware.PermRequired(entity.PERM_REQUEST_CONTENT), r.GetRadarrServer)
s.POST("/add", authmiddleware.AdminRequired(), r.AddRadarr)
s.POST("/edit", authmiddleware.AdminRequired(), r.UpdateRadarrServer)
s.POST("/rm/:name", authmiddleware.AdminRequired(), r.UpdateRemoveRadarrServer)
s.GET("", authmiddleware.PermRequired(entity.PERM_REQUEST_CONTENT), r.GetRadarrsSafe)
s.POST("/request", authmiddleware.PermRequired(entity.PERM_REQUEST_CONTENT), r.CreateRadarrRequest)
s.GET("/request/:tmdbId", authmiddleware.PermRequired(entity.PERM_REQUEST_CONTENT), r.GetRadarrRequestByTmdbId)
s.POST("/request/approve/:id", authmiddleware.PermRequired(entity.PERM_ADMIN), r.UpdateApproveRadarrRequest)
s.GET("/status/:serverName/:arrId", authmiddleware.PermRequired(entity.PERM_REQUEST_CONTENT), r.GetRadarrQueueDetails)
s.GET("/info/:requestId", authmiddleware.PermRequired(entity.PERM_REQUEST_CONTENT), r.GetRadarrRequestInfo)
}
// Request Management
{
s := r.br.Router.Group("/arr/request").Use(authmiddleware.AuthRequired(r.br.DB, r.br.Cfg))
// Get all requests (for manage_requests view), only for admins.
s.GET("/", authmiddleware.AdminRequired(), r.GetAllRequests)
// Deny a request (for manage_requests view), only for admins.
s.POST("/deny/:id", authmiddleware.AdminRequired(), r.UpdateDenyRequest)
}
}
// Test configuration
func (r *Router) TestSonarr(c *gin.Context) {
var ur ArrTestParams
err := c.ShouldBindJSON(&ur)
if err == nil {
resp, err := testSonarr(ur)
if err != nil {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
c.JSON(http.StatusOK, resp)
return
}
c.AbortWithStatusJSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
}
// Used to get config for specific server (quality profile, root folder, etc)
func (r *Router) GetSonarrServer(c *gin.Context) {
server, err := getSonarr(r.br.Cfg, c.Param("name"))
if err != nil {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
resp, err := testSonarr(ArrTestParams{Host: server.Host, Key: server.Key})
if err != nil {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
c.JSON(http.StatusOK, resp)
}
// Add sonarr server into config
func (r *Router) AddSonarr(c *gin.Context) {
var ur cfgmodel.SonarrSettings
err := c.ShouldBindJSON(&ur)
if err == nil {
err := addSonarr(r.br.Cfg, ur)
if err != nil {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
c.Status(http.StatusOK)
return
}
c.AbortWithStatusJSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
}
// Edit sonarr servers config
func (r *Router) UpdateSonarrServer(c *gin.Context) {
var ur cfgmodel.SonarrSettings
err := c.ShouldBindJSON(&ur)
if err == nil {
err := editSonarr(r.br.Cfg, ur)
if err != nil {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
c.Status(http.StatusOK)
return
}
c.AbortWithStatusJSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
}
// Remove sonarr server
func (r *Router) UpdateRemoveSonarrServer(c *gin.Context) {
err := rmSonarr(r.br.Cfg, c.Param("name"))
if err != nil {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
c.Status(http.StatusOK)
}
// Get safe config for all sonarr servers
func (r *Router) GetSonarrsSafe(c *gin.Context) {
response := getSonarrsSafe(r.br.Cfg)
c.JSON(http.StatusOK, response)
}
// Request a show
func (r *Router) CreateSonarrRequest(c *gin.Context) {
var ur arr.SonarrRequest
err := c.ShouldBindJSON(&ur)
if err == nil {
userId := c.MustGet("userId").(uint)
perms := c.GetInt("userPermissions")
response, err := createSonarrRequest(r.br.Cfg, r.br.DB, r.contentProvider, userId, perms, ur)
if err != nil {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
c.JSON(http.StatusOK, response)
return
}
c.AbortWithStatusJSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
}
func (r *Router) GetSonarrRequestByTmdbId(c *gin.Context) {
tmdbId, err := strconv.Atoi(c.Param("tmdbId"))
if err != nil {
slog.Error("Couldn't parse tmdbId", "tmdbId", tmdbId)
c.Status(400)
return
}
response, err := getArrRequestByTmdbId(r.br.DB, entity.SHOW, tmdbId)
if err != nil {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
c.JSON(http.StatusOK, response)
}
func (r *Router) UpdateApproveSonarrRequest(c *gin.Context) {
var ur arr.SonarrRequest
err := c.ShouldBindJSON(&ur)
if err == nil {
requestId, err := strconv.Atoi(c.Param("id"))
if err != nil {
slog.Error("Couldn't parse request id", "request_id", requestId)
c.Status(400)
return
}
response, err := approveSonarrRequest(r.br.Cfg, r.br.DB, uint(requestId), ur)
if err != nil {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
c.JSON(http.StatusOK, response)
return
}
c.AbortWithStatusJSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
}
func (r *Router) GetSonarrQueueDetails(c *gin.Context) {
response, err := getSonarrQueueDetails(r.br.Cfg, c.Param("serverName"), c.Param("arrId"))
if err != nil {
if err.Error() == "no details found" {
c.Status(http.StatusNoContent) // Item not found in queue.. missing
return
}
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
c.JSON(http.StatusOK, response)
}
func (r *Router) GetSonarrRequestInfo(c *gin.Context) {
requestId, err := strconv.ParseUint(c.Param("requestId"), 10, 64)
if err != nil {
slog.Error("/info/:requestId - requestId could not be parsed", "requestId", requestId)
c.Status(http.StatusBadRequest)
return
}
response, err := getSonarrRequestInfo(r.br.Cfg, r.br.DB, uint(requestId))
if err != nil {
if err.Error() == "request deleted" {
c.JSON(http.StatusNotFound, router.ErrorResponse{Error: "request deleted"})
return
}
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
c.JSON(http.StatusOK, response)
}
// Test configuration
func (r *Router) TestRadarr(c *gin.Context) {
var ur ArrTestParams
err := c.ShouldBindJSON(&ur)
if err == nil {
resp, err := testRadarr(ur)
if err != nil {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
c.JSON(http.StatusOK, resp)
return
}
c.AbortWithStatusJSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
}
// Get config for specific server
func (r *Router) GetRadarrServer(c *gin.Context) {
server, err := getRadarr(r.br.Cfg, c.Param("name"))
if err != nil {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
resp, err := testRadarr(ArrTestParams{Host: server.Host, Key: server.Key})
if err != nil {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
c.JSON(http.StatusOK, resp)
}
func (r *Router) AddRadarr(c *gin.Context) {
var ur cfgmodel.RadarrSettings
err := c.ShouldBindJSON(&ur)
if err == nil {
err := addRadarr(r.br.Cfg, ur)
if err != nil {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
c.Status(http.StatusOK)
return
}
c.AbortWithStatusJSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
}
func (r *Router) UpdateRadarrServer(c *gin.Context) {
var ur cfgmodel.RadarrSettings
err := c.ShouldBindJSON(&ur)
if err == nil {
err := editRadarr(r.br.Cfg, ur)
if err != nil {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
c.Status(http.StatusOK)
return
}
c.AbortWithStatusJSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
}
func (r *Router) UpdateRemoveRadarrServer(c *gin.Context) {
err := rmRadarr(r.br.Cfg, c.Param("name"))
if err != nil {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
c.Status(http.StatusOK)
}
func (r *Router) GetRadarrsSafe(c *gin.Context) {
response := getRadarrsSafe(r.br.Cfg)
c.JSON(http.StatusOK, response)
}
func (r *Router) CreateRadarrRequest(c *gin.Context) {
var ur arr.RadarrRequest
err := c.ShouldBindJSON(&ur)
if err == nil {
userId := c.MustGet("userId").(uint)
perms := c.GetInt("userPermissions")
response, err := createRadarrRequest(r.br.Cfg, r.br.DB, r.contentProvider, userId, perms, ur)
if err != nil {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
c.JSON(http.StatusOK, response)
return
}
c.AbortWithStatusJSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
}
func (r *Router) GetRadarrRequestByTmdbId(c *gin.Context) {
tmdbId, err := strconv.Atoi(c.Param("tmdbId"))
if err != nil {
slog.Error("Couldn't parse tmdbId", "tmdbId", tmdbId)
c.Status(400)
return
}
response, err := getArrRequestByTmdbId(r.br.DB, entity.MOVIE, tmdbId)
if err != nil {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
c.JSON(http.StatusOK, response)
}
func (r *Router) UpdateApproveRadarrRequest(c *gin.Context) {
var ur arr.RadarrRequest
err := c.ShouldBindJSON(&ur)
if err == nil {
requestId, err := strconv.Atoi(c.Param("id"))
if err != nil {
slog.Error("Couldn't parse request id", "request_id", requestId)
c.Status(400)
return
}
response, err := approveRadarrRequest(r.br.Cfg, r.br.DB, uint(requestId), ur)
if err != nil {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
c.JSON(http.StatusOK, response)
return
}
c.AbortWithStatusJSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
}
func (r *Router) GetRadarrQueueDetails(c *gin.Context) {
response, err := getRadarrQueueDetails(r.br.Cfg, c.Param("serverName"), c.Param("arrId"))
if err != nil {
if err.Error() == "no details found" {
c.Status(http.StatusNoContent) // Item not found in queue.. missing
return
}
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
c.JSON(http.StatusOK, response)
}
func (r *Router) GetRadarrRequestInfo(c *gin.Context) {
requestId, err := strconv.ParseUint(c.Param("requestId"), 10, 64)
if err != nil {
slog.Error("/info/:requestId - requestId could not be parsed", "requestId", requestId)
c.Status(http.StatusBadRequest)
return
}
response, err := getRadarrRequestInfo(r.br.Cfg, r.br.DB, uint(requestId))
if err != nil {
if err.Error() == "request deleted" {
c.JSON(http.StatusNotFound, router.ErrorResponse{Error: "request deleted"})
return
}
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
c.JSON(http.StatusOK, response)
}
// Get all requests (for manage_requests view), only for admins.
func (r *Router) GetAllRequests(c *gin.Context) {
response, err := getArrRequests(r.br.DB)
if err != nil {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
c.JSON(http.StatusOK, response)
}
// Deny a request (for manage_requests view), only for admins.
func (r *Router) UpdateDenyRequest(c *gin.Context) {
requestId, err := strconv.Atoi(c.Param("id"))
if err != nil {
slog.Error("Couldn't parse request id", "request_id", requestId)
c.Status(400)
return
}
err = denyArrRequest(r.br.DB, uint(requestId))
if err != nil {
c.JSON(http.StatusInternalServerError, router.ErrorResponse{Error: err.Error()})
return
}
c.Status(http.StatusOK)
}
+127 -310
View File
@@ -1,4 +1,4 @@
package main
package auth
import (
"bytes"
@@ -17,117 +17,15 @@ import (
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"github.com/sbondCo/Watcharr/config"
"github.com/sbondCo/Watcharr/database/entity"
"github.com/sbondCo/Watcharr/feature/plex"
"github.com/sbondCo/Watcharr/token"
"golang.org/x/crypto/argon2"
"gorm.io/gorm"
)
type UserType uint8
var (
WATCHARR_USER UserType = 0
JELLYFIN_USER UserType = 1
PLEX_USER UserType = 2
// Registered via trusted header auth
PROXY_USER UserType = 3
)
// User Perms
// iota auto increments for us so when adding new
// perms, add to bottom as to not change other perm
// values.
const (
PERM_NONE int = 1 << iota
PERM_ADMIN
PERM_REQUEST_CONTENT
PERM_REQUEST_CONTENT_AUTO_APPROVE
)
// uniqueIndex applied between Username and UserType, so same usernames can exist, but only with different types.
// This is incase different users with same name from different services try to signup.
type User struct {
GormModel
Username string `gorm:"uniqueIndex:usr_name_to_type;not null" json:"username" binding:"required"`
Password string `gorm:"not null" json:"password" binding:"required"`
AvatarID uint `json:"-"`
Avatar Image `json:"avatar"`
Bio string `json:"bio"`
// The type of user/which auth service they originate from.
// Empty if from Watcharr, or the name of the service (eg. jellyfin)
Type UserType `gorm:"uniqueIndex:usr_name_to_type;not null;default:0" json:"type"`
// ID of user from the third party service, this will be used purely for lookup of user at signin.
ThirdPartyID string `json:"-"`
// Auth token from third party (jellyfin)
ThirdPartyAuth string `json:"-"`
// Users third party integrations (minus jellyfin for now)
UserServices []UserServices `json:"-"`
Watched []Watched
// All Tags
Tags []Tag `json:"-"`
// Users permissions
Permissions int `gorm:"default:1" json:"-"`
// All user settings cols, in another struct for reusability
UserSettings
}
func (u *User) GetSafe() PublicUser {
return PublicUser{
ID: u.ID,
Username: u.Username,
Avatar: u.Avatar,
Bio: u.Bio,
}
}
// This struct uses pointer to the values, so in update user settings,
// we can tell which setting is being updated (if not nil..).
type UserSettings struct {
// Is profile private
Private *bool `gorm:"default:false" json:"private"`
// Are watched list content thoughts public (profile must also be public is false)
PrivateThoughts *bool `gorm:"default:false" json:"privateThoughts"`
// If ui 'spoilers' should be shown
HideSpoilers *bool `gorm:"default:false" json:"hideSpoilers"`
// If user wants previously watched items to show in 'Finished' filter,
// even if the watched item state has since been changed.
// Also if user wants to show in watched stats.
IncludePreviouslyWatched *bool `gorm:"default:false" json:"includePreviouslyWatched"`
// User's country to get correct content streaming providers.
Country *string `gorm:"default:'US'" json:"country"`
// Does the user want show, season and episode automations enabled.
AutomateShowStatuses *bool `gorm:"default:true" json:"automateShowStatuses"`
// Rating system user wants to use (frontend only).
// RatingSystem enum in frontend maxes out at 3, so just max=3 on this and we should be gut.
RatingSystem *int `json:"ratingSystem" binding:"omitempty,max=3"`
// Rating step for supported rating systems (frontend only, enum goes up to 2).
RatingStep *int `json:"ratingStep" binding:"omitempty,max=2"`
}
// Holds third party service auth tokens for users.
// Each service may use the fields in their own way.
// Unique index applied between service name and clientID
// to ensure no duplicates (no need to apply it against
// user_id, no accounts should share an integration).
//
// Plex:
// - AuthToken : Used for requests against plex.tv
// - AuthToken2 : Used for requests against home plex server.
type UserServices struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
// Service/integration name
Name string `gorm:"uniqueIndex:svc_name_to_cltid;not null;" json:"-"`
// The users id on the third party service
ClientID string `gorm:"uniqueIndex:svc_name_to_cltid;not null;" json:"-"`
AuthToken string `gorm:"not null;" json:"-"`
// Second auth token, generic name so future services can use it without extra confusion.
// Ex: We require a second auth token for use with our local server for Plex.
AuthToken2 string `json:"-"`
UserID uint `gorm:"not null;" json:"-"`
}
// We use a separate struct for registration to avoid confusion
// and possible accidents where we allow a user to pass in a
// property from the main User struct that shouldn't be allowed.
@@ -157,6 +55,11 @@ type AuthResponse struct {
Token string `json:"token"`
}
type UserPasswordUpdateRequest struct {
OldPassword string `json:"oldPassword" binding:"required"`
NewPassword string `json:"newPassword" binding:"required"`
}
type AvailableAuthProvidersResponse struct {
AvailableAuthProviders []string `json:"available"`
SignupEnabled bool `json:"signupEnabled"`
@@ -165,134 +68,33 @@ type AvailableAuthProvidersResponse struct {
HeaderAuthAutoLogin bool `json:"headerAuthAutoLogin"`
}
type ArgonParams struct {
memory uint32
iterations uint32
parallelism uint8
saltLength uint32
keyLength uint32
type PlexProvider interface {
FetchPlexAccountFromToken(token string) (plex.PlexUser, error)
GetPlexHomeServerAuthToken(plexAuth string, userClientId string) (string, error)
}
func GetPassArgonParams() *ArgonParams {
return &ArgonParams{
memory: 64 * 1024,
iterations: 3,
parallelism: 2,
saltLength: 16,
keyLength: 32,
type Service struct {
db *gorm.DB
cfg *config.ServerConfig
plexProvider PlexProvider
}
func NewService(db *gorm.DB, cfg *config.ServerConfig, plexProvider PlexProvider) *Service {
return &Service{
db,
cfg,
plexProvider,
}
}
type TokenClaims struct {
UserID uint `json:"userId"`
Username string `json:"username"`
Type UserType `json:"type"`
jwt.RegisteredClaims
}
type UserPasswordUpdateRequest struct {
OldPassword string `json:"oldPassword" binding:"required"`
NewPassword string `json:"newPassword" binding:"required"`
}
// Auth middleware
// If db is passed, extra user info from the database will be fetched.
func AuthRequired(db *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {
slog.Debug("AuthRequired middleware hit")
atoken := c.GetHeader("Authorization")
// Make sure auth header isn't empty
if atoken == "" {
slog.Warn("Returning 401, Authorization header not provided")
c.AbortWithStatus(401)
return
}
// Parse token
token, err := jwt.ParseWithClaims(atoken, &TokenClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(Config.JWT_SECRET), nil
})
if err != nil {
slog.Error("AuthRequired failed to parse token", "error", err)
c.AbortWithStatus(401)
return
}
// If token is valid, go to next handler
if claims, ok := token.Claims.(*TokenClaims); ok && token.Valid {
// Check if token issuedAt is from before `timeOfNewLoginRequired`.
// Basically just so we can logout old tokens and force relogin...
// since new changes require the user login again.
timeOfNewLoginRequired, _ := time.Parse(time.RFC822, "18 Aug 23 20:30 UTC")
if claims.IssuedAt.Before(timeOfNewLoginRequired) {
slog.Info("Token is from before timeOfNewLoginRequired.. returning 401", "token_issued_at", claims.IssuedAt, "time_of_new_login_required", timeOfNewLoginRequired)
c.AbortWithStatus(401)
return
}
slog.Debug("Token is valid", "claims", claims)
c.Set("userId", claims.UserID)
c.Set("userType", claims.Type)
// If db passed, get extra user info and set as variables in req context
if db != nil {
slog.Debug("AuthRequired: db passed.. getting extra user info")
dbUser := new(User)
res := db.Where("id = ?", claims.UserID).Take(&dbUser)
if res.Error != nil {
slog.Error("AuthRequired: Failed to select user from database", "error", res.Error)
c.AbortWithStatus(401)
return
}
slog.Debug("AuthRequired: fetched extra user info. Setting vars.", "userThirdPartyId", dbUser.ThirdPartyID, "userThirdPartyAuth", "lol this is censored dude")
c.Set("userThirdPartyId", dbUser.ThirdPartyID)
c.Set("userThirdPartyAuth", dbUser.ThirdPartyAuth)
c.Set("username", dbUser.Username)
c.Set("userPermissions", dbUser.Permissions)
}
c.Next()
} else {
slog.Error("Token is **not** valid")
c.AbortWithStatus(401)
return
}
}
}
// Admin only middleware (use after AuthRequired with extra info!)
func AdminRequired() gin.HandlerFunc {
return func(c *gin.Context) {
userId := c.GetUint("userId")
perms := c.GetInt("userPermissions")
if hasPermission(perms, PERM_ADMIN) {
slog.Debug("AdminRequired: User has permission to access admin only route", "user_id", userId)
c.Next()
return
}
slog.Info("AdminRequired: User denied permission to access admin only route", "user_id", userId)
c.AbortWithStatus(401)
}
}
// Specific perm only middleware (use after AuthRequired with extra info!)
func PermRequired(perm int) gin.HandlerFunc {
return func(c *gin.Context) {
userId := c.GetUint("userId")
perms := c.GetInt("userPermissions")
if hasPermission(perms, perm) {
slog.Debug("PermRequired: User has permission to access perm only route", "user_id", userId, "required_perm", perm)
c.Next()
return
}
slog.Info("PermRequired: User denied permission to access perm only route", "user_id", userId, "required_perm", perm)
c.AbortWithStatus(401)
}
}
func register(ur *UserRegisterRequest, initialPerm int, db *gorm.DB) (AuthResponse, error) {
if !Config.SIGNUP_ENABLED {
slog.Warn("Register called, but signing up is disabled.")
func (s *Service) Register(ur *UserRegisterRequest, initialPerm int) (AuthResponse, error) {
if !s.cfg.SIGNUP_ENABLED {
slog.Warn("Register: Register called, but signing up is disabled.")
return AuthResponse{}, errors.New("registering is disabled")
}
var user User = User{Username: ur.Username, Password: ur.Password}
slog.Info("A user is registering", "username", user.Username)
hash, err := hashPassword(user.Password, GetPassArgonParams())
var user entity.User = entity.User{Username: ur.Username, Password: ur.Password}
slog.Info("Register: A user is registering", "username", user.Username)
hash, err := s.hashPassword(user.Password, entity.GetPassArgonParams())
if err != nil {
log.Fatal(err)
}
@@ -301,14 +103,14 @@ func register(ur *UserRegisterRequest, initialPerm int, db *gorm.DB) (AuthRespon
user.Password = hash
// Update user permissions if an initial perm is passed in (1 is default)
if initialPerm != 0 && initialPerm != PERM_NONE {
slog.Info("User being registered has been given extra initial permissions", "initial_perm", initialPerm)
if initialPerm != 0 && initialPerm != entity.PERM_NONE {
slog.Info("Register: User being registered has been given extra initial permissions", "initial_perm", initialPerm)
user.Permissions = initialPerm
}
user.Country = &Config.DEFAULT_COUNTRY
user.Country = &s.cfg.DEFAULT_COUNTRY
res := db.Create(&user)
res := s.db.Create(&user)
if res.Error != nil {
// If error is because unique contraint failed.. user already exists
if res.Error == gorm.ErrDuplicatedKey {
@@ -326,7 +128,7 @@ func register(ur *UserRegisterRequest, initialPerm int, db *gorm.DB) (AuthRespon
return AuthResponse{}, errors.New("failed to get user id, try login")
}
token, err := signJWT(&user)
token, err := s.signJWT(&user)
if err != nil {
slog.Error("Registration: Failed to sign new jwt", "error", err)
return AuthResponse{}, errors.New("failed to get auth token")
@@ -334,10 +136,10 @@ func register(ur *UserRegisterRequest, initialPerm int, db *gorm.DB) (AuthRespon
return AuthResponse{Token: token}, nil
}
func registerFirstUser(user *UserRegisterRequest, db *gorm.DB) (AuthResponse, error) {
func (s *Service) RegisterFirstUser(urr *UserRegisterRequest) (AuthResponse, error) {
// Ensure no users exist
var userCount int64
uresp := db.Model(&User{}).Count(&userCount)
uresp := s.db.Model(&entity.User{}).Count(&userCount)
if uresp.Error != nil {
slog.Error("registerFirstUser: User count query failed!", "error", uresp.Error)
return AuthResponse{}, errors.New("failed to query db for a count of users")
@@ -347,19 +149,19 @@ func registerFirstUser(user *UserRegisterRequest, db *gorm.DB) (AuthResponse, er
return AuthResponse{}, errors.New("first user already registered")
}
slog.Info("Registering first user.")
return register(user, PERM_ADMIN, db)
return s.Register(urr, entity.PERM_ADMIN)
}
func login(user *User, db *gorm.DB) (AuthResponse, error) {
slog.Debug("A User Is Logging In", "username", user.Username)
dbUser := new(User)
res := db.Where("username = ? AND (type IS NULL OR type = 0)", user.Username).Take(&dbUser)
func (s *Service) Login(userL *entity.User) (AuthResponse, error) {
slog.Debug("A User Is Logging In", "username", userL.Username)
dbUser := new(entity.User)
res := s.db.Where("username = ? AND (type IS NULL OR type = 0)", userL.Username).Take(&dbUser)
if res.Error != nil {
slog.Error("Failed to select user from database for login", "error", res.Error)
return AuthResponse{}, errors.New("User does not exist")
}
match, err := compareHash(user.Password, dbUser.Password)
match, err := s.compareHash(userL.Password, dbUser.Password)
if err != nil {
slog.Error("Failed to compare pass to hash for login", "error", err)
return AuthResponse{}, errors.New("failed to login")
@@ -369,7 +171,7 @@ func login(user *User, db *gorm.DB) (AuthResponse, error) {
return AuthResponse{}, errors.New("incorrect details")
}
token, err := signJWT(dbUser)
token, err := s.signJWT(dbUser)
if err != nil {
slog.Error("Failed to sign new jwt", "error", err)
return AuthResponse{}, errors.New("failed to get auth token")
@@ -377,20 +179,20 @@ func login(user *User, db *gorm.DB) (AuthResponse, error) {
return AuthResponse{Token: token}, nil
}
func loginJellyfin(user *User, db *gorm.DB) (AuthResponse, error) {
if Config.JELLYFIN_HOST == "" {
func (s *Service) LoginJellyfin(userL *entity.User) (AuthResponse, error) {
if s.cfg.JELLYFIN_HOST == "" {
slog.Error("Request made to login via Jellyfin, but JELLYFIN_HOST has not been configured.")
return AuthResponse{}, errors.New("jellyfin login not enabled")
}
base, err := url.Parse(Config.JELLYFIN_HOST + "/Users/AuthenticateByName")
base, err := url.Parse(s.cfg.JELLYFIN_HOST + "/Users/AuthenticateByName")
if err != nil {
slog.Error("Failed to parse AuthenticateByName api endpoint url", "error", err.Error())
return AuthResponse{}, errors.New("failed to parse api uri")
}
// Marshall struct as json
usrJSON, err := json.Marshal(JellyfinAuth{Username: user.Username, Pw: user.Password})
usrJSON, err := json.Marshal(JellyfinAuth{Username: userL.Username, Pw: userL.Password})
if err != nil {
slog.Error("Error marshalling JellyfinAuth JSON", "error", err.Error())
return AuthResponse{}, errors.New("failed to marshal json")
@@ -403,7 +205,7 @@ func loginJellyfin(user *User, db *gorm.DB) (AuthResponse, error) {
return AuthResponse{}, errors.New("request failed")
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("X-Emby-Authorization", "MediaBrowser Client=\"Watcharr\", Device=\"HTTP\", DeviceId=\"WatcharrFor"+user.Username+"\", Version=\"10.8.0\"")
req.Header.Add("X-Emby-Authorization", "MediaBrowser Client=\"Watcharr\", Device=\"HTTP\", DeviceId=\"WatcharrFor"+userL.Username+"\", Version=\"10.8.0\"")
res, err := client.Do(req)
if err != nil {
slog.Error("making request to jellyfin for auth failed", "error", err)
@@ -429,8 +231,8 @@ func loginJellyfin(user *User, db *gorm.DB) (AuthResponse, error) {
return AuthResponse{}, errors.New("jellyfin returned empty user id")
}
dbUser := new(User)
dbRes := db.Where("third_party_id = ? AND type = ?", resp.User.ID, JELLYFIN_USER).Take(&dbUser)
dbUser := new(entity.User)
dbRes := s.db.Where("third_party_id = ? AND type = ?", resp.User.ID, entity.JELLYFIN_USER).Take(&dbUser)
if dbRes.Error != nil {
if errors.Is(dbRes.Error, gorm.ErrRecordNotFound) {
// Record not found, so we should create the user
@@ -438,10 +240,10 @@ func loginJellyfin(user *User, db *gorm.DB) (AuthResponse, error) {
dbUser.ThirdPartyID = resp.User.ID
dbUser.ThirdPartyAuth = resp.AccessToken
dbUser.Username = resp.User.Name
dbUser.Type = JELLYFIN_USER
dbUser.Country = &Config.DEFAULT_COUNTRY
dbUser.Type = entity.JELLYFIN_USER
dbUser.Country = &s.cfg.DEFAULT_COUNTRY
dbRes = db.Create(&dbUser)
dbRes = s.db.Create(&dbUser)
if dbRes.Error != nil {
slog.Error("Failed to create new user in db from jellyfin response", "error", dbRes.Error)
return AuthResponse{}, errors.New("failed to create new user from jellyfin")
@@ -454,10 +256,10 @@ func loginJellyfin(user *User, db *gorm.DB) (AuthResponse, error) {
if resp.AccessToken != "" {
slog.Debug("Jellyfin user login - updating user with new access token")
dbUser.ThirdPartyAuth = resp.AccessToken
db.Save(&dbUser)
s.db.Save(&dbUser)
}
token, err := signJWT(dbUser)
token, err := s.signJWT(dbUser)
if err != nil {
slog.Error("Failed to sign new (jellyfin login) jwt", "error", err)
return AuthResponse{}, errors.New("failed to get auth token")
@@ -466,13 +268,13 @@ func loginJellyfin(user *User, db *gorm.DB) (AuthResponse, error) {
}
// Login via Plex.
func loginPlex(lr *PlexLoginRequest, db *gorm.DB) (AuthResponse, error) {
if Config.PLEX_HOST == "" || Config.PLEX_MACHINE_ID == "" {
func (s *Service) LoginPlex(lr *plex.PlexLoginRequest) (AuthResponse, error) {
if s.cfg.PLEX_HOST == "" || s.cfg.PLEX_MACHINE_ID == "" {
slog.Error("Request made to login via Plex, but Plex authentication is disabled")
return AuthResponse{}, errors.New("plex login not enabled")
}
slog.Debug("A Plex User Is Logging In")
account, err := fetchPlexAccountFromToken(lr.AuthToken)
account, err := s.plexProvider.FetchPlexAccountFromToken(lr.AuthToken)
if err != nil {
slog.Error("loginPlex: Could not fetch Plex account", "error", err)
return AuthResponse{}, errors.New("could not fetch plex acount")
@@ -483,27 +285,27 @@ func loginPlex(lr *PlexLoginRequest, db *gorm.DB) (AuthResponse, error) {
}
// Get users auth token against our home plex server.
// If no auth token, assume they don't have access to our plex server.
homeAuthToken, err := getPlexHomeServerAuthToken(lr.AuthToken, lr.ClientIdentifier)
homeAuthToken, err := s.plexProvider.GetPlexHomeServerAuthToken(lr.AuthToken, lr.ClientIdentifier)
if err != nil || homeAuthToken == "" {
slog.Error("loginPlex: Failed to get home server auth token for user! If not because the request failed, then ensure the user has access to our home servers library.", "error", err)
return AuthResponse{}, errors.New("failed to verify plex access")
}
dbUser := new(User)
userIdQ := db.Select("user_id").Where("name = ? AND client_id = ?", "plex", account.Id).Table("user_services")
dbRes := db.Where("type = ?", PLEX_USER).Where("id = (?)", userIdQ).Preload("UserServices").Take(&dbUser)
dbUser := new(entity.User)
userIdQ := s.db.Select("user_id").Where("name = ? AND client_id = ?", "plex", account.Id).Table("user_services")
dbRes := s.db.Where("type = ?", entity.PLEX_USER).Where("id = (?)", userIdQ).Preload("UserServices").Take(&dbUser)
if dbRes.Error != nil {
if errors.Is(dbRes.Error, gorm.ErrRecordNotFound) {
slog.Debug("loginPlex: New plex user attempted login.. creating Watcharr account now.")
dbUser.Username = account.Username
dbUser.Type = PLEX_USER
dbUser.UserServices = append(dbUser.UserServices, UserServices{
dbUser.Type = entity.PLEX_USER
dbUser.UserServices = append(dbUser.UserServices, entity.UserServices{
Name: "plex",
ClientID: strconv.FormatUint(account.Id, 10),
AuthToken: lr.AuthToken,
AuthToken2: homeAuthToken,
})
dbUser.Country = &Config.DEFAULT_COUNTRY
dbRes = db.Create(&dbUser)
dbUser.Country = &s.cfg.DEFAULT_COUNTRY
dbRes = s.db.Create(&dbUser)
if dbRes.Error != nil {
slog.Error("loginPlex: Failed to create new user in db from plex response", "error", dbRes.Error)
return AuthResponse{}, errors.New("failed to create new user from plex")
@@ -524,9 +326,9 @@ func loginPlex(lr *PlexLoginRequest, db *gorm.DB) (AuthResponse, error) {
break
}
}
db.Save(&dbUser.UserServices)
s.db.Save(&dbUser.UserServices)
}
token, err := signJWT(dbUser)
token, err := s.signJWT(dbUser)
if err != nil {
slog.Error("loginPlex: Failed to sign new jwt", "error", err)
return AuthResponse{}, errors.New("failed to get auth token")
@@ -534,19 +336,20 @@ func loginPlex(lr *PlexLoginRequest, db *gorm.DB) (AuthResponse, error) {
return AuthResponse{Token: token}, nil
}
func useAdminToken(req *UseAdminTokenRequest, db *gorm.DB, userId uint) error {
var dbToken Token
resp := db.Where("value = ?", req.Token).Take(&dbToken)
// TODO the logic that gets and validated a token should be moved to Token service.
func (s *Service) UseAdminToken(req *UseAdminTokenRequest, userId uint) error {
var dbToken entity.Token
resp := s.db.Where("value = ?", req.Token).Take(&dbToken)
if resp.Error != nil {
slog.Info("useAdminToken failed", "error", "token not found in db")
return errors.New("invalid token")
}
if dbToken.Type != TOKENTYPE_ADMIN {
slog.Info("useAdminToken failed", "error", "token is of wrong type", "type_wanted", TOKENTYPE_ADMIN, "type_actual", dbToken.Type)
if dbToken.Type != entity.TOKENTYPE_ADMIN {
slog.Info("useAdminToken failed", "error", "token is of wrong type", "type_wanted", entity.TOKENTYPE_ADMIN, "type_actual", dbToken.Type)
return errors.New("invalid token")
}
dur := time.Since(dbToken.CreatedAt)
if dur > tokenMaxAge {
if dur > token.TokenMaxAge {
slog.Info("useAdminToken failed", "error", "token in db has expired")
return errors.New("invalid token")
}
@@ -556,13 +359,13 @@ func useAdminToken(req *UseAdminTokenRequest, db *gorm.DB, userId uint) error {
}
// Token is valid and for current user.. give user admin.
// Incase removing the token after used fails, this is in a transaction so user wont be admin.
err := db.Transaction(func(tx *gorm.DB) error {
err := s.db.Transaction(func(tx *gorm.DB) error {
// Give user admin
if err := tx.Model(&User{}).Where("id = ?", userId).Update("permissions", PERM_ADMIN).Error; err != nil {
if err := tx.Model(&entity.User{}).Where("id = ?", userId).Update("permissions", entity.PERM_ADMIN).Error; err != nil {
return err
}
// Delete used token
if err := tx.Where("value = ?", req.Token).Delete(&Token{}).Error; err != nil {
if err := tx.Where("value = ?", req.Token).Delete(&entity.Token{}).Error; err != nil {
return err
}
// commit transaction if no errors
@@ -575,13 +378,13 @@ func useAdminToken(req *UseAdminTokenRequest, db *gorm.DB, userId uint) error {
return nil
}
func signJWT(user *User) (token string, err error) {
func (s *Service) signJWT(user *entity.User) (token string, err error) {
// Create new jwt with claim data
jwt := jwt.NewWithClaims(jwt.SigningMethodHS256, TokenClaims{
user.ID,
user.Username,
user.Type,
jwt.RegisteredClaims{
jwt := jwt.NewWithClaims(jwt.SigningMethodHS256, entity.TokenClaims{
UserID: user.ID,
Username: user.Username,
Type: user.Type,
RegisteredClaims: jwt.RegisteredClaims{
// ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)),
IssuedAt: jwt.NewNumericDate(time.Now()),
Issuer: "watcharr",
@@ -589,28 +392,43 @@ func signJWT(user *User) (token string, err error) {
})
// Sign and get the complete encoded token as a string using the secret
return jwt.SignedString([]byte(Config.JWT_SECRET))
return jwt.SignedString([]byte(s.cfg.JWT_SECRET))
}
func hashPassword(password string, p *ArgonParams) (encodedHash string, err error) {
salt, err := generateRandomBytes(p.saltLength)
func (s *Service) hashPassword(password string, p *entity.ArgonParams) (encodedHash string, err error) {
salt, err := s.generateRandomBytes(p.SaltLength)
if err != nil {
return "", err
}
hash := argon2.IDKey([]byte(password), salt, p.iterations, p.memory, p.parallelism, p.keyLength)
hash := argon2.IDKey(
[]byte(password),
salt,
p.Iterations,
p.Memory,
p.Parallelism,
p.KeyLength,
)
// Base64 encode the salt and hashed password.
b64Salt := base64.RawStdEncoding.EncodeToString(salt)
b64Hash := base64.RawStdEncoding.EncodeToString(hash)
// Format hash in standard way.
encodedHash = fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s", argon2.Version, p.memory, p.iterations, p.parallelism, b64Salt, b64Hash)
encodedHash = fmt.Sprintf(
"$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
argon2.Version,
p.Memory,
p.Iterations,
p.Parallelism,
b64Salt,
b64Hash,
)
return encodedHash, nil
}
func generateRandomBytes(n uint32) ([]byte, error) {
func (s *Service) generateRandomBytes(n uint32) ([]byte, error) {
b := make([]byte, n)
_, err := rand.Read(b)
if err != nil {
@@ -620,16 +438,23 @@ func generateRandomBytes(n uint32) ([]byte, error) {
return b, nil
}
func compareHash(password, encodedHash string) (match bool, err error) {
func (s *Service) compareHash(password, encodedHash string) (match bool, err error) {
// Extract the parameters, salt and derived key from the encoded password
// hash.
p, salt, hash, err := decodeHash(encodedHash)
p, salt, hash, err := s.decodeHash(encodedHash)
if err != nil {
return false, err
}
// Derive the key from the other password using the same parameters.
otherHash := argon2.IDKey([]byte(password), salt, p.iterations, p.memory, p.parallelism, p.keyLength)
otherHash := argon2.IDKey(
[]byte(password),
salt,
p.Iterations,
p.Memory,
p.Parallelism,
p.KeyLength,
)
// Check that the contents of the hashed passwords are identical. Note
// that we are using the subtle.ConstantTimeCompare() function for this
@@ -640,7 +465,7 @@ func compareHash(password, encodedHash string) (match bool, err error) {
return false, nil
}
func decodeHash(encodedHash string) (p *ArgonParams, salt, hash []byte, err error) {
func (s *Service) decodeHash(encodedHash string) (p *entity.ArgonParams, salt, hash []byte, err error) {
vals := strings.Split(encodedHash, "$")
if len(vals) != 6 {
return nil, nil, nil, errors.New("the encoded hash is not in the correct format")
@@ -655,8 +480,8 @@ func decodeHash(encodedHash string) (p *ArgonParams, salt, hash []byte, err erro
return nil, nil, nil, errors.New("incompatible version of argon2")
}
p = &ArgonParams{}
_, err = fmt.Sscanf(vals[3], "m=%d,t=%d,p=%d", &p.memory, &p.iterations, &p.parallelism)
p = &entity.ArgonParams{}
_, err = fmt.Sscanf(vals[3], "m=%d,t=%d,p=%d", &p.Memory, &p.Iterations, &p.Parallelism)
if err != nil {
return nil, nil, nil, err
}
@@ -665,35 +490,27 @@ func decodeHash(encodedHash string) (p *ArgonParams, salt, hash []byte, err erro
if err != nil {
return nil, nil, nil, err
}
p.saltLength = uint32(len(salt))
p.SaltLength = uint32(len(salt))
hash, err = base64.RawStdEncoding.Strict().DecodeString(vals[5])
if err != nil {
return nil, nil, nil, err
}
p.keyLength = uint32(len(hash))
p.KeyLength = uint32(len(hash))
return p, salt, hash, nil
}
func hasPermission(perms int, reqPerm int) bool {
// Admins have permission for everything.
if perms&PERM_ADMIN == PERM_ADMIN {
return true
}
return (perms & reqPerm) == reqPerm
}
func userChangePassword(db *gorm.DB, pwds UserPasswordUpdateRequest, userId uint) error {
func (s *Service) UserChangePassword(pwds UserPasswordUpdateRequest, userId uint) error {
slog.Debug("userChangePassword request running", "user_id", userId)
user := new(User)
res := db.Where("id = ?", userId).Select("password").Take(&user)
user := new(entity.User)
res := s.db.Where("id = ?", userId).Select("password").Take(&user)
if res.Error != nil {
slog.Error("userChangePassword failed - failed to retrieve user from database", "user_id", userId, "error", res.Error)
return errors.New("failed to retrieve user")
}
slog.Debug("userChangePassword user found", "user_id", userId)
match, err := compareHash(pwds.OldPassword, user.Password)
match, err := s.compareHash(pwds.OldPassword, user.Password)
if err != nil {
slog.Error("userChangePassword failed - failed to compare passwords", "user_id", userId, "error", err)
return errors.New("failed to compare passwords")
@@ -704,13 +521,13 @@ func userChangePassword(db *gorm.DB, pwds UserPasswordUpdateRequest, userId uint
}
slog.Debug("userChangePassword hash for current password matches hash in the database", "user_id", userId)
slog.Debug("userChangePassword hashing new password", "user_id", userId)
hash, err := hashPassword(pwds.NewPassword, GetPassArgonParams())
hash, err := s.hashPassword(pwds.NewPassword, entity.GetPassArgonParams())
if err != nil {
slog.Error("userChangePassword failed - failed to hash new password", "user_id", userId, "error", err)
return errors.New("failed to hash new password")
}
slog.Debug("userChangePassword new password hashed", "user_id", userId)
if err := db.Model(&User{}).Where("id = ?", userId).Update("password", hash).Error; err != nil {
if err := s.db.Model(&entity.User{}).Where("id = ?", userId).Update("password", hash).Error; err != nil {
slog.Error("userChangePassword failed - failed to update password in database", "user_id", userId, "error", err)
return errors.New("failed to update password")
} else {
@@ -4,46 +4,44 @@
// a header for auth, so this should only be configured if you are
// certain your watcharr instance is only available behind your proxy.
package main
package auth
import (
"errors"
"log/slog"
"github.com/sbondCo/Watcharr/config"
"github.com/sbondCo/Watcharr/database/entity"
"gorm.io/gorm"
)
type TrustedHeaderAuthSetting struct {
// Required: Should header auth be enabled?
// This bool exists so header auth can be toggled
// easily without having to remove configuration.
// To be actually enabled, HEADER_NAME must also
// be set.
Enabled bool `json:"enabled"`
// Required: What is the name of the trusted header
// that will contain the logged in users username?
HeaderName string `json:"headerName"`
// Should the frontend attempt auto login if
// trusted header auth is enabled.
AutoLogin bool `json:"autoLogin"`
// Where can we redirect the user to logout
// of the auth service?
LogoutUrl string `json:"logoutUrl"`
}
type TrustedHeaderAuthLogoutDetailsResponse struct {
LogoutUrl string `json:"logoutUrl,omitempty"`
}
// Is trusted header auth configured on this server?
func trustedHeaderAuthIsEnabled() bool {
return Config.HEADER_AUTH.Enabled && Config.HEADER_AUTH.HeaderName != ""
type TrustedHeaderService struct {
db *gorm.DB
cfg *config.ServerConfig
authService *Service
}
func setTrustedHeaderAuthSetting(has TrustedHeaderAuthSetting) error {
func NewTrustedHeaderService(db *gorm.DB, cfg *config.ServerConfig, authService *Service) *TrustedHeaderService {
return &TrustedHeaderService{
db,
cfg,
authService,
}
}
// Is trusted header auth configured on this server?
func (s *TrustedHeaderService) TrustedHeaderAuthIsEnabled() bool {
return s.cfg.HEADER_AUTH.Enabled && s.cfg.HEADER_AUTH.HeaderName != ""
}
func (s *TrustedHeaderService) SetTrustedHeaderAuthSetting(has config.TrustedHeaderAuthSetting) error {
slog.Debug("setTrustedHeaderAuthSetting: Attempting to update to new provided value", "new_value", has)
Config.HEADER_AUTH = has
err := writeConfig()
s.cfg.HEADER_AUTH = has
err := s.cfg.Write()
if err != nil {
slog.Error("setTrustedHeaderAuthSetting: Failed to write updated config!", "error", err)
return errors.New("failed to write config")
@@ -54,27 +52,27 @@ func setTrustedHeaderAuthSetting(has TrustedHeaderAuthSetting) error {
// Gets proxy logout details.
// Details are accessible to any user for the logout flow.
// If proxy configured should be checked before using this.
func getTrustedHeaderAuthLogoutDetails() *TrustedHeaderAuthLogoutDetailsResponse {
func (s *TrustedHeaderService) GetTrustedHeaderAuthLogoutDetails() *TrustedHeaderAuthLogoutDetailsResponse {
return &TrustedHeaderAuthLogoutDetailsResponse{
LogoutUrl: Config.HEADER_AUTH.LogoutUrl,
LogoutUrl: s.cfg.HEADER_AUTH.LogoutUrl,
}
}
// Login via header sso
func loginTrustedHeaderAuth(user *User, db *gorm.DB) (AuthResponse, error) {
func (s *TrustedHeaderService) LoginTrustedHeaderAuth(user *entity.User) (AuthResponse, error) {
slog.Debug("loginTrustedHeaderAuth: A user is logging in", "username_from_header", user.Username)
dbUser := new(User)
res := db.Where("username = ? AND type = ?", user.Username, PROXY_USER).Take(&dbUser)
dbUser := new(entity.User)
res := s.db.Where("username = ? AND type = ?", user.Username, entity.PROXY_USER).Take(&dbUser)
if res.Error != nil {
if errors.Is(res.Error, gorm.ErrRecordNotFound) {
slog.Info("loginTrustedHeaderAuth: Creating new User from authentication header", "username_from_header", user.Username)
// Record not found, so we should create the user (if configured to do so)
// dbUser will be empty, so we can just reuse it for this purpose.
dbUser.Username = user.Username
dbUser.Type = PROXY_USER
dbUser.Country = &Config.DEFAULT_COUNTRY
dbUser.Type = entity.PROXY_USER
dbUser.Country = &s.cfg.DEFAULT_COUNTRY
res = db.Create(&dbUser)
res = s.db.Create(&dbUser)
if res.Error != nil {
slog.Error("loginTrustedHeaderAuth: Failed to create new user in db", "error", res.Error)
return AuthResponse{}, errors.New("failed to create new user")
@@ -84,7 +82,7 @@ func loginTrustedHeaderAuth(user *User, db *gorm.DB) (AuthResponse, error) {
return AuthResponse{}, errors.New("error locating user in db")
}
}
token, err := signJWT(dbUser)
token, err := s.authService.signJWT(dbUser)
if err != nil {
slog.Error("loginTrustedHeaderAuth: Failed to sign new jwt", "error", err)
return AuthResponse{}, errors.New("failed to get auth token")
@@ -0,0 +1,106 @@
package authmiddleware
import (
"log/slog"
"time"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"github.com/sbondCo/Watcharr/config"
"github.com/sbondCo/Watcharr/database/entity"
"github.com/sbondCo/Watcharr/feature/auth/permission"
"gorm.io/gorm"
)
// Auth middleware
// If db is passed, extra user info from the database will be fetched.
func AuthRequired(db *gorm.DB, cfg *config.ServerConfig) gin.HandlerFunc {
return func(c *gin.Context) {
slog.Debug("AuthRequired middleware hit")
atoken := c.GetHeader("Authorization")
// Make sure auth header isn't empty
if atoken == "" {
slog.Warn("Returning 401, Authorization header not provided")
c.AbortWithStatus(401)
return
}
// Parse token
token, err := jwt.ParseWithClaims(atoken, &entity.TokenClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(cfg.JWT_SECRET), nil
})
if err != nil {
slog.Error("AuthRequired failed to parse token", "error", err)
c.AbortWithStatus(401)
return
}
// If token is valid, go to next handler
if claims, ok := token.Claims.(*entity.TokenClaims); ok && token.Valid {
// Check if token issuedAt is from before `timeOfNewLoginRequired`.
// Basically just so we can logout old tokens and force relogin...
// since new changes require the user login again.
timeOfNewLoginRequired, _ := time.Parse(time.RFC822, "18 Aug 23 20:30 UTC")
if claims.IssuedAt.Before(timeOfNewLoginRequired) {
slog.Info("Token is from before timeOfNewLoginRequired.. returning 401", "token_issued_at", claims.IssuedAt, "time_of_new_login_required", timeOfNewLoginRequired)
c.AbortWithStatus(401)
return
}
slog.Debug("Token is valid", "claims", claims)
c.Set("userId", claims.UserID)
c.Set("userType", claims.Type)
// If db passed, get extra user info and set as variables in req context
if db != nil {
slog.Debug("AuthRequired: db passed.. getting extra user info")
dbUser := new(entity.User)
res := db.Where("id = ?", claims.UserID).Take(&dbUser)
if res.Error != nil {
slog.Error("AuthRequired: Failed to select user from database", "error", res.Error)
c.AbortWithStatus(401)
return
}
slog.Debug("AuthRequired: fetched extra user info. Setting vars.", "userThirdPartyId", dbUser.ThirdPartyID, "userThirdPartyAuth", "lol this is censored dude")
c.Set("userThirdPartyId", dbUser.ThirdPartyID)
c.Set("userThirdPartyAuth", dbUser.ThirdPartyAuth)
c.Set("username", dbUser.Username)
c.Set("userPermissions", dbUser.Permissions)
if dbUser.Country != nil {
c.Set("userCountry", *dbUser.Country)
}
}
c.Next()
} else {
slog.Error("Token is **not** valid")
c.AbortWithStatus(401)
return
}
}
}
// Admin only middleware (use after AuthRequired with extra info!)
func AdminRequired() gin.HandlerFunc {
return func(c *gin.Context) {
userId := c.GetUint("userId")
perms := c.GetInt("userPermissions")
if permission.Has(perms, entity.PERM_ADMIN) {
slog.Debug("AdminRequired: User has permission to access admin only route", "user_id", userId)
c.Next()
return
}
slog.Info("AdminRequired: User denied permission to access admin only route", "user_id", userId)
c.AbortWithStatus(401)
}
}
// Specific perm only middleware (use after AuthRequired with extra info!)
func PermRequired(perm int) gin.HandlerFunc {
return func(c *gin.Context) {
userId := c.GetUint("userId")
perms := c.GetInt("userPermissions")
if permission.Has(perms, perm) {
slog.Debug("PermRequired: User has permission to access perm only route", "user_id", userId, "required_perm", perm)
c.Next()
return
}
slog.Info("PermRequired: User denied permission to access perm only route", "user_id", userId, "required_perm", perm)
c.AbortWithStatus(401)
}
}
@@ -0,0 +1,12 @@
package permission
import "github.com/sbondCo/Watcharr/database/entity"
// If `perms` has `req(uired)Perm`.
func Has(perms int, reqPerm int) bool {
// Admins have permission for everything.
if perms&entity.PERM_ADMIN == entity.PERM_ADMIN {
return true
}
return (perms & reqPerm) == reqPerm
}
+224
View File
@@ -0,0 +1,224 @@
package auth
import (
"log/slog"
"net/http"
"github.com/gin-gonic/gin"
"github.com/sbondCo/Watcharr/database/entity"
"github.com/sbondCo/Watcharr/feature/auth/authmiddleware"
"github.com/sbondCo/Watcharr/feature/plex"
"github.com/sbondCo/Watcharr/feature/setup/setupglob"
"github.com/sbondCo/Watcharr/router"
"github.com/sbondCo/Watcharr/token"
)
type Router struct {
br *router.BaseRouter
service *Service
trustedHeaderService *TrustedHeaderService
}
func NewRouter(br *router.BaseRouter, service *Service, trustedHeaderService *TrustedHeaderService) *Router {
return &Router{
br,
service,
trustedHeaderService,
}
}
func (r *Router) AddRoutes() {
auth := r.br.Router.Group("/auth")
// Login
auth.POST("/", r.Login)
// Jellyfin login
auth.POST("/jellyfin", r.LoginJellyfin)
// Plex login
auth.POST("/plex", r.LoginPlex)
// Proxy Login
auth.POST("/proxy", r.LoginProxy)
// Register
auth.POST("/register", r.Register)
// Get available auth providers
auth.GET("/available", r.GetAvailableAuthProviders)
// IMPORTANT: Routes below here must be authenticated.
auth.Use(authmiddleware.AuthRequired(nil, r.br.Cfg))
{
// Request details for logout process for proxy users.
// Any proxy user can request this for logout.
auth.GET("/proxy_logout_details", r.GetProxyLogoutDetails)
// Request admin token
auth.GET("/admin_token", r.GetAdminToken)
// Use admin token
auth.POST("/admin_token", r.UseAdminToken)
// Change password
auth.POST("/change_password", r.UpdateUserPassword)
}
}
// Login
func (r *Router) Login(c *gin.Context) {
var user entity.User
if c.ShouldBindJSON(&user) == nil {
response, err := r.service.Login(&user)
if err != nil {
c.JSON(http.StatusForbidden, router.ErrorResponse{Error: err.Error()})
return
}
c.JSON(http.StatusOK, response)
return
}
c.Status(400)
}
// Jellyfin login
func (r *Router) LoginJellyfin(c *gin.Context) {
var user entity.User
if c.ShouldBindJSON(&user) == nil {
response, err := r.service.LoginJellyfin(&user)
if err != nil {
c.JSON(http.StatusForbidden, router.ErrorResponse{Error: err.Error()})
return
}
c.JSON(http.StatusOK, response)
return
}
c.Status(400)
}
// Plex login
func (r *Router) LoginPlex(c *gin.Context) {
var plexRequest plex.PlexLoginRequest
if c.ShouldBindJSON(&plexRequest) == nil {
response, err := r.service.LoginPlex(&plexRequest)
if err != nil {
c.JSON(http.StatusForbidden, router.ErrorResponse{Error: err.Error()})
return
}
c.JSON(http.StatusOK, response)
return
}
c.Status(400)
}
// Proxy Login
func (r *Router) LoginProxy(c *gin.Context) {
var user entity.User
if !r.trustedHeaderService.TrustedHeaderAuthIsEnabled() {
slog.Error("ProxyLogin: SSO has not been configured.")
c.JSON(http.StatusForbidden, router.ErrorResponse{Error: "proxy authentication is disabled"})
return
}
user.Username = c.GetHeader(r.br.Cfg.HEADER_AUTH.HeaderName)
if user.Username == "" {
slog.Error("ProxyLogin: Authentication header is missing.")
c.JSON(http.StatusForbidden, router.ErrorResponse{Error: "authentication header missing"})
return
}
response, err := r.trustedHeaderService.LoginTrustedHeaderAuth(&user)
if err != nil {
c.JSON(http.StatusForbidden, router.ErrorResponse{Error: err.Error()})
return
}
c.JSON(http.StatusOK, response)
}
// Register
func (r *Router) Register(c *gin.Context) {
var user UserRegisterRequest
if c.ShouldBindJSON(&user) == nil {
response, err := r.service.Register(&user, entity.PERM_NONE)
if err != nil {
c.JSON(http.StatusForbidden, router.ErrorResponse{Error: err.Error()})
return
}
c.JSON(http.StatusOK, response)
return
}
c.Status(400)
}
// Get available auth providers
func (r *Router) GetAvailableAuthProviders(c *gin.Context) {
resp := &AvailableAuthProvidersResponse{
AvailableAuthProviders: []string{},
SignupEnabled: r.br.Cfg.SIGNUP_ENABLED,
IsInSetup: setupglob.ServerInSetup,
UseEmby: r.br.Cfg.USE_EMBY,
}
if r.br.Cfg.JELLYFIN_HOST != "" {
resp.AvailableAuthProviders = append(resp.AvailableAuthProviders, "jellyfin")
}
if r.br.Cfg.PLEX_HOST != "" && r.br.Cfg.PLEX_MACHINE_ID != "" {
resp.AvailableAuthProviders = append(resp.AvailableAuthProviders, "plex")
}
if r.trustedHeaderService.TrustedHeaderAuthIsEnabled() {
resp.AvailableAuthProviders = append(resp.AvailableAuthProviders, "header")
resp.HeaderAuthAutoLogin = r.br.Cfg.HEADER_AUTH.AutoLogin
}
c.JSON(http.StatusOK, resp)
}
// Request details for logout process for proxy users.
// Any proxy user can request this for logout.
func (r *Router) GetProxyLogoutDetails(c *gin.Context) {
if !r.trustedHeaderService.TrustedHeaderAuthIsEnabled() {
slog.Error("GetProxy: SSO has not been configured.")
c.JSON(http.StatusForbidden, router.ErrorResponse{Error: "proxy authentication is disabled"})
return
}
userType := c.MustGet("userType").(entity.UserType)
if userType != entity.PROXY_USER {
slog.Error("GetProxy: Non proxy user attempted to fetch proxy logout details.")
c.JSON(http.StatusForbidden, router.ErrorResponse{Error: "you are not a proxy user"})
return
}
c.JSON(http.StatusOK, r.trustedHeaderService.GetTrustedHeaderAuthLogoutDetails())
}
// Request admin token
func (r *Router) GetAdminToken(c *gin.Context) {
userId := c.MustGet("userId").(uint)
token, err := token.CreateOneUseToken(r.br.DB, entity.TOKENTYPE_ADMIN, userId)
if err != nil {
c.JSON(http.StatusForbidden, router.ErrorResponse{Error: err.Error()})
return
}
slog.Info("Admin token generated. Type this token into the web ui to gain admin access on your account.", "token", token, "generated_for", userId)
c.Status(http.StatusNoContent)
}
// Use admin token
func (r *Router) UseAdminToken(c *gin.Context) {
userId := c.MustGet("userId").(uint)
var atr UseAdminTokenRequest
if c.ShouldBindJSON(&atr) == nil {
err := r.service.UseAdminToken(&atr, userId)
if err != nil {
c.JSON(http.StatusForbidden, router.ErrorResponse{Error: err.Error()})
return
}
c.Status(http.StatusNoContent)
return
}
c.Status(400)
}
// Change password
func (r *Router) UpdateUserPassword(c *gin.Context) {
userId := c.MustGet("userId").(uint)
var pwds UserPasswordUpdateRequest
err := c.ShouldBindJSON(&pwds)
if err == nil {
err := r.service.UserChangePassword(pwds, userId)
if err != nil {
c.JSON(http.StatusForbidden, router.ErrorResponse{Error: err.Error()})
return
}
c.Status(http.StatusOK)
return
}
c.AbortWithStatusJSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
}
+1
View File
@@ -0,0 +1 @@
This is a bit confusing, but `content` only refers to tmdb data at this time. This is mostly because of how this was named when the code was first written, the name is fine once understood: content is for tv/movie/actor and any other modules will be named what they are for specifically (ie: game)
+652
View File
@@ -0,0 +1,652 @@
package content
import (
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"os"
"path"
"strconv"
"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"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
// inmemory content cache
var ContentStore = gocache.New(time.Hour*24, time.Minute)
// Download file over http (used for downloading poster images)
// url - The remote file url.
// outf - Where should we store the downloaded file.
// force - Should we overwrite an existing file? If false, existing files will be skipped.
func download(url string, outf string, force bool) (err error) {
slog.Debug("download: Attempting to download file", "url", url, "outf", outf, "force", force)
// If not forced, skip call if file already exists to save unnecessary requests.
if !force {
if _, err := os.Stat(outf); !errors.Is(err, os.ErrNotExist) {
slog.Debug("download: Skipping file, it already exists locally.", "outf", outf, "error", err)
return nil
} else {
slog.Debug("download: Continuing to download file, it does not already exist.", "outf", outf, "error", err)
}
}
// Get the data
resp, err := http.Get(url)
if err != nil {
slog.Error("download: Failed to make request.", "outf", outf, "error", err)
return err
}
defer resp.Body.Close()
// Check server response
if resp.StatusCode != http.StatusOK {
slog.Error("download: Request failed. Non OK response.", "outf", outf, "status", resp.Status, "error", err)
return fmt.Errorf("bad status: %s", resp.Status)
}
// Create the file
out, err := os.Create(outf)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
slog.Warn("download: Failed to create out file, trying to recover by ensuring directories exist.", "outf", outf)
err = os.MkdirAll(path.Dir(outf), 0764)
if err != nil {
slog.Error("download: Failed to create dir(s) in recovery attempt.", "outf", outf, "error", err)
return err
}
// If dirs made, try making file again
out, err = os.Create(outf)
if err != nil {
slog.Error("download: Failed to create out file again in recovery attempt.", "outf", outf, "error", err)
return err
}
slog.Info("download: recovered by creating dir(s).", "outf", outf)
} else {
slog.Error("download: Failed to create out file. No known recovery path possible.", "outf", outf, "error", err)
return err
}
}
defer out.Close()
// Write the body to file
_, err = io.Copy(out, resp.Body)
if err != nil {
slog.Error("download: Failed to write file to our file.", "outf", outf, "error", err)
return err
}
slog.Debug("download: Successfully downloaded file", "outf", outf)
return nil
}
type Service struct {
db *gorm.DB
tmdb *tmdb.TMDB
}
func NewService(db *gorm.DB, tmdb *tmdb.TMDB) *Service {
return &Service{
db,
tmdb,
}
}
// onlyUpdate - If we should only update existing row if exists, or false to create/update if not exist.
func (s *Service) saveContent(c *entity.Content, onlyUpdate bool) error {
slog.Info("Saving content to db", "id", c.TmdbID, "title", c.Title)
if c.TmdbID == 0 || c.Title == "" || c.Type == "" {
slog.Error("saveContent: content missing id, title or type!", "id", c.TmdbID, "title", c.Title, "type", c.Type)
return errors.New("content missing id or title")
}
var res *gorm.DB
if onlyUpdate {
// We only want to update an existing row, if it exists.
res = s.db.Model(&entity.Content{}).Where("type = ? AND tmdb_id = ?", c.Type, c.TmdbID).Updates(c)
if res.Error != nil {
slog.Error("saveContent: Error updating content in database", "error", res.Error.Error())
return errors.New("failed to update cached content in database")
}
} else {
// On conflict, update existing row with details incase any were updated/missing.
res = s.db.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "tmdb_id"}, {Name: "type"}},
DoUpdates: clause.AssignmentColumns([]string{
"title",
"poster_path",
"overview",
"release_date",
"popularity",
"vote_average",
"vote_count",
"imdb_id",
"status",
"budget",
"revenue",
"runtime",
"number_of_episodes",
"number_of_seasons",
}),
}).Create(&c)
if res.Error != nil {
// Error if anything but unique contraint error
if res.Error != gorm.ErrDuplicatedKey {
slog.Error("saveContent: Error creating content in database", "error", res.Error.Error())
return errors.New("failed to cache content in database")
}
}
}
// If row created, download the image
if res.RowsAffected > 0 {
slog.Debug("saveContent: Downloading poster.")
err := download(
"https://image.tmdb.org/t/p/w500"+c.PosterPath,
path.Join(config.DataPath, "img", c.PosterPath),
false,
)
if err != nil {
slog.Error("saveContent: Failed to download content image!", "error", err.Error())
}
}
return nil
}
func (s *Service) cacheContentTv(content tmdb.TMDBShowDetails, onlyUpdate bool) (entity.Content, error) {
slog.Debug("cacheContentTv", "content", content)
var (
releaseDate time.Time
runtime uint32
)
var dateFormat = "2006-01-02"
releaseDate, err := time.Parse(dateFormat, content.FirstAirDate)
if err != nil {
slog.Error("Failed to parse tv release date", "error", err)
}
if len(content.EpisodeRunTime) > 0 {
runtime = uint32(content.EpisodeRunTime[0])
}
c := entity.Content{
TmdbID: content.ID,
Title: content.Name,
Overview: content.Overview,
PosterPath: content.PosterPath,
Type: entity.SHOW,
ReleaseDate: &releaseDate,
Popularity: content.Popularity,
VoteAverage: content.VoteAverage,
VoteCount: content.VoteCount,
Status: content.Status,
Runtime: runtime,
NumberOfEpisodes: content.NumberOfEpisodes,
NumberOfSeasons: content.NumberOfSeasons,
}
err = s.saveContent(&c, onlyUpdate)
if err != nil {
slog.Error("cacheContentTv: 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) {
var (
releaseDate time.Time
)
var dateFormat = "2006-01-02"
// Get details from movie/show response and fill out needed vars
releaseDate, err := time.Parse(dateFormat, content.ReleaseDate)
if err != nil {
slog.Error("Failed to parse movie release date", "error", err)
}
c := entity.Content{
TmdbID: content.ID,
Title: content.Title,
Overview: content.Overview,
PosterPath: content.PosterPath,
Type: entity.MOVIE,
ReleaseDate: &releaseDate,
Popularity: content.Popularity,
VoteAverage: content.VoteAverage,
VoteCount: content.VoteCount,
ImdbID: content.ImdbID,
Status: content.Status,
Budget: content.Budget,
Revenue: content.Revenue,
Runtime: content.Runtime,
}
err = s.saveContent(&c, onlyUpdate)
if err != nil {
slog.Error("cacheContentMovie: Failed to save content!", "error", err)
return entity.Content{}, errors.New("failed to save content")
}
return c, nil
}
// 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) {
var content entity.Content
// Look in db for content.
s.db.Where("type = ? AND tmdb_id = ?", contentType, tmdbId).Find(&content)
// Create content if not found from our db.
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")
}
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
}
@@ -0,0 +1,82 @@
package content
import (
"log/slog"
"github.com/sbondCo/Watcharr/media/tmdb"
)
// Getting only region needed from api is not a feature yet
// https://trello.com/c/75tR4cpF/106-add-watch-provider-region-filtering
// When it is, this can be removed for that instead.
func transformProviders(c *any, country string) tmdb.WatchProviders {
slog.Debug("transformProviders called", "country", country)
resp := tmdb.WatchProviders{}
cmap, ok := (*c).(map[string]any)
if !ok {
slog.Error("transformProviders: Assertion failed")
return tmdb.WatchProviders{}
}
rmap, ok := cmap["results"].(map[string]any)
if !ok {
slog.Warn("transformProviders: Couldn't find results property..")
return tmdb.WatchProviders{}
}
val, ok := rmap[country]
if !ok {
slog.Warn("transformProviders: Couldn't find country..",
"country", country)
return tmdb.WatchProviders{}
}
slog.Debug("transformProviders: Found country..", "obj", val)
rvmap, ok := val.(map[string]any)
if !ok {
slog.Warn("transformProviders: Couldn't assert country obj")
return tmdb.WatchProviders{}
}
// Turning any into a type safe object we can use later.
// Here we are just getting the flatrate items and manually
// mapping them to a WatchProvider struct.
resp.Flatrate = transformProvidersType("flatrate", rvmap, resp.Flatrate)
resp.Free = transformProvidersType("free", rvmap, resp.Free)
tmdbLink, ok := rvmap["link"].(string)
if ok {
resp.Link = tmdbLink
}
return resp
}
// Transform the type of provider requested.
func transformProvidersType(
ptype string,
rvmap map[string]any,
providers []tmdb.WatchProvider,
) []tmdb.WatchProvider {
tm, ok := rvmap[ptype].([]any)
if !ok {
slog.Warn("transformProvidersType: Assertion failed")
return providers
}
for i := range tm {
v2, ok := tm[i].(map[string]any)
if !ok {
continue
}
providerName, ok := v2["provider_name"].(string)
if !ok {
continue
}
providers = append(providers,
tmdb.WatchProvider{
ProviderName: providerName,
})
}
return providers
}
+273
View File
@@ -0,0 +1,273 @@
package content
import (
"log/slog"
"net/http"
"strconv"
"time"
"github.com/gin-contrib/cache"
"github.com/gin-gonic/gin"
"github.com/sbondCo/Watcharr/database/entity"
"github.com/sbondCo/Watcharr/domain"
"github.com/sbondCo/Watcharr/feature/auth/authmiddleware"
"github.com/sbondCo/Watcharr/feature/watched/addedtocontent"
"github.com/sbondCo/Watcharr/router"
"github.com/sbondCo/Watcharr/util"
)
type WatchedProvider interface {
UpdateWatchedLastViewedSeason(userId uint, id uint, seasonNum int) error
GetWatchedItemBySupportedMediaId(userId uint, id uint, t util.SupportedMedia) (entity.Watched, error)
GetWatchedItemsBySupportedMediaIds(userId uint, c []addedtocontent.IdToTypePair) ([]entity.Watched, error)
}
type Router struct {
br *router.BaseRouter
cs *Service
wp WatchedProvider
}
func NewRouter(br *router.BaseRouter, cs *Service, wp WatchedProvider) *Router {
return &Router{
br: br,
cs: cs,
wp: wp,
}
}
func (r *Router) AddRoutes() {
content := r.br.Router.Group("/content").Use(authmiddleware.AuthRequired(nil, r.br.Cfg))
exp := time.Hour * 24
// NOTE: Some routes use `cache.CachePage`, but others that contain user watched data
// don't and rather have their caching on the TMDB methods directly.
// Get movie details (for movie page)
content.GET("/movie/:id", router.WhereaboutsRequired(r.br.Cfg), r.GetMovieDetails)
// Get movie cast
content.GET("/movie/:id/credits", cache.CachePage(r.br.MemStore, exp, r.GetMovieCredits))
// Get tv details (for tv page)
content.GET("/tv/:id", router.WhereaboutsRequired(r.br.Cfg), r.GetTvDetails)
// Get tv cast
content.GET("/tv/:id/credits", cache.CachePage(r.br.MemStore, exp, r.GetTvCredits))
// Get season details
// Supports `watchedId` query parameter for saving the requested season as `LastViewedSeason`.
content.GET("/tv/:id/season/:num", r.GetSeasonDetails)
// Get person details
content.GET("/person/:id", cache.CachePage(r.br.MemStore, exp, r.GetPerson))
// Get person credits
content.GET("/person/:id/credits", r.GetPersonCredits)
// Available regions for watch providers
content.GET("/regions", r.GetRegions)
}
func (r *Router) GetMovieDetails(c *gin.Context) {
userId := c.MustGet("userId").(uint)
if c.Param("id") == "" {
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{
"append_to_response": "videos,watch/providers,similar",
},
)
if err != nil {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
contentAsMedia := content.AsMedia()
if err := addedtocontent.AddSingularAndList(
r.wp,
userId,
contentAsMedia,
func(w *entity.Watched) {
contentAsMedia.Watched = domain.NewWatchedDtoForContentPage(w)
},
[]*addedtocontent.AddListCall[domain.Media]{
addedtocontent.NewAddListCall(
contentAsMedia.Similar,
func(i int, w *entity.Watched) {
contentAsMedia.Similar[i].Watched = domain.NewWatchedDtoForLists(w)
},
),
},
); err != nil {
slog.Error("GetMovieDetails: Failed to add watched to content!", "error", err)
c.JSON(
http.StatusInternalServerError,
router.ErrorResponse{Error: "failed to add watched data to response"},
)
return
}
c.JSON(http.StatusOK, contentAsMedia)
}
func (r *Router) GetMovieCredits(c *gin.Context) {
if c.Param("id") == "" {
c.Status(400)
return
}
content, err := r.cs.MovieCredits(c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
c.JSON(http.StatusOK, content)
}
func (r *Router) GetTvDetails(c *gin.Context) {
userId := c.MustGet("userId").(uint)
if c.Param("id") == "" {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: "an id was not provided"})
return
}
// 1. Get details
content, err := r.cs.TvDetails(
c.Param("id"),
c.MustGet("userCountry").(string),
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
}
contentAsMedia := content.AsMedia()
if err := addedtocontent.AddSingularAndList(
r.wp,
userId,
contentAsMedia,
func(w *entity.Watched) {
contentAsMedia.Watched = domain.NewWatchedDtoForContentPage(w)
},
[]*addedtocontent.AddListCall[domain.Media]{
addedtocontent.NewAddListCall(
contentAsMedia.Similar,
func(i int, w *entity.Watched) {
contentAsMedia.Similar[i].Watched = domain.NewWatchedDtoForLists(w)
},
),
},
); err != nil {
slog.Error("GetTvDetails: Failed to add watched to content!", "error", err)
c.JSON(
http.StatusInternalServerError,
router.ErrorResponse{Error: "failed to add watched data to response"},
)
return
}
c.JSON(http.StatusOK, contentAsMedia)
}
func (r *Router) GetTvCredits(c *gin.Context) {
if c.Param("id") == "" {
c.Status(400)
return
}
content, err := r.cs.TvCredits(c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
c.JSON(http.StatusOK, content)
}
// Get season details
// Supports `watchedId` query parameter for saving the requested season as `LastViewedSeason`.
func (r *Router) GetSeasonDetails(c *gin.Context) {
if c.Param("id") == "" || c.Param("num") == "" {
c.Status(400)
return
}
content, err := r.cs.SeasonDetails(c.Param("id"), c.Param("num"))
if err != nil {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
// If a `watchedId` is passed, we should update it with this season
// number, so the LastViewedSeason field is up to date (this seemed
// better than making a new request for just saving this).
// We will attach a `watcharr-lastviewedseason-saved` header if
// this part succeeds so the client can decide on showing an error.
if watchedIdQ := c.Query("watchedId"); watchedIdQ != "" {
userId := c.MustGet("userId").(uint)
watchedId, err := strconv.ParseUint(watchedIdQ, 10, 64)
if err != nil {
slog.Error("get season details route: Processing watchedId param failed", "error", err.Error(), "id", watchedIdQ)
} else {
if seasonNum, err := strconv.ParseInt(c.Param("num"), 10, 64); err == nil {
if err = r.wp.UpdateWatchedLastViewedSeason(
userId, uint(watchedId), int(seasonNum),
); err == nil {
c.Header("watcharr-lastviewedseason-saved", "1")
}
} else {
slog.Error("get season details route: Parsing season number as int failed", "error", err.Error(), "season_num", c.Param("num"))
}
}
} else {
slog.Debug("get season details route: No watchedId parameter found.. not doing anything.")
}
c.JSON(http.StatusOK, content)
}
func (r *Router) GetPerson(c *gin.Context) {
if c.Param("id") == "" {
c.Status(400)
return
}
content, err := r.cs.PersonDetails(c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
c.JSON(http.StatusOK, content.AsPersonDetailsResponse())
}
func (r *Router) GetPersonCredits(c *gin.Context) {
userId := c.MustGet("userId").(uint)
if c.Param("id") == "" {
c.Status(400)
return
}
content, err := r.cs.PersonCredits(c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
// Add content into response struct then add watched entries
resp := domain.PersonCreditsResponse{}
for i := range content.Cast {
resp.Credits = append(resp.Credits, content.Cast[i].AsMedia())
}
if err := addedtocontent.AddList(
r.wp,
userId,
resp.Credits,
func(i int, w *entity.Watched) {
resp.Credits[i].Watched = domain.NewWatchedDtoForLists(w)
},
); err != nil {
slog.Error("GetPersonCredits: Failed to add watched to content!", "error", err)
c.JSON(
http.StatusInternalServerError,
router.ErrorResponse{Error: "failed to add watched data to response"},
)
return
}
c.JSON(http.StatusOK, resp)
}
func (r *Router) GetRegions(c *gin.Context) {
re, err := r.cs.Regions()
if err != nil {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
c.JSON(http.StatusOK, re)
}
+391
View File
@@ -0,0 +1,391 @@
package discover
import (
"errors"
"log/slog"
"time"
"github.com/sbondCo/Watcharr/config"
"github.com/sbondCo/Watcharr/domain"
"github.com/sbondCo/Watcharr/media/tmdb"
"gorm.io/gorm"
)
type ContentProvider interface {
Trending(t tmdb.TrendingType, pageNum int, region string) (tmdb.TMDBTrendingCombined, error)
DiscoverMovies(o tmdb.DiscoverOptions, pageNum int, region string) (tmdb.TMDBDiscoverMovies, error)
DiscoverTv(o tmdb.DiscoverOptions, pageNum int, region string) (tmdb.TMDBDiscoverShows, error)
PopularPeople(pageNum int) (tmdb.TMDBPopularPeople, error)
}
type Service struct {
db *gorm.DB
cfg *config.ServerConfig
contentProvider ContentProvider
}
func NewService(
db *gorm.DB,
cfg *config.ServerConfig,
contentProvider ContentProvider,
) *Service {
return &Service{
db,
cfg,
contentProvider,
}
}
// `Limit` is not supported.
func (s *Service) Discover(
// User request
r domain.DiscoverRequest,
// Extra data
meta domain.DiscoverRequestMeta,
) (domain.DiscoverResponse, error) {
resp := domain.DiscoverResponse{}
switch r.Type {
case domain.SearchTypeMulti:
return s.DiscoverMulti(r, meta)
case domain.SearchTypeShow:
return s.DiscoverTv(r, meta)
case domain.SearchTypePerson:
return s.DiscoverPeople(r, meta)
case domain.SearchTypeMovie:
return s.DiscoverMovie(r, meta)
case domain.SearchTypeGame:
return s.DiscoverGame(r, meta)
}
return resp, nil
}
// Discover Multi. Just for tmdb.
func (s *Service) DiscoverMulti(
r domain.DiscoverRequest,
meta domain.DiscoverRequestMeta,
) (domain.DiscoverResponse, error) {
resp := domain.DiscoverResponse{}
var err error
switch r.Filter {
case domain.DiscoverFilterTrending:
err = s.discoverMultiTrending(tmdb.TrendingTypeAll, meta, &resp)
case domain.DiscoverFilterInTheatres:
err = s.discoverMovieInTheatres(meta, &resp)
default:
slog.Error("DiscoverMulti: Unsupported filter.")
return resp, errors.New("unsupported filter")
}
return resp, err
}
// Discover movies.
func (s *Service) DiscoverMovie(
r domain.DiscoverRequest,
meta domain.DiscoverRequestMeta,
) (domain.DiscoverResponse, error) {
resp := domain.DiscoverResponse{}
var err error
switch r.Filter {
case domain.DiscoverFilterTrending:
err = s.discoverMultiTrending(tmdb.TrendingTypeMovie, meta, &resp)
case domain.DiscoverFilterInTheatres:
err = s.discoverMovieInTheatres(meta, &resp)
case domain.DiscoverFilterUpcoming:
err = s.discoverMovieUpcoming(meta, &resp)
case domain.DiscoverFilterPopular:
err = s.discoverMoviePopular(meta, &resp)
default:
slog.Error("DiscoverMovie: Unsupported filter.")
return resp, errors.New("unsupported filter")
}
return resp, err
}
// Discover shows.
func (s *Service) DiscoverTv(
r domain.DiscoverRequest,
meta domain.DiscoverRequestMeta,
) (domain.DiscoverResponse, error) {
resp := domain.DiscoverResponse{}
var err error
switch r.Filter {
case domain.DiscoverFilterTrending:
err = s.discoverMultiTrending(tmdb.TrendingTypeShow, meta, &resp)
case domain.DiscoverFilterUpcoming:
err = s.discoverTvUpcoming(meta, &resp)
case domain.DiscoverFilterPopular:
err = s.discoverTvPopular(meta, &resp)
default:
slog.Error("DiscoverMovie: Unsupported filter.")
return resp, errors.New("unsupported filter")
}
return resp, err
}
// Discover people.
func (s *Service) DiscoverPeople(
r domain.DiscoverRequest,
meta domain.DiscoverRequestMeta,
) (domain.DiscoverResponse, error) {
resp := domain.DiscoverResponse{}
var err error
switch r.Filter {
case domain.DiscoverFilterTrending:
err = s.discoverMultiTrending(tmdb.TrendingTypePerson, meta, &resp)
case domain.DiscoverFilterPopular:
err = s.discoverPeoplePopular(meta, &resp)
default:
slog.Error("DiscoverMulti: Unsupported filter.")
return resp, errors.New("unsupported filter")
}
return resp, err
}
// Discover games.
func (s *Service) DiscoverGame(
r domain.DiscoverRequest,
meta domain.DiscoverRequestMeta,
) (domain.DiscoverResponse, error) {
resp := domain.DiscoverResponse{}
var err error
switch r.Filter {
case domain.DiscoverFilterTrending:
err = s.discoverGameTrending(&resp)
case domain.DiscoverFilterUpcoming:
err = s.discoverGameUpcoming(&resp)
default:
slog.Error("DiscoverGame: Unsupported filter.")
return resp, errors.New("unsupported filter")
}
return resp, err
}
// Discover anything that is trending on TMDB (including combined).
func (s *Service) discoverMultiTrending(
t tmdb.TrendingType,
meta domain.DiscoverRequestMeta,
resp *domain.DiscoverResponse,
) error {
tmdbRes, err := s.contentProvider.Trending(t, meta.PageParams.Page, meta.Region)
if err != nil {
slog.Error("discoverMulti: Failed to search tmdb!", "error", err)
return errors.New("content request failed")
}
for _, v := range tmdbRes.Results {
resp.Results = append(
resp.Results,
v.AsMedia(),
)
}
resp.Page = tmdbRes.Page
resp.TotalPages = tmdbRes.TotalPages
resp.TotalResults = int64(tmdbRes.TotalResults)
return nil
}
func (s *Service) discoverMovieInTheatres(
meta domain.DiscoverRequestMeta,
resp *domain.DiscoverResponse,
) error {
tmdbRes, err := s.contentProvider.DiscoverMovies(
tmdb.DiscoverOptions{
ReleaseDateMin: time.Now().AddDate(0, 0, -40),
ReleaseDateMax: time.Now().AddDate(0, 0, 2),
WithReleaseType: "2|3",
},
meta.PageParams.Page,
meta.Region,
)
if err != nil {
slog.Error("discoverMovieInTheatres: Failed to search tmdb!",
"error", err)
return errors.New("content request failed")
}
for _, v := range tmdbRes.Results {
resp.Results = append(
resp.Results,
v.AsMedia(),
)
}
resp.Page = tmdbRes.Page
resp.TotalPages = tmdbRes.TotalPages
resp.TotalResults = int64(tmdbRes.TotalResults)
return nil
}
func (s *Service) discoverMovieUpcoming(
meta domain.DiscoverRequestMeta,
resp *domain.DiscoverResponse,
) error {
tmdbRes, err := s.contentProvider.DiscoverMovies(
tmdb.DiscoverOptions{
ReleaseDateMin: time.Now(),
ReleaseDateMax: time.Now().AddDate(0, 1, 0),
WithReleaseType: "2|3",
},
meta.PageParams.Page,
meta.Region,
)
if err != nil {
slog.Error("discoverMovieUpcoming: Failed to search tmdb!",
"error", err)
return errors.New("content request failed")
}
for _, v := range tmdbRes.Results {
resp.Results = append(
resp.Results,
v.AsMedia(),
)
}
resp.Page = tmdbRes.Page
resp.TotalPages = tmdbRes.TotalPages
resp.TotalResults = int64(tmdbRes.TotalResults)
return nil
}
func (s *Service) discoverMoviePopular(
meta domain.DiscoverRequestMeta,
resp *domain.DiscoverResponse,
) error {
tmdbRes, err := s.contentProvider.DiscoverMovies(
tmdb.DiscoverOptions{},
meta.PageParams.Page,
meta.Region,
)
if err != nil {
slog.Error("discoverMoviePopular: Failed to search tmdb!",
"error", err)
return errors.New("content request failed")
}
for _, v := range tmdbRes.Results {
resp.Results = append(
resp.Results,
v.AsMedia(),
)
}
resp.Page = tmdbRes.Page
resp.TotalPages = tmdbRes.TotalPages
resp.TotalResults = int64(tmdbRes.TotalResults)
return nil
}
func (s *Service) discoverTvUpcoming(
meta domain.DiscoverRequestMeta,
resp *domain.DiscoverResponse,
) error {
tmdbRes, err := s.contentProvider.DiscoverTv(
tmdb.DiscoverOptions{
ReleaseDateMin: time.Now(),
ReleaseDateMax: time.Now().AddDate(0, 1, 0),
WithReleaseType: "2|3",
},
meta.PageParams.Page,
meta.Region,
)
if err != nil {
slog.Error("discoverTvUpcoming: Failed to search tmdb!",
"error", err)
return errors.New("content request failed")
}
for _, v := range tmdbRes.Results {
resp.Results = append(
resp.Results,
v.AsMedia(),
)
}
resp.Page = tmdbRes.Page
resp.TotalPages = tmdbRes.TotalPages
resp.TotalResults = int64(tmdbRes.TotalResults)
return nil
}
func (s *Service) discoverTvPopular(
meta domain.DiscoverRequestMeta,
resp *domain.DiscoverResponse,
) error {
tmdbRes, err := s.contentProvider.DiscoverTv(
tmdb.DiscoverOptions{},
meta.PageParams.Page,
meta.Region,
)
if err != nil {
slog.Error("discoverTvPopular: Failed to search tmdb!",
"error", err)
return errors.New("content request failed")
}
for _, v := range tmdbRes.Results {
resp.Results = append(
resp.Results,
v.AsMedia(),
)
}
resp.Page = tmdbRes.Page
resp.TotalPages = tmdbRes.TotalPages
resp.TotalResults = int64(tmdbRes.TotalResults)
return nil
}
func (s *Service) discoverPeoplePopular(
meta domain.DiscoverRequestMeta,
resp *domain.DiscoverResponse,
) error {
tmdbRes, err := s.contentProvider.PopularPeople(
meta.PageParams.Page,
)
if err != nil {
slog.Error("discoverPeoplePopular: Failed to search tmdb!",
"error", err)
return errors.New("content request failed")
}
for _, v := range tmdbRes.Results {
resp.Results = append(
resp.Results,
v.AsMedia(),
)
}
resp.Page = tmdbRes.Page
resp.TotalPages = tmdbRes.TotalPages
resp.TotalResults = int64(tmdbRes.TotalResults)
return nil
}
func (s *Service) discoverGameTrending(
resp *domain.DiscoverResponse,
) error {
igdbRes, err := s.cfg.TWITCH.Trending()
if err != nil {
slog.Error("discoverGameTrending: Failed to search igdb!", "error", err)
return errors.New("content request failed")
}
for _, v := range igdbRes {
resp.Results = append(
resp.Results,
v.AsMedia(),
)
}
resp.Page = 1
resp.TotalPages = 1
resp.TotalResults = int64(len(igdbRes))
return nil
}
func (s *Service) discoverGameUpcoming(
resp *domain.DiscoverResponse,
) error {
igdbRes, err := s.cfg.TWITCH.Upcoming()
if err != nil {
slog.Error("discoverGameUpcoming: Failed to search igdb!", "error", err)
return errors.New("content request failed")
}
for _, v := range igdbRes {
resp.Results = append(
resp.Results,
v.AsMedia(),
)
}
resp.Page = 1
resp.TotalPages = 1
resp.TotalResults = int64(len(igdbRes))
return nil
}
+101
View File
@@ -0,0 +1,101 @@
package discover
import (
"log/slog"
"net/http"
"github.com/gin-gonic/gin"
"github.com/jinzhu/copier"
"github.com/sbondCo/Watcharr/database/entity"
"github.com/sbondCo/Watcharr/domain"
"github.com/sbondCo/Watcharr/feature/auth/authmiddleware"
"github.com/sbondCo/Watcharr/feature/watched/addedtocontent"
"github.com/sbondCo/Watcharr/router"
"github.com/sbondCo/Watcharr/util"
)
type WatchedProvider interface {
GetWatchedItemBySupportedMediaId(userId uint, id uint, t util.SupportedMedia) (entity.Watched, error)
GetWatchedItemsBySupportedMediaIds(userId uint, c []addedtocontent.IdToTypePair) ([]entity.Watched, error)
}
type Router struct {
br *router.BaseRouter
service *Service
watchedProvider WatchedProvider
}
func NewRouter(br *router.BaseRouter, service *Service, watchedProvider WatchedProvider) *Router {
return &Router{
br,
service,
watchedProvider,
}
}
func (r *Router) AddRoutes() {
discover := r.br.Router.Group("/discover").Use(authmiddleware.AuthRequired(r.br.DB, r.br.Cfg))
// Master discovery
discover.GET("", router.WhereaboutsRequired(r.br.Cfg), router.PaginatedRequest(true), r.GetDiscover)
}
// NOTE: The handler functions use `copier` to copy values from the response
// structs into a new one that includes the user "Watched" data.
// This was done to avoid adding Watched data to the response structs, as they
// are cached in our in-mem cache, which could cause references to pollute the cache
// resulting in user data being leaked to others.
// We are doing to to explicitly not let that case happen.
func (r *Router) GetDiscover(c *gin.Context) {
userId := c.MustGet("userId").(uint)
pp := c.MustGet("paginationParams").(util.PaginationParams)
req := domain.DiscoverRequest{
// Defaults...
Type: domain.SearchTypeMulti,
Filter: domain.DiscoverFilterTrending,
}
if err := c.ShouldBind(&req); err != nil {
slog.Error("GetDiscover: ShouldBind for request params failed!", "error", err)
c.JSON(
http.StatusBadRequest,
router.ErrorResponse{
Error: "failed to get request parameters or they are invalid",
},
)
return
}
resp, err := r.service.Discover(req, domain.DiscoverRequestMeta{
PageParams: pp,
Region: c.MustGet("userCountry").(string),
})
if err != nil {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
ww := domain.DiscoverResponse{}
if err := copier.Copy(&ww, &resp); err != nil {
slog.Error("GetDiscover: Failed to copy", "error", err)
c.JSON(
http.StatusInternalServerError,
router.ErrorResponse{Error: "failed to prepare response"},
)
return
}
if err := addedtocontent.AddList(
r.watchedProvider,
userId,
ww.Results,
func(i int, w *entity.Watched) {
ww.Results[i].Watched = domain.NewWatchedDtoForLists(w)
},
); err != nil {
slog.Error("GetDiscover: Failed to add watched to content!", "error", err)
c.JSON(
http.StatusInternalServerError,
router.ErrorResponse{Error: "failed to add watched data to response"},
)
return
}
c.JSON(http.StatusOK, ww)
}
+42
View File
@@ -0,0 +1,42 @@
package feature
import (
"github.com/sbondCo/Watcharr/config"
"github.com/sbondCo/Watcharr/database/entity"
"github.com/sbondCo/Watcharr/feature/auth/permission"
)
type ServerFeatures struct {
Sonarr bool `json:"sonarr"`
Radarr bool `json:"radarr"`
Games bool `json:"games"`
}
type Service struct {
cfg *config.ServerConfig
}
func NewService(cfg *config.ServerConfig) *Service {
return &Service{
cfg,
}
}
// Get enabled server functionality from Config.
// Mainly so the frontend can store this once and know
// which btns should be shown, etc.
func (s *Service) GetEnabledFeatures(userPerms int) ServerFeatures {
var f ServerFeatures
if s.cfg.TwitchEnabled() {
f.Games = true
}
if permission.Has(userPerms, entity.PERM_REQUEST_CONTENT) {
if len(s.cfg.SONARR) > 0 {
f.Sonarr = true
}
if len(s.cfg.RADARR) > 0 {
f.Radarr = true
}
}
return f
}
+30
View File
@@ -0,0 +1,30 @@
package feature
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/sbondCo/Watcharr/feature/auth/authmiddleware"
"github.com/sbondCo/Watcharr/router"
)
type Router struct {
*router.BaseRouter
service *Service
}
func NewRouter(br *router.BaseRouter, service *Service) *Router {
return &Router{
br,
service,
}
}
func (r *Router) AddRoutes() {
feature := r.Router.Group("/features").Use(authmiddleware.AuthRequired(r.DB, r.Cfg))
// Get enabled features (aka functionality)
feature.GET("", func(c *gin.Context) {
c.JSON(http.StatusOK, r.service.GetEnabledFeatures(c.GetInt("userPermissions")))
})
}
@@ -1,39 +1,40 @@
package main
package follow
import (
"errors"
"log/slog"
"time"
"github.com/sbondCo/Watcharr/database/entity"
"gorm.io/gorm"
)
// Database struct, only internal.
type Follow struct {
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"-"`
UserID uint `gorm:"primaryKey:usr_id_to_followed_id;not null;check:user_id != followed_user_id" json:"-"`
User User `json:"-"`
FollowedUserID uint `gorm:"primaryKey:usr_id_to_followed_id;not null" json:"-"`
FollowedUser User `json:"-"`
}
// For end users to see.
type FollowPublic struct {
CreatedAt time.Time `json:"createdAt"`
FollowedUser PublicUser `json:"followedUser"`
CreatedAt time.Time `json:"createdAt"`
FollowedUser entity.PublicUser `json:"followedUser"`
}
type FollowThoughts struct {
FollowedUser PublicUser `json:"followedUser"`
Thoughts string `json:"thoughts"`
Status WatchedStatus `json:"status"`
Rating float64 `json:"rating"`
FollowedUser entity.PublicUser `json:"followedUser"`
Thoughts string `json:"thoughts"`
Status entity.WatchedStatus `json:"status"`
Rating float64 `json:"rating"`
}
func followUser(db *gorm.DB, currentUserId uint, toFollowUserId uint) (FollowPublic, error) {
f := Follow{UserID: currentUserId, FollowedUserID: toFollowUserId}
res := db.Model(&Follow{}).Create(&f)
type Service struct {
db *gorm.DB
}
func NewService(db *gorm.DB) *Service {
return &Service{
db,
}
}
func (s *Service) FollowUser(currentUserId uint, toFollowUserId uint) (FollowPublic, error) {
f := entity.Follow{UserID: currentUserId, FollowedUserID: toFollowUserId}
res := s.db.Model(&entity.Follow{}).Create(&f)
if res.Error != nil {
slog.Error("followUser: Error on inserting follow.", "error", res.Error)
err := "failed to insert follow"
@@ -43,8 +44,8 @@ func followUser(db *gorm.DB, currentUserId uint, toFollowUserId uint) (FollowPub
return FollowPublic{}, errors.New(err)
}
// Now get the row with preloaded followed user
var nf Follow
res = db.Where("user_id = ? AND followed_user_id = ?", currentUserId, toFollowUserId).Preload("FollowedUser", "private = ?", 0).Take(&nf)
var nf entity.Follow
res = s.db.Where("user_id = ? AND followed_user_id = ?", currentUserId, toFollowUserId).Preload("FollowedUser", "private = ?", 0).Take(&nf)
if res.Error != nil {
slog.Error("followUser: Couldn't fetch newly followed user.", "error", res.Error)
return FollowPublic{}, errors.New("followed, but failed to fetch followed user")
@@ -52,9 +53,9 @@ func followUser(db *gorm.DB, currentUserId uint, toFollowUserId uint) (FollowPub
return FollowPublic{CreatedAt: nf.CreatedAt, FollowedUser: nf.FollowedUser.GetSafe()}, nil
}
func unfollowUser(db *gorm.DB, currentUserId uint, toFollowUserId uint) (bool, error) {
f := Follow{UserID: currentUserId, FollowedUserID: toFollowUserId}
res := db.Delete(&f)
func (s *Service) UnfollowUser(currentUserId uint, toFollowUserId uint) (bool, error) {
f := entity.Follow{UserID: currentUserId, FollowedUserID: toFollowUserId}
res := s.db.Delete(&f)
if res.Error != nil {
slog.Error("unfollowUser: Error deleting follow.", "error", res.Error)
err := "failed to remove follow"
@@ -67,9 +68,9 @@ func unfollowUser(db *gorm.DB, currentUserId uint, toFollowUserId uint) (bool, e
}
// Get current users follows
func getFollows(db *gorm.DB, userId uint) ([]FollowPublic, error) {
var follows []Follow
res := db.Where("user_id = ?", userId).Preload("FollowedUser", "private = ?", 0).Find(&follows)
func (s *Service) GetFollows(userId uint) ([]FollowPublic, error) {
var follows []entity.Follow
res := s.db.Where("user_id = ?", userId).Preload("FollowedUser", "private = ?", 0).Find(&follows)
if res.Error != nil {
slog.Error("getFollows: Error finding follows.", "error", res.Error)
return []FollowPublic{}, errors.New("failed to find follows")
@@ -88,9 +89,9 @@ func getFollows(db *gorm.DB, userId uint) ([]FollowPublic, error) {
}
// Get followed profile thoughts, rating, etc on specific content.
func getFollowsThoughts(db *gorm.DB, userId uint, mediaType string, mediaId string) ([]FollowThoughts, error) {
var follows []Follow
res := db.Where("user_id = ?", userId).Preload("FollowedUser", "private = ? AND private_thoughts = ?", 0, 0).Find(&follows)
func (s *Service) GetFollowsThoughts(userId uint, mediaType string, mediaId string) ([]FollowThoughts, error) {
var follows []entity.Follow
res := s.db.Where("user_id = ?", userId).Preload("FollowedUser", "private = ? AND private_thoughts = ?", 0, 0).Find(&follows)
if res.Error != nil {
slog.Error("getFollows: Error finding follows.", "error", res.Error)
return []FollowThoughts{}, errors.New("failed to find follows")
@@ -107,8 +108,8 @@ func getFollowsThoughts(db *gorm.DB, userId uint, mediaType string, mediaId stri
var contentOrGameId int
if mediaType == "game" {
// Get our content id from type and tmdbId
var content Game
res = db.Where("igdb_id = ?", mediaId).Select("id").Find(&content)
var content entity.Game
res = s.db.Where("igdb_id = ?", mediaId).Select("id").Find(&content)
if res.Error != nil {
slog.Error("getFollows: Error finding content from db.", "error", res.Error)
return []FollowThoughts{}, errors.New("failed to find content")
@@ -116,8 +117,8 @@ func getFollowsThoughts(db *gorm.DB, userId uint, mediaType string, mediaId stri
contentOrGameId = content.ID
} else if mediaType == "movie" || mediaType == "tv" {
// Get our content id from type and tmdbId
var content Content
res = db.Where("type = ? AND tmdb_id = ?", mediaType, mediaId).Select("id").Find(&content)
var content entity.Content
res = s.db.Where("type = ? AND tmdb_id = ?", mediaType, mediaId).Select("id").Find(&content)
if res.Error != nil {
slog.Error("getFollows: Error finding content from db.", "error", res.Error)
return []FollowThoughts{}, errors.New("failed to find content")
@@ -128,11 +129,11 @@ func getFollowsThoughts(db *gorm.DB, userId uint, mediaType string, mediaId stri
return []FollowThoughts{}, errors.New("unrecognized media type")
}
// Get list of followeds watcheds for this content
var fw []Watched
var fw []entity.Watched
if mediaType == "game" {
res = db.Where("game_id = ? AND user_id IN ?", contentOrGameId, followIds).Find(&fw)
res = s.db.Where("game_id = ? AND user_id IN ?", contentOrGameId, followIds).Find(&fw)
} else {
res = db.Where("content_id = ? AND user_id IN ?", contentOrGameId, followIds).Find(&fw)
res = s.db.Where("content_id = ? AND user_id IN ?", contentOrGameId, followIds).Find(&fw)
}
if res.Error != nil {
slog.Error("getFollows: Error finding followed watcheds from db.", "error", res.Error)
@@ -141,7 +142,7 @@ func getFollowsThoughts(db *gorm.DB, userId uint, mediaType string, mediaId stri
// Create followThoughts array by combining follows and fw(atcheds)
ft := []FollowThoughts{}
for _, v := range fw {
var fu PublicUser
var fu entity.PublicUser
for _, f := range follows {
if f.FollowedUser.ID == v.UserID {
fu = f.FollowedUser.GetSafe()
+98
View File
@@ -0,0 +1,98 @@
package follow
import (
"log/slog"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"github.com/sbondCo/Watcharr/feature/auth/authmiddleware"
"github.com/sbondCo/Watcharr/router"
)
type Router struct {
br *router.BaseRouter
service *Service
}
func NewRouter(br *router.BaseRouter, service *Service) *Router {
return &Router{
br,
service,
}
}
func (r *Router) AddRoutes() {
f := r.br.Router.Group("/follow").Use(authmiddleware.AuthRequired(r.br.DB, r.br.Cfg))
// Get users follows
f.GET("", r.GetFollows)
// Follow a user
f.POST("/:toFollowId", r.AddFollowUser)
// Unfollow a user
f.DELETE("/:toUnfollowId", r.DeleteFollow)
// Get follows thoughts on content
// TODO Rename `tmdbId` to `mediaId` to match what it is actually used as (since it works for games).
f.GET("/thoughts/:type/:tmdbId", r.GetFollowsThoughts)
}
// Get users follows // TODO extend to support optionally passing user id as route param, default to current user
func (r *Router) GetFollows(c *gin.Context) {
userId := c.MustGet("userId").(uint)
response, err := r.service.GetFollows(userId)
if err != nil {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
c.JSON(http.StatusOK, response)
}
// Follow a user
func (r *Router) AddFollowUser(c *gin.Context) {
userId := c.MustGet("userId").(uint)
toFollowId, err := strconv.ParseUint(c.Param("toFollowId"), 10, 64)
if err != nil {
slog.Error("failed to convert toFollowId param to uint", "toFollowId", toFollowId)
c.Status(400)
return
}
response, err := r.service.FollowUser(userId, uint(toFollowId))
if err != nil {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
c.JSON(http.StatusOK, response)
}
// Unfollow a user
func (r *Router) DeleteFollow(c *gin.Context) {
userId := c.MustGet("userId").(uint)
toUnfollowId, err := strconv.ParseUint(c.Param("toUnfollowId"), 10, 64)
if err != nil {
slog.Error("failed to convert toUnfollowId param to uint", "toUnfollowId", toUnfollowId)
c.Status(400)
return
}
response, err := r.service.UnfollowUser(userId, uint(toUnfollowId))
if err != nil {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
c.JSON(http.StatusOK, response)
}
// Get follows thoughts on content
func (r *Router) GetFollowsThoughts(c *gin.Context) {
t := c.Param("type")
if t != "movie" && t != "tv" && t != "game" {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: "only movie, tv or game types are supported"})
return
}
userId := c.MustGet("userId").(uint)
response, err := r.service.GetFollowsThoughts(userId, t, c.Param("tmdbId"))
if err != nil {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
c.JSON(http.StatusOK, response)
}
+151
View File
@@ -0,0 +1,151 @@
package game
import (
"errors"
"log/slog"
"strconv"
"github.com/sbondCo/Watcharr/database/entity"
"github.com/sbondCo/Watcharr/domain"
"github.com/sbondCo/Watcharr/image"
"github.com/sbondCo/Watcharr/media/igdb"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
type Service struct {
db *gorm.DB
igdb *igdb.IGDB
activityProvider domain.ActivityAddProvider
}
func NewService(db *gorm.DB, igdb *igdb.IGDB, activityProvider domain.ActivityAddProvider) *Service {
return &Service{
db,
igdb,
activityProvider,
}
}
// Cache(save) game to our table
func (s *Service) saveGame(c *entity.Game, onlyUpdate bool) error {
slog.Info("Saving game to db", "id", c.IgdbID, "name", c.Name)
if c.IgdbID == 0 || c.Name == "" {
slog.Error("saveGame: content missing id or name!", "id", c.IgdbID, "name", c.Name)
return errors.New("game missing id or title")
}
if c.CoverID != "" {
p, err := image.DownloadAndInsertImage(s.db, "https://images.igdb.com/igdb/image/upload/t_cover_big/"+c.CoverID+".png", "games")
if err != nil {
slog.Error("saveGame: Failed to cache game cover.", "error", err)
} else {
slog.Debug("saveGame: Cached game cover", "p", p)
c.PosterID = &p.ID
}
}
var res *gorm.DB
if onlyUpdate {
// We only want to update an existing row, if it exists.
res = s.db.Model(&entity.Game{}).Where("igdb_id = ?", c.IgdbID).Updates(c)
if res.Error != nil {
slog.Error("saveGame: Error updating game in database", "error", res.Error.Error())
return errors.New("failed to update cached game in database")
}
} else {
// On conflict, update existing row with details incase any were updated/missing.
res = s.db.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "igdb_id"}},
DoUpdates: clause.AssignmentColumns([]string{
"name",
"cover_id",
"summary",
"storyline",
"release_date",
"rating",
"rating_count",
"status",
"game_modes",
"genres",
}),
}).Create(&c)
if res.Error != nil {
// Error if anything but unique contraint error
if res.Error != gorm.ErrDuplicatedKey {
slog.Error("saveGame: Error creating game in database", "error", res.Error.Error())
return errors.New("failed to cache game in database")
}
}
}
return nil
}
func (s *Service) cacheGame(g igdb.GameDetailsBasicResponse, onlyUpdate bool) (entity.Game, error) {
slog.Debug("cacheGame", "game_details", g)
var (
gameModes string
genres string
platforms string
)
if len(g.GameModes) > 0 {
for _, v := range g.GameModes {
gameModes += v.Name + "|"
}
}
if len(g.Genres) > 0 {
for _, v := range g.Genres {
genres += v.Name + "|"
}
}
if len(g.Platforms) > 0 {
for _, v := range g.Platforms {
platforms += v.Name + "|"
}
}
c := entity.Game{
IgdbID: g.ID,
Name: g.Name,
CoverID: g.Cover.ImageID,
Summary: g.Summary,
Storyline: g.Storyline,
ReleaseDate: &g.FirstReleaseDate.Time,
Rating: (g.Rating),
RatingCount: g.RatingCount,
Status: g.Status,
Category: g.Category,
GameModes: gameModes,
Genres: genres,
Platforms: platforms,
}
err := s.saveGame(&c, onlyUpdate)
if err != nil {
slog.Error("cacheGame: Failed to save game!", "error", err)
return entity.Game{}, errors.New("failed to save game")
}
return c, nil
}
func (s *Service) GetOrCache(igdbID int) (entity.Game, error) {
var game entity.Game
s.db.Where("igdb_id = ?", igdbID).Find(&game)
// Create game if not found from our db
if game == (entity.Game{}) {
slog.Debug("GetOrCache: Game not in db, fetching...")
resp, err := s.igdb.GameDetailsBasic(strconv.Itoa(igdbID))
if err != nil {
slog.Error("GetOrCache: content api request failed", "error", err)
return game, errors.New("failed to find requested games")
}
game, err = s.cacheGame(resp, false)
if err != nil {
slog.Error("GetOrCache: failed to cache game",
"igdb_id", igdbID,
"err", err)
return game, errors.New("failed to cache content")
}
}
return game, nil
}
+116
View File
@@ -0,0 +1,116 @@
package game
import (
"log/slog"
"net/http"
"github.com/gin-gonic/gin"
"github.com/sbondCo/Watcharr/database/entity"
"github.com/sbondCo/Watcharr/domain"
"github.com/sbondCo/Watcharr/feature/auth/authmiddleware"
"github.com/sbondCo/Watcharr/feature/watched/addedtocontent"
"github.com/sbondCo/Watcharr/media/igdb"
"github.com/sbondCo/Watcharr/router"
"github.com/sbondCo/Watcharr/util"
)
type WatchedProvider interface {
UpdateWatchedLastViewedSeason(userId uint, id uint, seasonNum int) error
GetWatchedItemBySupportedMediaId(userId uint, id uint, t util.SupportedMedia) (entity.Watched, error)
GetWatchedItemsBySupportedMediaIds(userId uint, c []addedtocontent.IdToTypePair) ([]entity.Watched, error)
}
type Router struct {
br *router.BaseRouter
service *Service
watchedProvider WatchedProvider
}
func NewRouter(br *router.BaseRouter, service *Service, watchedProvider WatchedProvider) *Router {
return &Router{
br,
service,
watchedProvider,
}
}
func (r *Router) AddRoutes() {
gamer := r.br.Router.Group("/game").Use(authmiddleware.AuthRequired(nil, r.br.Cfg))
// TODO This config init can be moved to NewRouter, then `gdb` can be accessible in Router for all service funcs.
r.br.Cfg.TWITCH.OnTokenRefreshed(func() {
// Save new token to config when we refresh it.
slog.Debug("GameRoutes: token refreshed.. saving to config.")
if err := r.br.Cfg.Write(); err != nil {
slog.Error("GameRoutes: failed to save refreshed token to config.", "error", err)
}
})
err := r.br.Cfg.TWITCH.Init()
// Save cfg if init succeeded, this will save our access token
if err != nil {
slog.Error("GameRoutes: Twitch init failed!", "error", err)
}
// Game details for game page
gamer.GET("/:id", r.GetGameDetails)
// IMPORTANT: Routes below only for admins!
gamer.Use(authmiddleware.AuthRequired(r.br.DB, r.br.Cfg), authmiddleware.AdminRequired())
{
gamer.POST("/config", r.UpdateConfig)
}
}
func (r *Router) GetGameDetails(c *gin.Context) {
userId := c.MustGet("userId").(uint)
if c.Param("id") == "" {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: "an id was not provided"})
return
}
content, err := r.br.Cfg.TWITCH.GameDetails(c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
return
}
contentAsMedia := content.AsMedia()
if err := addedtocontent.AddSingularAndList(
r.watchedProvider,
userId,
contentAsMedia,
func(w *entity.Watched) {
contentAsMedia.Watched = domain.NewWatchedDtoForContentPage(w)
},
[]*addedtocontent.AddListCall[domain.Media]{
addedtocontent.NewAddListCall(
contentAsMedia.Similar,
func(i int, w *entity.Watched) {
contentAsMedia.Similar[i].Watched = domain.NewWatchedDtoForLists(w)
},
),
},
); err != nil {
slog.Error("GetGameDetails: Failed to add watched to content!", "error", err)
c.JSON(
http.StatusInternalServerError,
router.ErrorResponse{Error: "failed to add watched data to response"},
)
return
}
c.JSON(http.StatusOK, contentAsMedia)
}
func (r *Router) UpdateConfig(c *gin.Context) {
var ar igdb.IGDB
err := c.ShouldBindJSON(&ar)
if err == nil {
err := r.br.Cfg.SaveTwitchConfig(ar)
if err != nil {
c.JSON(http.StatusForbidden, router.ErrorResponse{Error: err.Error()})
return
}
// gdb = &b.cfg.TWITCH
c.Status(http.StatusOK)
return
}
c.AbortWithStatusJSON(http.StatusBadRequest, router.ErrorResponse{Error: err.Error()})
}
+378
View File
@@ -0,0 +1,378 @@
package imprt
import (
"encoding/json"
"errors"
"log/slog"
"strconv"
"strings"
"time"
"github.com/sbondCo/Watcharr/database/entity"
"github.com/sbondCo/Watcharr/domain"
"github.com/sbondCo/Watcharr/feature/watched"
"github.com/sbondCo/Watcharr/feature/watched/episode"
"github.com/sbondCo/Watcharr/feature/watched/season"
"github.com/sbondCo/Watcharr/media/tmdb"
"github.com/sbondCo/Watcharr/util"
"gorm.io/gorm"
)
type WatchedProvider interface {
AddWatched(userId uint, ar domain.WatchedAddRequest, at entity.ActivityType) (entity.Watched, error)
GetWatchedItemByTmdbId(userId uint, tmdbId uint, contentType entity.ContentType) (entity.Watched, error)
}
type WatchedSeasonProvider interface {
AddWatchedSeason(userId uint, ar season.WatchedSeasonAddRequest) (season.WatchedSeasonAddResponse, error)
}
type WatchedEpisodeProvider interface {
AddWatchedEpisodes(userId uint, ar episode.WatchedEpisodeAddRequest) (episode.WatchedEpisodeAddResponse, error)
}
type ContentProvider interface {
SearchContent(query string, pageNum int) (tmdb.TMDBSearchMultiResponse, error)
SearchByExternalId(id string, source string) (tmdb.TMDBSearchMultiResponse, error)
MovieDetails(id string, country string, rParams map[string]string) (tmdb.TMDBMovieDetails, error)
TvDetails(id string, country string, rParams map[string]string) (tmdb.TMDBShowDetails, error)
}
type TagProvider interface {
AddTag(userId uint, tr domain.TagAddRequest) (entity.Tag, error)
GetTagByNameAndColor(userId uint, tagName string, tagColor string, tagBgColor string) (entity.Tag, error)
}
type Service struct {
db *gorm.DB
wp WatchedProvider
wsp WatchedSeasonProvider
wep WatchedEpisodeProvider
cp ContentProvider
activityProvider domain.ActivityAddProvider
tagProvider TagProvider
}
func NewService(
db *gorm.DB,
wp WatchedProvider,
wsp WatchedSeasonProvider,
wep WatchedEpisodeProvider,
cp ContentProvider,
activityProvider domain.ActivityAddProvider,
tagProvider TagProvider,
) *Service {
return &Service{
db,
wp,
wsp,
wep,
cp,
activityProvider,
tagProvider,
}
}
// TODO Support game importing
func (s *Service) ImportContent(
userId uint,
ar domain.ImportRequest,
) (domain.ImportResponse, error) {
slog.Debug("import: Processing request:", "request", ar)
// If tmdbId and type passed in request body
// we dont need to use a search tmdb request.
// Retrieve the details directly.
if ar.TmdbID != 0 && (ar.Type == entity.MOVIE || ar.Type == entity.SHOW) {
tid := strconv.Itoa(ar.TmdbID)
if ar.Type == entity.MOVIE {
cr, err := s.cp.MovieDetails(tid, "", map[string]string{})
if err != nil {
return domain.ImportResponse{}, errors.New("movie details request failed")
}
slog.Debug("import: by tmdbid of movie", "cr", cr)
return s.SuccessfulImport(userId, cr.ID, util.SupportedMediaMovie, ar)
} else if ar.Type == entity.SHOW {
cr, err := s.cp.TvDetails(tid, "", map[string]string{})
if err != nil {
return domain.ImportResponse{}, errors.New("tv details request failed")
}
slog.Debug("import: by tmdbid of tv", "cr", cr)
return s.SuccessfulImport(userId, cr.ID, util.SupportedMediaShow, ar)
}
}
// If imdb id passed, attempt to get content with it
if ar.ImdbID != "" && (ar.Type == entity.MOVIE || ar.Type == entity.SHOW || ar.Type == entity.SHOW_EPISODE) {
if imdbResp, err := s.cp.SearchByExternalId(ar.ImdbID, "imdb"); err == nil {
if len(imdbResp.Results) == 1 {
onlyResult := imdbResp.Results[0]
if onlyResult.MediaType == string(entity.MOVIE) || onlyResult.MediaType == string(entity.SHOW) {
// Will only be one result
slog.Debug("import: importing imdb match", "imdb_id", ar.ImdbID, "tmdb_id_thatwasfound", onlyResult.ID)
return s.SuccessfulImport(userId, onlyResult.ID, util.SupportedMedia(onlyResult.MediaType), ar)
} else if onlyResult.MediaType == string(entity.SHOW_EPISODE) {
// Handle episodes differently.
// Clients must import tv episodes last so that the actual show can be imported first
// will fail if watched entry isn't imported first or already exists (we won't make it here).
w, e := s.wp.GetWatchedItemByTmdbId(userId, uint(onlyResult.ShowId), "tv")
if e != nil {
slog.Error("import: imdb match: Failed to add watched episode (failed to find watched item, it must exist!).", "rq", ar, "error", err)
return domain.ImportResponse{Type: domain.IMPORT_FAILED}, nil
}
ws, err := s.wep.AddWatchedEpisodes(userId, episode.WatchedEpisodeAddRequest{
WatchedID: w.ID,
SeasonNumber: onlyResult.SeasonNumber,
EpisodeNumber: onlyResult.EpisodeNumber,
Status: ar.Status,
Rating: int8(ar.Rating),
AddActivityDate: *ar.RatingCustomDate,
})
if err != nil {
slog.Error("import: imdb match: Failed to add watched episode.", "rq", ar, "error", err)
return domain.ImportResponse{Type: domain.IMPORT_FAILED}, nil
} else {
w.WatchedEpisodes = ws.WatchedEpisodes
return domain.ImportResponse{Type: domain.IMPORT_SUCCESS, WatchedEntry: w}, nil
}
} else {
slog.Error("import: imdb match has unsupported media type.", "media_type", imdbResp.Results[0].MediaType, "rq", ar)
return domain.ImportResponse{Type: domain.IMPORT_FAILED}, nil
}
} else {
// Content in tmdb may just be missing a related imdb id, so allow search to continue by name below.
slog.Warn("import: No results for search by imdb id.. search will contiue by content name.", "rq", ar)
}
} else {
slog.Warn("import: Failed to get content by imdb id.. search will contiue by content name.", "rq", ar)
}
}
// tmdbId not passed.. search for the content by name.
sr, err := s.cp.SearchContent(ar.Name, 1)
if err != nil {
slog.Error("import: content search failed", "error", err)
return domain.ImportResponse{}, errors.New("content search failed")
}
// potential matches
pMatches := []domain.Media{}
for _, r := range sr.Results {
if r.MediaType != "person" {
pMatches = append(pMatches, r.AsMedia())
}
}
resLen := len(pMatches)
slog.Debug("import: potential matches", "num_found", resLen)
if resLen <= 0 {
slog.Debug("import: returning IMPORT_NOTFOUND")
return domain.ImportResponse{Type: domain.IMPORT_NOTFOUND}, nil
} else if resLen > 1 {
slog.Debug("import: multiple results found")
// If there are multiple responses, but only one item
// from the results is a 100% match for the imported
// items name, then consider successful match with that.
perfectMatches := []domain.Media{}
for _, r := range pMatches {
itemReleaseYear := 0
// Only parse dates to find year if the import request has provided
// a year to comparisons.. otherwise don't do it to save some performance juice.
if ar.Year != 0 {
if !r.ReleaseDate.IsZero() {
itemReleaseYear = r.ReleaseDate.Year()
} else {
slog.Error("import: failed to check item release year, it can't be used for matching",
"error", err, "item", r)
}
}
if strings.EqualFold(r.Name, ar.Name) {
slog.Debug("import: multiple results processing: found a perfect name match", "itemReleaseYear", itemReleaseYear, "ar.Year", ar.Year, "match", r)
// If we have a year for comparison, force a check to compare them for a
// match to be deemed perfect.
// `itemReleaseYear` can only ever have a value if `ar.Year` has one, so this
// check is safe as is.
if itemReleaseYear != 0 || ar.Year != 0 {
if itemReleaseYear == ar.Year {
perfectMatches = append(perfectMatches, r)
slog.Debug("import: multiple results processing: name match also matched year")
} else {
slog.Debug("import: multiple results processing: name match didnt match year")
}
continue
}
// Otherwise, if we don't have valid dates to compare, append the perfect name match anyways.
slog.Debug("import: multiple results processing: name match didn't have valid release year, adding to matches anyways")
perfectMatches = append(perfectMatches, r)
}
}
// If one perfect match found, import it
pmLen := len(perfectMatches)
if pmLen == 1 && perfectMatches[0].IDs.TMDB != 0 {
slog.Debug("import: importing from perfect match")
return s.SuccessfulImport(
userId,
perfectMatches[0].IDs.TMDB,
perfectMatches[0].GetMediaType(),
ar)
}
slog.Debug("import: returning all potential matches")
return domain.ImportResponse{Type: domain.IMPORT_MULTI, Results: pMatches}, nil
} else {
slog.Debug("import: success.. only found one result")
return s.SuccessfulImport(
userId,
pMatches[0].IDs.TMDB,
pMatches[0].GetMediaType(),
ar)
}
}
func (s *Service) SuccessfulImport(
userId uint,
contentId int,
contentType util.SupportedMedia,
ar domain.ImportRequest,
) (domain.ImportResponse, error) {
status := entity.FINISHED
if ar.Status != "" {
status = ar.Status
}
// Get the latest date from DatesWatched if we have any.
var wDate time.Time
if len(ar.DatesWatched) > 0 {
for _, dw := range ar.DatesWatched {
if dw.After(wDate) {
wDate = dw
}
}
}
w, err := s.wp.AddWatched(userId, domain.WatchedAddRequest{
Status: status,
TMDBID: contentId,
ContentType: contentType,
Rating: ar.Rating,
Thoughts: ar.Thoughts,
WatchedDate: wDate,
}, entity.IMPORTED_WATCHED)
if err != nil {
if err.Error() == "content already on watched list" {
slog.Error("successfulImport: unique constraint hit.. show must already be on watch list", "error", err)
return domain.ImportResponse{Type: domain.IMPORT_EXISTS}, nil
}
slog.Error("successfulImport: Failed to add content as watched", "error", err)
return domain.ImportResponse{Type: domain.IMPORT_FAILED}, nil
}
// Add activity of the original time the show was added to the users
// watchlist on whichever platform they are coming from.
if ar.RatingCustomDate != nil {
var addedActivity entity.Activity
if len(w.Activity) > 0 {
activityJson, _ := json.Marshal(map[string]interface{}{
"rating": ar.Rating,
"linkedActivity": w.Activity[0].ID,
})
addedActivity, _ = s.activityProvider.AddActivity(userId, domain.ActivityAddRequest{WatchedID: w.ID, Type: entity.IMPORTED_RATING, Data: string(activityJson), CustomDate: ar.RatingCustomDate})
} else {
addedActivity, _ = s.activityProvider.AddActivity(userId, domain.ActivityAddRequest{WatchedID: w.ID, Type: entity.IMPORTED_RATING, Data: strconv.Itoa(int(ar.Rating)), CustomDate: ar.RatingCustomDate})
}
w.Activity = append(w.Activity, addedActivity)
}
// Add all dates watched as activity, if any
if len(ar.DatesWatched) > 0 {
for _, v := range ar.DatesWatched {
customDate := v
addedActivity, err := s.activityProvider.AddActivity(userId, domain.ActivityAddRequest{WatchedID: w.ID, Type: entity.IMPORTED_ADDED_WATCHED, CustomDate: &customDate})
if err == nil {
w.Activity = append(w.Activity, addedActivity)
} else {
slog.Error("successfulImport: Failed to add dateswatched activity.", "date", v, "error", err)
}
}
}
// Add all activity passed in.
// Probably was is a Watcharr export being imported, so it'll have all it's activity too.
if len(ar.Activity) > 0 {
slog.Debug("successfulImport: Importing activity")
for i, v := range ar.Activity {
activityDate := ar.Activity[i].CustomDate
if activityDate == nil || activityDate.IsZero() {
activityDate = &ar.Activity[i].CreatedAt
}
addedActivity, err := s.activityProvider.AddActivity(userId, domain.ActivityAddRequest{WatchedID: w.ID, Type: v.Type, Data: v.Data, CustomDate: activityDate})
if err == nil {
w.Activity = append(w.Activity, addedActivity)
} else {
slog.Error("successfulImport: Failed to add imported activity.", "full_object", v, "error", err)
}
}
}
// Import watched seasons, if any
if len(ar.WatchedSeason) > 0 {
slog.Debug("successfulImport: Importing watched seasons")
for _, v := range ar.WatchedSeason {
ws, err := s.wsp.AddWatchedSeason(userId, season.WatchedSeasonAddRequest{
WatchedID: w.ID,
SeasonNumber: v.SeasonNumber,
Status: v.Status,
Rating: v.Rating,
AddActivityDate: v.CreatedAt,
})
if err != nil {
slog.Error("successfulImport: Failed to add watched season.", "error", err)
continue
}
w.WatchedSeasons = ws.WatchedSeasons
}
}
// Import watched episodes, if any
if len(ar.WatchedEpisodes) > 0 {
slog.Debug("successfulImport: Importing watched episodes")
for _, v := range ar.WatchedEpisodes {
ws, err := s.wep.AddWatchedEpisodes(userId, episode.WatchedEpisodeAddRequest{
WatchedID: w.ID,
SeasonNumber: v.SeasonNumber,
EpisodeNumber: v.EpisodeNumber,
Status: v.Status,
Rating: v.Rating,
AddActivityDate: v.CreatedAt,
})
if err != nil {
slog.Error("successfulImport: Failed to add watched episodes.", "error", err)
continue
}
w.WatchedEpisodes = ws.WatchedEpisodes
}
}
// Import tags, if any
if len(ar.Tags) > 0 {
// Create tags if they dont exist
slog.Debug("successfulImport: Importing tags")
for _, v := range ar.Tags {
// Check if tag exists
var t entity.Tag
t, err := s.tagProvider.GetTagByNameAndColor(userId, v.Name, v.Color, v.BgColor)
if err != nil && err.Error() != "tag does not exist" {
slog.Error("successfulImport: Failed to check for an existing tag", "name", v.Name, "error", err)
continue
}
if t.ID == 0 {
tag, err := s.tagProvider.AddTag(userId, domain.TagAddRequest{
Name: v.Name,
Color: v.Color,
BgColor: v.BgColor,
})
if err != nil {
slog.Error("successfulImport: Failed to add a tag.", "name", v.Name, "error", err)
continue
}
t = tag
}
// Associate the watched entry with the tag
err = watched.AddWatchedToTag(s.db, userId, t.ID, w.ID)
if err != nil {
slog.Error("successfulImport: Failed to associate watched entry with tag.", "error", err)
continue
}
w.Tags = append(w.Tags, t)
}
}
return domain.ImportResponse{Type: domain.IMPORT_SUCCESS, WatchedEntry: w}, nil
}
@@ -1,6 +1,6 @@
// Trakt.tv importer.
package main
package imprt
import (
"encoding/json"
@@ -13,12 +13,17 @@ import (
"strconv"
"time"
"gorm.io/gorm"
"github.com/sbondCo/Watcharr/database/dbmodel"
"github.com/sbondCo/Watcharr/database/entity"
"github.com/sbondCo/Watcharr/domain"
"github.com/sbondCo/Watcharr/job"
)
type TraktImportRequest struct {
// Username of public trakt user to import from.
Username string `json:"username" binding:"required"`
// An optional custom api key to use for the requests.
ApiKey string `json:"apiKey"`
}
type TraktUser struct {
@@ -93,48 +98,69 @@ type TraktImportResponse struct {
JobId string `json:"jobId"`
}
type TraktService struct {
s *Service
}
func NewTraktService(s *Service) *TraktService {
return &TraktService{
s,
}
}
// TODO we could support trakt list imports when we support a similar feature (tags will function as custom lists when done #199)
func startTraktImport(db *gorm.DB, jobId string, userId uint, traktUsername string) {
func (t *TraktService) startTraktImport(jobId string, userId uint, req TraktImportRequest) {
// Get trakt user. We want to get their profile `slug` for use in
// next requests and we can check their profile isn't private while here.
var traktUser TraktUser
_, err := traktAPIRequest("users/"+traktUsername, map[string]string{}, &traktUser)
_, err := t.traktAPIRequest(
"users/"+req.Username,
map[string]string{},
&traktUser,
req.ApiKey)
if err != nil {
slog.Error("startTraktImport: Failed to get users profile", "error", err, "trakt_user", traktUser)
addJobError(jobId, userId, "failed to request trakt profile from api")
updateJobStatus(jobId, userId, JOB_CANCELLED)
slog.Error("startTraktImport: Failed to get users profile",
"error", err,
"trakt_user", traktUser)
job.AddJobError(jobId, userId, "failed to request trakt profile from api")
job.UpdateJobStatus(jobId, userId, job.JOB_CANCELLED)
return
}
if traktUser.Private {
slog.Error("startTraktImport: Users profile is private. Cannot continue with import.")
addJobError(jobId, userId, "trakt profile is private")
updateJobStatus(jobId, userId, JOB_CANCELLED)
job.AddJobError(jobId, userId, "trakt profile is private")
job.UpdateJobStatus(jobId, userId, job.JOB_CANCELLED)
return
}
userSlug := traktUser.IDs.Slug
// Everything will be added to this map for importing at the end.
toImport := map[string]ImportRequest{}
toImport := map[string]domain.ImportRequest{}
// Process all history for this user (in chunks of 1000).
var history []TraktHistory
slog.Debug("startTraktImport: Getting first history page")
historyHeaders, err := traktAPIRequest("users/"+userSlug+"/history", map[string]string{"limit": "1000"}, &history)
historyHeaders, err := t.traktAPIRequest(
"users/"+userSlug+"/history",
map[string]string{"limit": "1000"},
&history,
req.ApiKey)
if err != nil {
// FATAL if we can't get the users history, we probably shouldn't continue (to ratings/watchlist below).
// FATAL if we can't get the users history, we probably shouldn't continue
// (to ratings/watchlist below).
slog.Error("startTraktImport: Failed to get users history", "error", err)
addJobError(jobId, userId, "failed to get your history")
job.AddJobError(jobId, userId, "failed to get your history")
return
} else {
pageCount := historyHeaders.Get("x-pagination-page-count")
slog.Debug("startTraktImport: Got first history page", "page_count", pageCount)
if pageCount == "" {
slog.Error("startTraktImport: Failed to get history page count!", "page_count", pageCount)
addJobError(jobId, userId, "Failed to get history page count")
job.AddJobError(jobId, userId, "Failed to get history page count")
return
}
pageCountNum, err := strconv.Atoi(pageCount)
if err != nil {
slog.Error("startTraktImport: Failed to parse history page count into an int!", "error", err)
addJobError(jobId, userId, "Failed to parse history page count: "+pageCount)
job.AddJobError(jobId, userId, "Failed to parse history page count: "+pageCount)
return
}
rProc := func(v TraktHistory) {
@@ -147,11 +173,11 @@ func startTraktImport(db *gorm.DB, jobId string, userId uint, traktUsername stri
collectingText = v.Movie.Title
}
if collectingText != "" {
updateJobCurrentTask(jobId, userId, "collecting "+collectingText)
job.UpdateJobCurrentTask(jobId, userId, "collecting "+collectingText)
}
err = processTraktHistoryItem(v, toImport)
err = t.processTraktHistoryItem(v, toImport)
if err != nil {
addJobError(jobId, userId, err.Error())
job.AddJobError(jobId, userId, err.Error())
}
}
// Process first page of history (next pages processed below)
@@ -160,10 +186,14 @@ func startTraktImport(db *gorm.DB, jobId string, userId uint, traktUsername stri
}
for i := range pageCountNum {
slog.Debug("startTraktImport: Getting history page", "page_num", i)
_, err := traktAPIRequest("users/"+userSlug+"/history", map[string]string{"limit": "1000", "page": strconv.Itoa(i)}, &history)
_, err := t.traktAPIRequest(
"users/"+userSlug+"/history",
map[string]string{"limit": "1000", "page": strconv.Itoa(i)},
&history,
req.ApiKey)
if err != nil {
slog.Error("startTraktImport: Failed to get a history page", "page_num", i, "error", err)
addJobError(jobId, userId, "Failed to get history page: "+strconv.Itoa(i))
job.AddJobError(jobId, userId, "Failed to get history page: "+strconv.Itoa(i))
} else {
for _, v := range history {
rProc(v)
@@ -176,33 +206,37 @@ func startTraktImport(db *gorm.DB, jobId string, userId uint, traktUsername stri
// Get watchlist for PLANNED items
slog.Info("startTraktImport: Getting whole watchlist")
var watchlist TraktWatchlist
_, err = traktAPIRequest("users/"+userSlug+"/watchlist", map[string]string{}, &watchlist)
_, err = t.traktAPIRequest(
"users/"+userSlug+"/watchlist",
map[string]string{},
&watchlist,
req.ApiKey)
if err != nil {
slog.Error("startTraktImport: Failed to get users watchlist! Cannot import planned content.", "error", err)
addJobError(jobId, userId, "failed to get your watchlist (planned items cannot be imported)")
job.AddJobError(jobId, userId, "failed to get your watchlist (planned items cannot be imported)")
} else {
slog.Debug("startTraktImport: Successfully got whole watchlist")
for _, v := range watchlist {
slog.Debug("startTraktImport: Processing watchlist item", "item", v)
var (
title string
contentType ContentType
contentType entity.ContentType
tmdbId int
)
if v.Type == "show" || v.Type == "episode" {
title = v.Show.Title
tmdbId = v.Show.Ids.Tmdb
contentType = SHOW
contentType = entity.SHOW
if v.Type == "episode" {
title = v.Episode.Title
}
} else if v.Type == "movie" {
title = v.Movie.Title
tmdbId = v.Movie.Ids.Tmdb
contentType = MOVIE
contentType = entity.MOVIE
}
updateJobCurrentTask(jobId, userId, "setting status for "+title)
mapKey := makeTraktMapKey(contentType, tmdbId)
job.UpdateJobCurrentTask(jobId, userId, "setting status for "+title)
mapKey := t.makeTraktMapKey(contentType, tmdbId)
if mv, ok := toImport[mapKey]; ok {
// If item already exists in toImport, set its status to planned.
if v.Type == "episode" {
@@ -210,25 +244,25 @@ func startTraktImport(db *gorm.DB, jobId string, userId uint, traktUsername stri
weFound := false
for i, we := range mv.WatchedEpisodes {
if we.SeasonNumber == v.Episode.Season && we.EpisodeNumber == v.Episode.Number {
we.Status = PLANNED
we.Status = entity.PLANNED
mv.WatchedEpisodes[i] = we
weFound = true
break
}
}
if !weFound {
mv.WatchedEpisodes = append(mv.WatchedEpisodes, WatchedEpisode{
mv.WatchedEpisodes = append(mv.WatchedEpisodes, entity.WatchedEpisode{
SeasonNumber: v.Episode.Season,
EpisodeNumber: v.Episode.Number,
Status: PLANNED,
GormModel: GormModel{
Status: entity.PLANNED,
GormModel: dbmodel.GormModel{
CreatedAt: v.ListedAt,
},
})
}
toImport[mapKey] = mv
} else {
mv.Status = PLANNED
mv.Status = entity.PLANNED
if v.Notes != "" {
// episodes dont support notes in watcharr
mv.Thoughts = v.Notes
@@ -237,17 +271,17 @@ func startTraktImport(db *gorm.DB, jobId string, userId uint, traktUsername stri
}
} else {
// If the item does not exist in toImport, create it and set it to planned.
ti := ImportRequest{
ti := domain.ImportRequest{
Type: contentType,
TmdbID: tmdbId,
Status: PLANNED,
Status: entity.PLANNED,
}
if v.Type == "episode" {
ti.WatchedEpisodes = []WatchedEpisode{{
ti.WatchedEpisodes = []entity.WatchedEpisode{{
SeasonNumber: v.Episode.Season,
EpisodeNumber: v.Episode.Number,
Status: PLANNED,
GormModel: GormModel{
Status: entity.PLANNED,
GormModel: dbmodel.GormModel{
CreatedAt: v.ListedAt,
},
}}
@@ -262,17 +296,21 @@ func startTraktImport(db *gorm.DB, jobId string, userId uint, traktUsername stri
// Process ratings
slog.Info("startTraktImport: Getting all ratings")
var ratings TraktRatings
_, err = traktAPIRequest("users/"+userSlug+"/ratings", map[string]string{}, &ratings)
_, err = t.traktAPIRequest(
"users/"+userSlug+"/ratings",
map[string]string{},
&ratings,
req.ApiKey)
if err != nil {
slog.Error("startTraktImport: Failed to get users ratings!", "error", err)
addJobError(jobId, userId, "failed to get your ratings (content ratings cannot be imported)")
job.AddJobError(jobId, userId, "failed to get your ratings (content ratings cannot be imported)")
} else {
slog.Debug("startTraktImport: Successfully got all ratings")
for _, v := range ratings {
slog.Debug("startTraktImport: Processing rating item", "item", v)
var (
title string
contentType ContentType
contentType entity.ContentType
tmdbId int
traktSlug string
)
@@ -280,7 +318,7 @@ func startTraktImport(db *gorm.DB, jobId string, userId uint, traktUsername stri
title = v.Show.Title
tmdbId = v.Show.Ids.Tmdb
traktSlug = v.Show.Ids.Slug
contentType = SHOW
contentType = entity.SHOW
if v.Type == "episode" {
title = v.Episode.Title
traktSlug = v.Episode.Ids.Slug
@@ -288,11 +326,11 @@ func startTraktImport(db *gorm.DB, jobId string, userId uint, traktUsername stri
} else if v.Type == "movie" {
title = v.Movie.Title
tmdbId = v.Movie.Ids.Tmdb
contentType = MOVIE
contentType = entity.MOVIE
traktSlug = v.Movie.Ids.Slug
}
updateJobCurrentTask(jobId, userId, fmt.Sprintf("setting rating of %d for %s", v.Rating, title))
mapKey := makeTraktMapKey(contentType, tmdbId)
job.UpdateJobCurrentTask(jobId, userId, fmt.Sprintf("setting rating of %d for %s", v.Rating, title))
mapKey := t.makeTraktMapKey(contentType, tmdbId)
if mv, ok := toImport[mapKey]; ok {
if v.Type == "episode" {
// For episode entries, we have to find the WatchedEpisode to set its rating.
@@ -307,7 +345,7 @@ func startTraktImport(db *gorm.DB, jobId string, userId uint, traktUsername stri
}
toImport[mapKey] = mv
if !epFound {
addJobError(jobId, userId, fmt.Sprintf("episode rating of %d for %s not imported. The episode does not exist in your history or watchlist.", v.Rating, title))
job.AddJobError(jobId, userId, fmt.Sprintf("episode rating of %d for %s not imported. The episode does not exist in your history or watchlist.", v.Rating, title))
}
} else {
mv.Rating = float64(v.Rating)
@@ -315,43 +353,43 @@ func startTraktImport(db *gorm.DB, jobId string, userId uint, traktUsername stri
}
} else {
// Item should be in toImport by now (from history or watchlist) if it has a rating, otherwise we won't import it
addJobError(jobId, userId, fmt.Sprintf("cannot import rating of %d for %s. The main content does not exist in your history or watchlist. type: %s traktSlug: %s", v.Rating, title, v.Type, traktSlug))
job.AddJobError(jobId, userId, fmt.Sprintf("cannot import rating of %d for %s. The main content does not exist in your history or watchlist. type: %s traktSlug: %s", v.Rating, title, v.Type, traktSlug))
}
}
}
// Loop over `toImport` and finally import everything.
for _, v := range toImport {
_, err := importContent(db, userId, v)
_, err := t.s.ImportContent(userId, v)
if err != nil {
slog.Error("startTraktImport: Failed to do import on content!", "error", err, "import_obj", v)
addJobError(jobId, userId, fmt.Sprintf("Failed to import %s as %s. tmdbId: %d", v.Type, v.Status, v.TmdbID))
job.AddJobError(jobId, userId, fmt.Sprintf("Failed to import %s as %s. tmdbId: %d", v.Type, v.Status, v.TmdbID))
}
}
// We are donezo
updateJobStatus(jobId, userId, JOB_DONE)
job.UpdateJobStatus(jobId, userId, job.JOB_DONE)
}
func processTraktHistoryItem(v TraktHistory, toImport map[string]ImportRequest) error {
func (t *TraktService) processTraktHistoryItem(v TraktHistory, toImport map[string]domain.ImportRequest) error {
var (
title string
traktId int
tmdbId int
contentType ContentType
watchedEpisode WatchedEpisode
contentType entity.ContentType
watchedEpisode entity.WatchedEpisode
)
if v.Type == "show" || v.Type == "episode" {
title = v.Show.Title
traktId = v.Show.Ids.Trakt
tmdbId = v.Show.Ids.Tmdb
contentType = SHOW
contentType = entity.SHOW
if v.Type == "episode" {
traktId = v.Episode.Ids.Trakt
watchedEpisode = WatchedEpisode{
watchedEpisode = entity.WatchedEpisode{
SeasonNumber: v.Episode.Season,
EpisodeNumber: v.Episode.Number,
Status: FINISHED,
Status: entity.FINISHED,
// Rating: ,
GormModel: GormModel{
GormModel: dbmodel.GormModel{
CreatedAt: v.WatchedAt,
},
}
@@ -363,35 +401,41 @@ func processTraktHistoryItem(v TraktHistory, toImport map[string]ImportRequest)
title = v.Movie.Title
traktId = v.Movie.Ids.Trakt
tmdbId = v.Movie.Ids.Tmdb
contentType = MOVIE
contentType = entity.MOVIE
slog.Debug("processTraktHistoryItem: Processing a movie.", "contentTitle", title, "contentTmdbId", tmdbId)
}
if tmdbId == 0 {
slog.Debug("processTraktHistoryItem: Item had no tmdbId. Cannot process.")
return errors.New("Failed to process history: " + title + " type:" + v.Type + " trakt id:" + strconv.Itoa(traktId) + " tmdb id:" + strconv.Itoa(tmdbId) + " error:" + "item had no tmdb id")
}
mapKey := makeTraktMapKey(contentType, tmdbId)
mapKey := t.makeTraktMapKey(contentType, tmdbId)
if e, ok := toImport[mapKey]; ok {
e.WatchedEpisodes = append(toImport[mapKey].WatchedEpisodes, watchedEpisode)
toImport[mapKey] = e
} else {
toImport[mapKey] = ImportRequest{
toImport[mapKey] = domain.ImportRequest{
Type: contentType,
TmdbID: tmdbId,
Status: FINISHED,
Status: entity.FINISHED,
DatesWatched: []time.Time{v.WatchedAt},
WatchedEpisodes: []WatchedEpisode{watchedEpisode},
WatchedEpisodes: []entity.WatchedEpisode{watchedEpisode},
}
}
return nil
}
// `tmdbId` is for the movie or show (not for episodes).
func makeTraktMapKey(ct ContentType, tmdbId int) string {
func (t *TraktService) makeTraktMapKey(ct entity.ContentType, tmdbId int) string {
return string(ct) + strconv.Itoa(tmdbId)
}
func traktAPIRequest(ep string, p map[string]string, resp interface{}) (http.Header, error) {
func (t *TraktService) traktAPIRequest(
ep string,
p map[string]string,
resp interface{},
// If not provided, a default key is used
apiKey string,
) (http.Header, error) {
base, err := url.Parse("https://api.trakt.tv")
if err != nil {
return map[string][]string{}, errors.New("failed to parse api uri")
@@ -409,7 +453,12 @@ func traktAPIRequest(ep string, p map[string]string, resp interface{}) (http.Hea
if err != nil {
return map[string][]string{}, err
}
req.Header.Add("trakt-api-key", "c481cb044dcd58d83f3fde113741d1e28d19c1bef1bcbfcb9acedee222f3a673")
traktApiKey := "1309b3a473f6718ba0586eddf4b8caccd8733ec74ac47aa6eadc23331d9c7ab4"
if apiKey != "" {
traktApiKey = apiKey
}
// trakt-api-key is your Trakt Apps 'Client ID'.
req.Header.Add("trakt-api-key", traktApiKey)
req.Header.Add("trakt-api-version", "2")
req.Header.Add("Content-type", "application/json")
res, err := http.DefaultClient.Do(req)
@@ -432,24 +481,27 @@ func traktAPIRequest(ep string, p map[string]string, resp interface{}) (http.Hea
return res.Header, nil
}
func traktImportWatched(
db *gorm.DB,
func (t *TraktService) TraktImportWatched(
userId uint,
traktUsername string,
req TraktImportRequest,
) (TraktImportResponse, error) {
jobId, err := addUniqueJob("trakt_import", userId)
jobId, err := job.AddUniqueJob("trakt_import", userId)
if err != nil {
slog.Error("traktSyncWatched: Failed to create a job", "error", err)
slog.Error("TraktImportWatched: Failed to create a job",
"error", err)
return TraktImportResponse{}, err
}
updateJobStatus(jobId, userId, JOB_RUNNING)
job.UpdateJobStatus(jobId, userId, job.JOB_RUNNING)
go startTraktImport(
db,
if req.ApiKey != "" {
slog.Info("TraktImportWatched: A custom api key was provided for this import.")
}
go t.startTraktImport(
jobId,
userId,
traktUsername,
req,
)
return TraktImportResponse{JobId: jobId}, nil
+65
View File
@@ -0,0 +1,65 @@
package imprt
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/sbondCo/Watcharr/domain"
"github.com/sbondCo/Watcharr/feature/auth/authmiddleware"
"github.com/sbondCo/Watcharr/router"
)
type Router struct {
br *router.BaseRouter
service *Service
traktService *TraktService
}
func NewRouter(br *router.BaseRouter, service *Service, traktService *TraktService) *Router {
return &Router{
br,
service,
traktService,
}
}
func (r *Router) AddRoutes() {
imprt := r.br.Router.Group("/import").Use(authmiddleware.AuthRequired(nil, r.br.Cfg))
imprt.POST("", r.ImportContent)
imprt.POST("/trakt", r.ImportTrakt)
}
// Import content (the client handle processing data and sends it to us in a uniform way).
func (r *Router) ImportContent(c *gin.Context) {
userId := c.MustGet("userId").(uint)
var ar domain.ImportRequest
err := c.ShouldBindJSON(&ar)
if err == nil {
response, err := r.service.ImportContent(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()})
}
// Import Trakt.
func (r *Router) ImportTrakt(c *gin.Context) {
userId := c.MustGet("userId").(uint)
var ar TraktImportRequest
err := c.ShouldBindJSON(&ar)
if err == nil {
response, err := r.traktService.TraktImportWatched(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()})
}
@@ -1,4 +1,4 @@
package main
package jellyfin
import (
"bytes"
@@ -11,6 +11,8 @@ import (
"time"
"github.com/gin-gonic/gin"
"github.com/sbondCo/Watcharr/config"
"github.com/sbondCo/Watcharr/database/entity"
)
type JellyfinItemSearchResponse struct {
@@ -46,21 +48,31 @@ type JFContentFindResponse struct {
Url string `json:"url"`
}
type Service struct {
cfg *config.ServerConfig
}
func NewService(cfg *config.ServerConfig) *Service {
return &Service{
cfg: cfg,
}
}
// Jellyfin access middleware, ensures user is a jellyfin user.
// To be ran after AuthRequired middleware with extra data.
func JellyfinAccessRequired() gin.HandlerFunc {
func (s *Service) JellyfinAccessRequired(cfg *config.ServerConfig) gin.HandlerFunc {
return func(c *gin.Context) {
userId := c.MustGet("userId").(uint)
slog.Debug("JellyfinAccessRequired middleware hit", "user_id", userId)
userType := c.MustGet("userType").(UserType)
userType := c.MustGet("userType").(entity.UserType)
userThirdPartyId := c.MustGet("userThirdPartyId").(string)
userThirdPartyAuth := c.MustGet("userThirdPartyAuth").(string)
if Config.JELLYFIN_HOST == "" {
if cfg.JELLYFIN_HOST == "" {
slog.Error("JellyfinAccessRequired: Request made to login via Jellyfin, but JELLYFIN_HOST has not been configured.")
c.AbortWithStatus(401)
return
}
if userType != JELLYFIN_USER || userThirdPartyId == "" {
if userType != entity.JELLYFIN_USER || userThirdPartyId == "" {
slog.Error("JellyfinAccessRequired: User is not a jellyfin user..", "user_type", userType, "user_third_party_id", userThirdPartyId)
c.AbortWithStatus(401)
return
@@ -73,13 +85,13 @@ func JellyfinAccessRequired() gin.HandlerFunc {
}
}
func jellyfinAPIRequest(method string, ep string, p map[string]string, username string, userToken string, resp interface{}) error {
if Config.JELLYFIN_HOST == "" {
func (s *Service) JellyfinAPIRequest(method string, ep string, p map[string]string, username string, userToken string, resp interface{}) error {
if s.cfg.JELLYFIN_HOST == "" {
slog.Error("jellyfinAPIRequest: JELLYFIN_HOST not configured.")
return errors.New("jellyfin not enabled")
}
slog.Debug("jellyfinAPIRequest", "endpoint", ep, "params", p)
base, err := url.Parse(Config.JELLYFIN_HOST)
base, err := url.Parse(s.cfg.JELLYFIN_HOST)
if err != nil {
return errors.New("failed to parse api uri")
}
@@ -132,9 +144,9 @@ func jellyfinAPIRequest(method string, ep string, p map[string]string, username
return nil
}
func jellyfinContentFind(
func (s *Service) JellyfinContentFind(
userId uint,
userType UserType,
userType entity.UserType,
username string,
userThirdPartyId string,
userThirdPartyAuth string,
@@ -151,7 +163,7 @@ func jellyfinContentFind(
}
resp := new(JellyfinItemSearchResponse)
err := jellyfinAPIRequest(
err := s.JellyfinAPIRequest(
"GET",
"/Users/"+userThirdPartyId+"/Items",
map[string]string{
@@ -184,7 +196,7 @@ func jellyfinContentFind(
for _, i := range resp.Items {
if i.ProviderIds.Tmdb == contentTmdbId {
ret.HasContent = true
ret.Url = Config.JELLYFIN_HOST + "/web/index.html#!/details?id=" + i.Id + "&serverId=" + i.ServerID
ret.Url = s.cfg.JELLYFIN_HOST + "/web/index.html#!/details?id=" + i.Id + "&serverId=" + i.ServerID
}
}
return *ret, nil
@@ -1,11 +1,17 @@
package main
package jellyfin
import (
"errors"
"log/slog"
"strconv"
"gorm.io/gorm"
"github.com/sbondCo/Watcharr/config"
"github.com/sbondCo/Watcharr/database/entity"
"github.com/sbondCo/Watcharr/domain"
"github.com/sbondCo/Watcharr/feature/watched/episode"
"github.com/sbondCo/Watcharr/feature/watched/season"
"github.com/sbondCo/Watcharr/job"
"github.com/sbondCo/Watcharr/util"
)
type JellyfinSeriesSeasonsResponse struct {
@@ -34,11 +40,49 @@ type JellyfinSyncResponse struct {
JobId string `json:"jobId"`
}
type WatchedProvider interface {
AddWatched(userId uint, ar domain.WatchedAddRequest, at entity.ActivityType) (entity.Watched, error)
}
type WatchedSeasonProvider interface {
AddWatchedSeason(userId uint, ar season.WatchedSeasonAddRequest) (season.WatchedSeasonAddResponse, error)
}
type WatchedEpisodeProvider interface {
AddWatchedEpisodes(userId uint, ar episode.WatchedEpisodeAddRequest) (episode.WatchedEpisodeAddResponse, error)
}
type SyncService struct {
cfg *config.ServerConfig
service *Service
wp WatchedProvider
wsp WatchedSeasonProvider
wep WatchedEpisodeProvider
activityProvider domain.ActivityAddProvider
}
func NewSyncService(
cfg *config.ServerConfig,
service *Service,
wp WatchedProvider,
wsp WatchedSeasonProvider,
wep WatchedEpisodeProvider,
activityProvider domain.ActivityAddProvider,
) *SyncService {
return &SyncService{
cfg,
service,
wp,
wsp,
wep,
activityProvider,
}
}
// Perform the jellyfin sync.
// Gets each type of media separately from jellyfin and attempts to import them.
// Errors are added silently to the job.
func startJellyfinSync(
db *gorm.DB,
func (s *SyncService) startJellyfinSync(
jobId string,
userId uint,
username string,
@@ -46,9 +90,9 @@ func startJellyfinSync(
userThirdPartyAuth string,
) {
// Get played movies
updateJobCurrentTask(jobId, userId, "syncing movies")
job.UpdateJobCurrentTask(jobId, userId, "syncing movies")
playedMovies := new(JellyfinItemSearchResponse)
err := jellyfinAPIRequest(
err := s.service.JellyfinAPIRequest(
"GET",
"/Users/"+userThirdPartyId+"/Items",
map[string]string{
@@ -63,7 +107,7 @@ func startJellyfinSync(
)
if err != nil {
slog.Error("jellyfinSyncWatched: Jellyfin API request failed", "error", err)
addJobError(jobId, userId, "failed to get jellyfin response for movies")
job.AddJobError(jobId, userId, "failed to get jellyfin response for movies")
} else {
if len(playedMovies.Items) <= 0 {
slog.Info("jellyfinSyncWatched: User has no played movies.", "user_id", userId)
@@ -75,36 +119,36 @@ func startJellyfinSync(
// 1. Ensure we have a tmdbId
if v.ProviderIds.Tmdb == "" {
slog.Error("jellyfinSyncWatched: Movie to import does not have a tmdb id.", "movie_name", v.Name, "movie_ids", v.ProviderIds, "user_id", userId)
addJobError(jobId, userId, "movie could not be imported (no tmdbId present): "+v.Name)
job.AddJobError(jobId, userId, "movie could not be imported (no tmdbId present): "+v.Name)
continue
}
tmdbId, err := strconv.Atoi(v.ProviderIds.Tmdb)
if err != nil {
slog.Error("jellyfinSyncWatched: Movie to import does not have a parseable (to int) tmdb id.", "movie_name", v.Name, "movie_ids", v.ProviderIds, "user_id", userId)
addJobError(jobId, userId, "movie could not be imported (tmdbId was not parseable): "+v.Name)
job.AddJobError(jobId, userId, "movie could not be imported (tmdbId was not parseable): "+v.Name)
continue
}
updateJobCurrentTask(jobId, userId, "syncing "+v.Name)
job.UpdateJobCurrentTask(jobId, userId, "syncing "+v.Name)
// 2. Imported watched movie
w, err := addWatched(db, userId, WatchedAddRequest{
Status: FINISHED,
ContentID: tmdbId,
ContentType: MOVIE,
w, err := s.wp.AddWatched(userId, domain.WatchedAddRequest{
Status: entity.FINISHED,
ContentType: util.SupportedMediaMovie,
TMDBID: tmdbId,
WatchedDate: v.UserData.LastPlayedDate,
}, IMPORTED_WATCHED_JF)
}, entity.IMPORTED_WATCHED_JF)
if err != nil {
if err.Error() == "content already on watched list" {
slog.Error("jellyfinSyncWatched: Unique constraint hit.. content must already be on watch list.", "movie_name", v.Name, "movie_ids", v.ProviderIds, "user_id", userId)
} else {
slog.Error("jellyfinSyncWatched: Movie failed to import.", "movie_name", v.Name, "movie_ids", v.ProviderIds, "user_id", userId)
addJobError(jobId, userId, "movie could not be imported (failed when adding to watched list): "+v.Name)
job.AddJobError(jobId, userId, "movie could not be imported (failed when adding to watched list): "+v.Name)
}
} else {
// 3. Add IMPORTED_ADDED_WATCHED_JF activity
if !v.UserData.LastPlayedDate.IsZero() {
_, err := addActivity(db, userId, ActivityAddRequest{WatchedID: w.ID, Type: IMPORTED_ADDED_WATCHED_JF, CustomDate: &v.UserData.LastPlayedDate})
_, err := s.activityProvider.AddActivity(userId, domain.ActivityAddRequest{WatchedID: w.ID, Type: entity.IMPORTED_ADDED_WATCHED_JF, CustomDate: &v.UserData.LastPlayedDate})
if err != nil {
slog.Error("jellyfinSyncWatched: Failed to add dateswatched activity.", "movie_name", v.Name,
"movie_ids", v.ProviderIds, "user_id", userId, "date", v.UserData.LastPlayedDate, "error", err)
@@ -117,9 +161,9 @@ func startJellyfinSync(
// Get played series
// Can't rely on IsPlayed filter, since we want to get partially played series too.
updateJobCurrentTask(jobId, userId, "syncing series")
job.UpdateJobCurrentTask(jobId, userId, "syncing series")
allSeries := new(JellyfinItemSearchResponse)
err = jellyfinAPIRequest(
err = s.service.JellyfinAPIRequest(
"GET",
"/Users/"+userThirdPartyId+"/Items",
map[string]string{
@@ -134,7 +178,7 @@ func startJellyfinSync(
)
if err != nil {
slog.Error("jellyfinSyncWatched: Jellyfin API request failed", "error", err)
addJobError(jobId, userId, "failed to get jellyfin response for series")
job.AddJobError(jobId, userId, "failed to get jellyfin response for series")
} else {
if len(allSeries.Items) <= 0 {
slog.Info("jellyfinSyncWatched: No series found.", "user_id", userId)
@@ -153,37 +197,37 @@ func startJellyfinSync(
// 1.1. Ensure we have a tmdbId
if v.ProviderIds.Tmdb == "" {
slog.Error("jellyfinSyncWatched: Series to import does not have a tmdb id.", "series_name", v.Name, "series_ids", v.ProviderIds, "user_id", userId)
addJobError(jobId, userId, "series could not be imported (no tmdbId present): "+v.Name)
job.AddJobError(jobId, userId, "series could not be imported (no tmdbId present): "+v.Name)
continue
}
tmdbId, err := strconv.Atoi(v.ProviderIds.Tmdb)
if err != nil {
slog.Error("jellyfinSyncWatched: Series to import does not have a parseable (to int) tmdb id.", "series_name", v.Name, "series_ids", v.ProviderIds, "user_id", userId)
addJobError(jobId, userId, "series could not be imported (tmdbId was not parseable): "+v.Name)
job.AddJobError(jobId, userId, "series could not be imported (tmdbId was not parseable): "+v.Name)
continue
}
updateJobCurrentTask(jobId, userId, "syncing serie "+v.Name)
job.UpdateJobCurrentTask(jobId, userId, "syncing serie "+v.Name)
// 2. Imported watched series
w, err := addWatched(db, userId, WatchedAddRequest{
Status: FINISHED,
ContentID: tmdbId,
ContentType: SHOW,
w, err := s.wp.AddWatched(userId, domain.WatchedAddRequest{
Status: entity.FINISHED,
ContentType: util.SupportedMediaShow,
TMDBID: tmdbId,
WatchedDate: v.UserData.LastPlayedDate,
}, IMPORTED_WATCHED_JF)
}, entity.IMPORTED_WATCHED_JF)
if err != nil {
if err.Error() == "content already on watched list" {
slog.Info("jellyfinSyncWatched: Unique constraint hit.. content must already be on watch list.",
"series_name", v.Name, "series_ids", v.ProviderIds, "user_id", userId, "watched_id", w.ID)
} else {
slog.Error("jellyfinSyncWatched: Series failed to import.", "series_name", v.Name, "series_ids", v.ProviderIds, "user_id", userId)
addJobError(jobId, userId, "series could not be imported (failed when adding to watched list): "+v.Name)
job.AddJobError(jobId, userId, "series could not be imported (failed when adding to watched list): "+v.Name)
}
} else {
// 3. Add IMPORTED_ADDED_WATCHED activity (only if no err above, show also must not have already been on our list)
if !v.UserData.LastPlayedDate.IsZero() {
_, err := addActivity(db, userId, ActivityAddRequest{WatchedID: w.ID, Type: IMPORTED_ADDED_WATCHED_JF, CustomDate: &v.UserData.LastPlayedDate})
_, err := s.activityProvider.AddActivity(userId, domain.ActivityAddRequest{WatchedID: w.ID, Type: entity.IMPORTED_ADDED_WATCHED_JF, CustomDate: &v.UserData.LastPlayedDate})
if err != nil {
slog.Error("jellyfinSyncWatched: Failed to add dateswatched activity.", "series_name", v.Name,
"series_ids", v.ProviderIds, "user_id", userId, "date", v.UserData.LastPlayedDate, "error", err)
@@ -194,7 +238,7 @@ func startJellyfinSync(
// 4. Import watched seasons for this serie
// Get all show seasons (filtering isPlayed doesn't seem to be a thing, so we will have to do that ourselves)
seriesSeasons := new(JellyfinSeriesSeasonsResponse)
err = jellyfinAPIRequest(
err = s.service.JellyfinAPIRequest(
"GET",
"/Shows/"+v.Id+"/Seasons",
map[string]string{
@@ -208,7 +252,7 @@ func startJellyfinSync(
)
if err != nil {
slog.Error("jellyfinSyncWatched: Failed to fetch series seasons.", "series_name", v.Name, "series_ids", v.ProviderIds, "user_id", userId, "error", err)
addJobError(jobId, userId, "series seasons could not be imported (request failed): "+v.Name)
job.AddJobError(jobId, userId, "series seasons could not be imported (request failed): "+v.Name)
} else if len(seriesSeasons.Items) <= 0 {
slog.Info("jellyfinSyncWatched: Series has no seasons.", "series_name", v.Name, "series_ids", v.ProviderIds, "user_id", userId)
} else {
@@ -218,17 +262,17 @@ func startJellyfinSync(
slog.Debug("jellyfinSyncWatched: Skipping import of unplayed season.", "series_name", v.Name, "season_num", vs.IndexNumber, "user_id", userId)
continue
}
updateJobCurrentTask(jobId, userId, "syncing "+v.Name+" season "+strconv.Itoa(vs.IndexNumber))
_, err = addWatchedSeason(db, userId, WatchedSeasonAddRequest{
job.UpdateJobCurrentTask(jobId, userId, "syncing "+v.Name+" season "+strconv.Itoa(vs.IndexNumber))
_, err = s.wsp.AddWatchedSeason(userId, season.WatchedSeasonAddRequest{
WatchedID: w.ID,
SeasonNumber: vs.IndexNumber,
Status: FINISHED,
addActivity: SEASON_ADDED_JF,
addActivityDate: vs.UserData.LastPlayedDate,
Status: entity.FINISHED,
AddActivity: entity.SEASON_ADDED_JF,
AddActivityDate: vs.UserData.LastPlayedDate,
})
if err != nil {
slog.Error("jellyfinSyncWatched: Failed to fetch series seasons.", "series_name", v.Name, "series_ids", v.ProviderIds, "user_id", userId, "error", err)
addJobError(jobId, userId, "series season could not be imported (addWatchedSeason request failed): "+v.Name+" season "+strconv.Itoa(vs.IndexNumber))
job.AddJobError(jobId, userId, "series season could not be imported (addWatchedSeason request failed): "+v.Name+" season "+strconv.Itoa(vs.IndexNumber))
}
}
}
@@ -236,7 +280,7 @@ func startJellyfinSync(
// 5. Import watched episodes for this serie
// Gets all show episodes (filtering isPlayed doesn't seem to be a thing, so we will have to do that ourselves)
seriesEpisodes := new(JellyfinSeriesEpisodesResponse)
err = jellyfinAPIRequest(
err = s.service.JellyfinAPIRequest(
"GET",
"/Shows/"+v.Id+"/Episodes",
map[string]string{
@@ -250,7 +294,7 @@ func startJellyfinSync(
)
if err != nil {
slog.Error("jellyfinSyncWatched: Failed to fetch series episodes.", "series_name", v.Name, "series_ids", v.ProviderIds, "user_id", userId, "error", err)
addJobError(jobId, userId, "series episodes could not be imported (request failed): "+v.Name)
job.AddJobError(jobId, userId, "series episodes could not be imported (request failed): "+v.Name)
} else if len(seriesEpisodes.Items) <= 0 {
slog.Info("jellyfinSyncWatched: Series has no episodes.", "series_name", v.Name, "series_ids", v.ProviderIds, "user_id", userId)
} else {
@@ -260,18 +304,18 @@ func startJellyfinSync(
slog.Debug("jellyfinSyncWatched: Skipping import of unplayed episode.", "series_name", v.Name, "season_num", vs.ParentIndexNumber, "episode_num", vs.IndexNumber, "user_id", userId)
continue
}
updateJobCurrentTask(jobId, userId, "syncing "+v.Name+" season "+strconv.Itoa(vs.ParentIndexNumber)+" episode "+strconv.Itoa(vs.IndexNumber))
_, err = addWatchedEpisodes(db, userId, WatchedEpisodeAddRequest{
job.UpdateJobCurrentTask(jobId, userId, "syncing "+v.Name+" season "+strconv.Itoa(vs.ParentIndexNumber)+" episode "+strconv.Itoa(vs.IndexNumber))
_, err = s.wep.AddWatchedEpisodes(userId, episode.WatchedEpisodeAddRequest{
WatchedID: w.ID,
SeasonNumber: vs.ParentIndexNumber,
EpisodeNumber: vs.IndexNumber,
Status: FINISHED,
addActivity: EPISODE_ADDED_JF,
addActivityDate: vs.UserData.LastPlayedDate,
Status: entity.FINISHED,
AddActivity: entity.EPISODE_ADDED_JF,
AddActivityDate: vs.UserData.LastPlayedDate,
})
if err != nil {
slog.Error("jellyfinSyncWatched: Failed to import series episode.", "series_name", v.Name, "season_num", vs.ParentIndexNumber, "episode_num", vs.IndexNumber, "user_id", userId, "error", err)
addJobError(jobId, userId, "series episode could not be imported (addWatchedEpisode request failed): "+v.Name+" "+vs.Name)
job.AddJobError(jobId, userId, "series episode could not be imported (addWatchedEpisode request failed): "+v.Name+" "+vs.Name)
}
}
}
@@ -279,27 +323,25 @@ func startJellyfinSync(
}
}
updateJobStatus(jobId, userId, JOB_DONE)
job.UpdateJobStatus(jobId, userId, job.JOB_DONE)
}
func jellyfinSyncWatched(
db *gorm.DB,
func (s *SyncService) jellyfinSyncWatched(
userId uint,
userType UserType,
userType entity.UserType,
username string,
userThirdPartyId string,
userThirdPartyAuth string,
) (JellyfinSyncResponse, error) {
jobId, err := addJob("jf_sync", userId)
jobId, err := job.AddJob("jf_sync", userId)
if err != nil {
slog.Error("jellyfinSyncWatched: Failed to create a job", "error", err)
return JellyfinSyncResponse{}, errors.New("failed to create job")
}
updateJobStatus(jobId, userId, JOB_RUNNING)
job.UpdateJobStatus(jobId, userId, job.JOB_RUNNING)
go startJellyfinSync(
db,
go s.startJellyfinSync(
jobId,
userId,
username,
+72
View File
@@ -0,0 +1,72 @@
package jellyfin
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/sbondCo/Watcharr/database/entity"
"github.com/sbondCo/Watcharr/feature/auth/authmiddleware"
"github.com/sbondCo/Watcharr/router"
)
type Router struct {
br *router.BaseRouter
s *Service
syncService *SyncService
}
func NewRouter(br *router.BaseRouter, s *Service, syncService *SyncService) *Router {
return &Router{
br: br,
s: s,
syncService: syncService,
}
}
func (r *Router) AddRoutes() {
jf := r.br.Router.Group("/jellyfin").Use(authmiddleware.AuthRequired(r.br.DB, r.br.Cfg), r.s.JellyfinAccessRequired(r.br.Cfg))
// Check if jf has item
jf.GET("/:type/:name/:tmdbId", r.GetFindContent)
// Sync users jellyfin watched items to watchlist
jf.GET("/sync", r.GetSync)
}
// Check if jf has item
func (r *Router) GetFindContent(c *gin.Context) {
userId := c.MustGet("userId").(uint)
userType := c.MustGet("userType").(entity.UserType)
username := c.MustGet("username").(string)
userThirdPartyId := c.MustGet("userThirdPartyId").(string)
userThirdPartyAuth := c.MustGet("userThirdPartyAuth").(string)
response, err := r.s.JellyfinContentFind(
userId,
userType,
username,
userThirdPartyId,
userThirdPartyAuth,
c.Param("type"),
c.Param("name"),
c.Param("tmdbId"),
)
if err != nil {
c.JSON(http.StatusForbidden, router.ErrorResponse{Error: err.Error()})
return
}
c.JSON(http.StatusOK, response)
}
// Sync users jellyfin watched items to watchlist
func (r *Router) GetSync(c *gin.Context) {
userId := c.MustGet("userId").(uint)
userType := c.MustGet("userType").(entity.UserType)
username := c.MustGet("username").(string)
userThirdPartyId := c.MustGet("userThirdPartyId").(string)
userThirdPartyAuth := c.MustGet("userThirdPartyAuth").(string)
response, err := r.syncService.jellyfinSyncWatched(userId, userType, username, userThirdPartyId, userThirdPartyAuth)
if err != nil {
c.JSON(http.StatusForbidden, router.ErrorResponse{Error: err.Error()})
return
}
c.JSON(http.StatusOK, response)
}
+39
View File
@@ -0,0 +1,39 @@
package job
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/sbondCo/Watcharr/feature/auth/authmiddleware"
"github.com/sbondCo/Watcharr/job"
"github.com/sbondCo/Watcharr/router"
)
type Router struct {
br *router.BaseRouter
}
func NewRouter(br *router.BaseRouter) *Router {
return &Router{
br,
}
}
func (r *Router) AddRoutes() {
job := r.br.Router.Group("/job").Use(authmiddleware.AuthRequired(nil, r.br.Cfg))
// Uses wildcard so it still works in cases where the job id includes a /.
// (yes i changed this instead of not allowing a / when we generate a job id becuz easier)
job.GET("/*id", r.GetJobById)
}
func (r *Router) GetJobById(c *gin.Context) {
userId := c.MustGet("userId").(uint)
// When we get id param, don't include first letter, which will be the beginning '/'.
response, err := job.GetJob(c.Param("id")[1:], userId)
if err != nil {
c.JSON(http.StatusForbidden, router.ErrorResponse{Error: err.Error()})
return
}
c.JSON(http.StatusOK, *response)
}
+32 -56
View File
@@ -1,4 +1,4 @@
package main
package plex
import (
"encoding/json"
@@ -8,8 +8,7 @@ import (
"net/http"
"time"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
"github.com/sbondCo/Watcharr/config"
)
type PlexLoginRequest struct {
@@ -335,40 +334,17 @@ type PlexClientResources []struct {
} `json:"connections"`
}
// Plex access middleware, ensures user is a Plex user.
// To be ran after AuthRequired middleware with extra data.
func PlexAccessRequired(db *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {
userId := c.MustGet("userId").(uint)
slog.Debug("PlexAccessRequired middleware hit", "user_id", userId)
userType := c.MustGet("userType").(UserType)
if Config.PLEX_HOST == "" || Config.PLEX_MACHINE_ID == "" {
slog.Error("PlexAccessRequired: Plex has not been configured.", "user_id", userId)
c.AbortWithStatus(401)
return
}
if userType != PLEX_USER {
slog.Error("PlexAccessRequired: User is not a Plex user..", "user_id", userId, "user_type", userType)
c.AbortWithStatus(401)
return
}
userPlexService := new(UserServices)
if res := db.Where("user_id = ? AND name = ?", userId, "plex").Take(&userPlexService); res.Error != nil {
slog.Error("PlexAccessRequired: Failed when attempting to get users plex service integration..", "user_id", userId, "user_type", userType)
c.AbortWithStatus(401)
return
}
if userPlexService.ClientID == "" || userPlexService.AuthToken == "" || userPlexService.AuthToken2 == "" {
slog.Error("PlexAccessRequired: User has missing details from service (clientId, authToken or authToken2)..", "user_id", userId, "client_id", userPlexService.ClientID)
c.AbortWithStatus(401)
return
}
c.Set("plexAuthToken", userPlexService.AuthToken)
c.Set("plexLocalAuthToken", userPlexService.AuthToken2)
type Service struct {
cfg *config.ServerConfig
}
func NewService(cfg *config.ServerConfig) *Service {
return &Service{
cfg,
}
}
func getPlexIdentity(host string) (PlexIdentity, error) {
func (s *Service) GetPlexIdentity(host string) (PlexIdentity, error) {
httpClient := &http.Client{}
req, err := http.NewRequest("GET", host+"/identity", nil)
if err != nil {
@@ -392,7 +368,7 @@ func getPlexIdentity(host string) (PlexIdentity, error) {
return pi, nil
}
func fetchPlexAccountFromToken(token string) (PlexUser, error) {
func (s *Service) FetchPlexAccountFromToken(token string) (PlexUser, error) {
httpClient := &http.Client{}
req, err := http.NewRequest("GET", "https://plex.tv/users/account.json", nil)
if err != nil {
@@ -419,32 +395,32 @@ func fetchPlexAccountFromToken(token string) (PlexUser, error) {
}
// Update plex host setting
func updateConfigPlexHost(v string) (PlexHostConfigUpdateResponse, error) {
Config.PLEX_HOST = v
if Config.PLEX_HOST != "" {
pi, err := getPlexIdentity(Config.PLEX_HOST)
func (s *Service) UpdateConfigPlexHost(cfg *config.ServerConfig, v string) (PlexHostConfigUpdateResponse, error) {
cfg.PLEX_HOST = v
if cfg.PLEX_HOST != "" {
pi, err := s.GetPlexIdentity(cfg.PLEX_HOST)
if err != nil {
slog.Error("updateConfigPlexHost: Failed to get plex server identity!", "error", err)
slog.Error("UpdateConfigPlexHost: Failed to get plex server identity!", "error", err)
return PlexHostConfigUpdateResponse{}, errors.New("failed to get Plex server identity. Please try setting the Plex Host again or setting PLEX_MACHINE_ID manually in your config file")
}
if pi.MediaContainer.MachineIdentifier == "" {
slog.Error("updateConfigPlexHost: Plex server identity response had no machine id!", "response", pi)
slog.Error("UpdateConfigPlexHost: Plex server identity response had no machine id!", "response", pi)
return PlexHostConfigUpdateResponse{}, errors.New("got Plex server identity, but no machine id was found")
}
Config.PLEX_MACHINE_ID = pi.MediaContainer.MachineIdentifier
cfg.PLEX_MACHINE_ID = pi.MediaContainer.MachineIdentifier
} else {
Config.PLEX_MACHINE_ID = ""
cfg.PLEX_MACHINE_ID = ""
}
if err := writeConfig(); err != nil {
slog.Error("updateConfigPlexHost: Failed to write updated config to file!", "err", err)
if err := cfg.Write(); err != nil {
slog.Error("UpdateConfigPlexHost: Failed to write updated config to file!", "err", err)
return PlexHostConfigUpdateResponse{}, errors.New("failed to write config")
}
return PlexHostConfigUpdateResponse{PLEX_MACHINE_ID: Config.PLEX_MACHINE_ID}, nil
return PlexHostConfigUpdateResponse{PLEX_MACHINE_ID: cfg.PLEX_MACHINE_ID}, nil
}
func getPlexLibraries(plexAuth string) (PlexLibrariesResponse, error) {
func (s *Service) GetPlexLibraries(plexAuth string) (PlexLibrariesResponse, error) {
httpClient := &http.Client{}
req, err := http.NewRequest("GET", Config.PLEX_HOST+"/library/sections", nil)
req, err := http.NewRequest("GET", s.cfg.PLEX_HOST+"/library/sections", nil)
if err != nil {
return PlexLibrariesResponse{}, err
}
@@ -467,9 +443,9 @@ func getPlexLibraries(plexAuth string) (PlexLibrariesResponse, error) {
return pl, nil
}
func getPlexLibraryItems(plexAuth string, libraryKey string) (PlexLibraryItemsResponse, error) {
func (s *Service) GetPlexLibraryItems(plexAuth string, libraryKey string) (PlexLibraryItemsResponse, error) {
httpClient := &http.Client{}
req, err := http.NewRequest("GET", Config.PLEX_HOST+"/library/sections/"+libraryKey+"/all?includeGuids=1", nil)
req, err := http.NewRequest("GET", s.cfg.PLEX_HOST+"/library/sections/"+libraryKey+"/all?includeGuids=1", nil)
if err != nil {
return PlexLibraryItemsResponse{}, err
}
@@ -492,9 +468,9 @@ func getPlexLibraryItems(plexAuth string, libraryKey string) (PlexLibraryItemsRe
return pl, nil
}
func getPlexLibraryItemSeasons(plexAuth string, ratingKey string) (PlexLibraryItemSeasonsResponse, error) {
func (s *Service) GetPlexLibraryItemSeasons(plexAuth string, ratingKey string) (PlexLibraryItemSeasonsResponse, error) {
httpClient := &http.Client{}
req, err := http.NewRequest("GET", Config.PLEX_HOST+"/library/metadata/"+ratingKey+"/children", nil)
req, err := http.NewRequest("GET", s.cfg.PLEX_HOST+"/library/metadata/"+ratingKey+"/children", nil)
if err != nil {
return PlexLibraryItemSeasonsResponse{}, err
}
@@ -517,9 +493,9 @@ func getPlexLibraryItemSeasons(plexAuth string, ratingKey string) (PlexLibraryIt
return pl, nil
}
func getPlexLibraryItemEpisodes(plexAuth string, ratingKey string) (PlexLibraryItemEpisodesResponse, error) {
func (s *Service) GetPlexLibraryItemEpisodes(plexAuth string, ratingKey string) (PlexLibraryItemEpisodesResponse, error) {
httpClient := &http.Client{}
req, err := http.NewRequest("GET", Config.PLEX_HOST+"/library/metadata/"+ratingKey+"/allLeaves", nil)
req, err := http.NewRequest("GET", s.cfg.PLEX_HOST+"/library/metadata/"+ratingKey+"/allLeaves", nil)
if err != nil {
return PlexLibraryItemEpisodesResponse{}, err
}
@@ -545,7 +521,7 @@ func getPlexLibraryItemEpisodes(plexAuth string, ratingKey string) (PlexLibraryI
// Gets users auth token for local plex server,
// so they can authenticate against it for api requests.
// If no auth token is returned or errored, assume user doesn't have access to home plex server library.
func getPlexHomeServerAuthToken(plexAuth string, userClientId string) (string, error) {
func (s *Service) GetPlexHomeServerAuthToken(plexAuth string, userClientId string) (string, error) {
httpClient := &http.Client{}
req, err := http.NewRequest("GET", "https://clients.plex.tv/api/v2/resources", nil)
if err != nil {
@@ -570,7 +546,7 @@ func getPlexHomeServerAuthToken(plexAuth string, userClientId string) (string, e
}
authToken := ""
for _, v := range pl {
if v.ClientIdentifier == Config.PLEX_MACHINE_ID {
if v.ClientIdentifier == s.cfg.PLEX_MACHINE_ID {
slog.Debug("getPlexHomeServerAuthToken: Found entry with clientIdentifier matching home server machine id.")
if v.AccessToken == "" {
slog.Error("getPlexHomeServerAuthToken: Matching entry has no AccessToken!")
@@ -1,4 +1,4 @@
package main
package plex
import (
"errors"
@@ -7,37 +7,77 @@ import (
"strings"
"time"
"gorm.io/gorm"
"github.com/sbondCo/Watcharr/database/entity"
"github.com/sbondCo/Watcharr/domain"
"github.com/sbondCo/Watcharr/feature/watched/episode"
"github.com/sbondCo/Watcharr/feature/watched/season"
"github.com/sbondCo/Watcharr/job"
"github.com/sbondCo/Watcharr/util"
)
type PlexSyncResponse struct {
JobId string `json:"jobId"`
}
type WatchedProvider interface {
AddWatched(userId uint, ar domain.WatchedAddRequest, at entity.ActivityType) (entity.Watched, error)
}
type WatchedSeasonProvider interface {
AddWatchedSeason(userId uint, ar season.WatchedSeasonAddRequest) (season.WatchedSeasonAddResponse, error)
}
type WatchedEpisodeProvider interface {
AddWatchedEpisodes(userId uint, ar episode.WatchedEpisodeAddRequest) (episode.WatchedEpisodeAddResponse, error)
}
type SyncService struct {
s *Service
wp WatchedProvider
wsp WatchedSeasonProvider
wep WatchedEpisodeProvider
activityProvider domain.ActivityAddProvider
}
func NewSyncService(
s *Service,
wp WatchedProvider,
wsp WatchedSeasonProvider,
wep WatchedEpisodeProvider,
activityProvider domain.ActivityAddProvider,
) *SyncService {
return &SyncService{
s,
wp,
wsp,
wep,
activityProvider,
}
}
// Perform a Plex sync.
// Errors are added silently to the job.
func startPlexSync(
db *gorm.DB,
func (s *SyncService) startPlexSync(
jobId string,
userId uint,
userPlexLocalAuth string,
) {
updateJobCurrentTask(jobId, userId, "fetching libraries")
libraries, err := getPlexLibraries(userPlexLocalAuth)
job.UpdateJobCurrentTask(jobId, userId, "fetching libraries")
libraries, err := s.s.GetPlexLibraries(userPlexLocalAuth)
if err != nil {
slog.Error("plexSyncWatched: Failed to fetch libraries", "user_id", userId, "error", err)
addJobError(jobId, userId, "failed to get plex libraries")
updateJobStatus(jobId, userId, JOB_DONE)
job.AddJobError(jobId, userId, "failed to get plex libraries")
job.UpdateJobStatus(jobId, userId, job.JOB_DONE)
return
}
for _, library := range libraries.MediaContainer.Directory {
slog.Debug("plexSyncWatched: Processing a library", "library_title", library.Title, "library_type", library.Type, "user_id", userId)
if library.Type == "movie" {
updateJobCurrentTask(jobId, userId, "importing movies from "+library.Title)
movies, err := getPlexLibraryItems(userPlexLocalAuth, library.Key)
job.UpdateJobCurrentTask(jobId, userId, "importing movies from "+library.Title)
movies, err := s.s.GetPlexLibraryItems(userPlexLocalAuth, library.Key)
if err != nil {
slog.Error("plexSyncWatched: Failed to fetch movies from library", "library", library.Key, "user_id", userId, "error", err)
addJobError(jobId, userId, "failed to fetch movies from library "+library.Key)
job.AddJobError(jobId, userId, "failed to fetch movies from library "+library.Key)
continue
}
for _, movie := range movies.MediaContainer.Metadata {
@@ -46,13 +86,13 @@ func startPlexSync(
slog.Debug("plexSyncWatched: Skipping unwatched movie:", "movie_name", movie.Title, "user_id", userId)
continue
}
updateJobCurrentTask(jobId, userId, "importing movie "+movie.Title)
job.UpdateJobCurrentTask(jobId, userId, "importing movie "+movie.Title)
slog.Info("plexSyncWatched: Importing movie.", "movie_name", movie.Title, "user_id", userId)
// Find tmdb id
if len(movie.Guid) <= 0 {
slog.Error("plexSyncWatched: Movie to import does not have any external guids.", "movie_name", movie.Title, "movie_id", movie.GUID, "user_id", userId)
addJobError(jobId, userId, "movie could not be imported (no external ids present): "+movie.Title)
job.AddJobError(jobId, userId, "movie could not be imported (no external ids present): "+movie.Title)
continue
}
tmdbIdStr := ""
@@ -64,37 +104,37 @@ func startPlexSync(
}
if tmdbIdStr == "" {
slog.Error("plexSyncWatched: Movie to import does not have a tmdb id.", "movie_name", movie.Title, "tmdb_id_str", tmdbIdStr, "movie_id", movie.GUID, "user_id", userId)
addJobError(jobId, userId, "movie could not be imported (no tmdbId present): "+movie.Title)
job.AddJobError(jobId, userId, "movie could not be imported (no tmdbId present): "+movie.Title)
continue
}
tmdbId, err := strconv.Atoi(tmdbIdStr)
if err != nil {
slog.Error("plexSyncWatched: Movie to import does not have a parseable (to int) tmdb id.", "movie_name", movie.Title, "tmdb_id_str", tmdbIdStr, "movie_id", movie.GUID, "user_id", userId)
addJobError(jobId, userId, "movie could not be imported (tmdbId was not parseable): "+movie.Title)
job.AddJobError(jobId, userId, "movie could not be imported (tmdbId was not parseable): "+movie.Title)
continue
}
lastViewedAt := time.Unix(movie.LastViewedAt, 0)
w, err := addWatched(db, userId, WatchedAddRequest{
Status: FINISHED,
ContentID: tmdbId,
ContentType: MOVIE,
w, err := s.wp.AddWatched(userId, domain.WatchedAddRequest{
Status: entity.FINISHED,
TMDBID: tmdbId,
ContentType: util.SupportedMediaMovie,
Rating: float64(movie.UserRating),
WatchedDate: lastViewedAt,
}, IMPORTED_WATCHED_PLEX)
}, entity.IMPORTED_WATCHED_PLEX)
if err != nil {
if err.Error() == "content already on watched list" {
slog.Error("plexSyncWatched: unique constraint hit. movie must already be on watch list", "error", err)
continue
}
slog.Error("plexSyncWatched: Failed to add movie as watched", "error", err)
addJobError(jobId, userId, "failed to add movie "+movie.Title)
job.AddJobError(jobId, userId, "failed to add movie "+movie.Title)
} else {
// 3. Add IMPORTED_ADDED_WATCHED_PLEX activity
if !lastViewedAt.IsZero() {
_, err := addActivity(db, userId, ActivityAddRequest{
_, err := s.activityProvider.AddActivity(userId, domain.ActivityAddRequest{
WatchedID: w.ID,
Type: IMPORTED_ADDED_WATCHED_PLEX,
Type: entity.IMPORTED_ADDED_WATCHED_PLEX,
CustomDate: &lastViewedAt,
})
if err != nil {
@@ -105,11 +145,11 @@ func startPlexSync(
}
}
} else if library.Type == "show" {
updateJobCurrentTask(jobId, userId, "importing tv shows from "+library.Title)
shows, err := getPlexLibraryItems(userPlexLocalAuth, library.Key)
job.UpdateJobCurrentTask(jobId, userId, "importing tv shows from "+library.Title)
shows, err := s.s.GetPlexLibraryItems(userPlexLocalAuth, library.Key)
if err != nil {
slog.Error("plexSyncWatched: Failed to fetch shows from library", "library", library.Key, "error", err)
addJobError(jobId, userId, "failed to fetch shows from library "+library.Key)
job.AddJobError(jobId, userId, "failed to fetch shows from library "+library.Key)
continue
}
for _, show := range shows.MediaContainer.Metadata {
@@ -119,7 +159,7 @@ func startPlexSync(
slog.Debug("plexSyncWatched: Skipping unwatched show:", "show_name", show.Title, "leaf_count", show.LeafCount, "viewed_leaf_count", show.ViewedLeafCount, "user_id", userId)
continue
}
updateJobCurrentTask(jobId, userId, "importing show "+show.Title)
job.UpdateJobCurrentTask(jobId, userId, "importing show "+show.Title)
slog.Info("plexSyncWatched: Importing show.", "show_name", show.Title, "user_id", userId)
tmdbIdStr := ""
@@ -131,37 +171,37 @@ func startPlexSync(
}
if tmdbIdStr == "" {
slog.Error("plexSyncWatched: Show to import does not have a tmdb id.", "show_name", show.Title, "tmdb_id_str", tmdbIdStr, "show_id", show.GUID, "user_id", userId)
addJobError(jobId, userId, "movie could not be imported (no tmdbId present): "+show.Title)
job.AddJobError(jobId, userId, "movie could not be imported (no tmdbId present): "+show.Title)
continue
}
tmdbId, err := strconv.Atoi(tmdbIdStr)
if err != nil {
slog.Error("plexSyncWatched: Show to import does not have a parseable (to int) tmdb id.", "show_name", show.Title, "tmdb_id_str", tmdbIdStr, "show_id", show.GUID, "user_id", userId)
addJobError(jobId, userId, "show could not be imported (tmdbId was not parseable): "+show.Title)
job.AddJobError(jobId, userId, "show could not be imported (tmdbId was not parseable): "+show.Title)
continue
}
lastViewedAt := time.Unix(show.LastViewedAt, 0)
w, err := addWatched(db, userId, WatchedAddRequest{
Status: FINISHED,
ContentID: tmdbId,
ContentType: SHOW,
w, err := s.wp.AddWatched(userId, domain.WatchedAddRequest{
Status: entity.FINISHED,
ContentType: util.SupportedMediaShow,
TMDBID: tmdbId,
Rating: float64(show.UserRating),
WatchedDate: lastViewedAt,
}, IMPORTED_WATCHED_PLEX)
}, entity.IMPORTED_WATCHED_PLEX)
if err != nil {
if err.Error() == "content already on watched list" {
slog.Info("plexSyncWatched: unique constraint hit. show must already be on watch list", "error", err)
} else {
slog.Error("plexSyncWatched: Failed to add show as watched", "error", err)
addJobError(jobId, userId, "failed to add show "+show.Title)
job.AddJobError(jobId, userId, "failed to add show "+show.Title)
}
} else {
// 3. Add IMPORTED_ADDED_WATCHED_PLEX activity
if !lastViewedAt.IsZero() {
_, err := addActivity(db, userId, ActivityAddRequest{
_, err := s.activityProvider.AddActivity(userId, domain.ActivityAddRequest{
WatchedID: w.ID,
Type: IMPORTED_ADDED_WATCHED_PLEX,
Type: entity.IMPORTED_ADDED_WATCHED_PLEX,
CustomDate: &lastViewedAt,
})
if err != nil {
@@ -172,10 +212,10 @@ func startPlexSync(
}
// Import watched seasons for this serie
seriesSeasons, err := getPlexLibraryItemSeasons(userPlexLocalAuth, show.RatingKey)
seriesSeasons, err := s.s.GetPlexLibraryItemSeasons(userPlexLocalAuth, show.RatingKey)
if err != nil {
slog.Error("plexSyncWatched: Failed to fetch series seasons.", "series_name", show.Title, "series_id", show.GUID, "user_id", userId, "error", err)
addJobError(jobId, userId, "series seasons could not be imported (request failed): "+show.Title)
job.AddJobError(jobId, userId, "series seasons could not be imported (request failed): "+show.Title)
} else if len(seriesSeasons.MediaContainer.Metadata) <= 0 {
slog.Info("plexSyncWatched: Series has no seasons.", "series_name", show.Title, "serie_ids", show.GUID, "user_id", userId)
} else {
@@ -185,30 +225,30 @@ func startPlexSync(
slog.Debug("plexSyncWatched: Skipping import of unplayed season.", "series_name", show.Title, "season_num", vs.Index, "user_id", userId)
continue
}
updateJobCurrentTask(jobId, userId, "syncing "+show.Title+" season "+strconv.Itoa(vs.Index))
job.UpdateJobCurrentTask(jobId, userId, "syncing "+show.Title+" season "+strconv.Itoa(vs.Index))
var seasonLastViewedAt time.Time
if vs.LastViewedAt != 0 {
seasonLastViewedAt = time.Unix(vs.LastViewedAt, 0)
}
_, err = addWatchedSeason(db, userId, WatchedSeasonAddRequest{
_, err = s.wsp.AddWatchedSeason(userId, season.WatchedSeasonAddRequest{
WatchedID: w.ID,
SeasonNumber: vs.Index,
Status: FINISHED,
addActivity: SEASON_ADDED_PLEX,
addActivityDate: seasonLastViewedAt,
Status: entity.FINISHED,
AddActivity: entity.SEASON_ADDED_PLEX,
AddActivityDate: seasonLastViewedAt,
})
if err != nil {
slog.Error("plexSyncWatched: Failed to fetch series seasons.", "series_name", show.Title, "series_id", show.GUID, "user_id", userId, "error", err)
addJobError(jobId, userId, "series season could not be imported (addWatchedSeason request failed): "+show.Title+" season "+strconv.Itoa(vs.Index))
job.AddJobError(jobId, userId, "series season could not be imported (addWatchedSeason request failed): "+show.Title+" season "+strconv.Itoa(vs.Index))
}
}
}
// Import watched episodes for this serie
seriesEpisodes, err := getPlexLibraryItemEpisodes(userPlexLocalAuth, show.RatingKey)
seriesEpisodes, err := s.s.GetPlexLibraryItemEpisodes(userPlexLocalAuth, show.RatingKey)
if err != nil {
slog.Error("plexSyncWatched: Failed to fetch series episodes.", "series_name", show.Title, "series_id", show.GUID, "user_id", userId, "error", err)
addJobError(jobId, userId, "series episodes could not be imported (request failed): "+show.Title)
job.AddJobError(jobId, userId, "series episodes could not be imported (request failed): "+show.Title)
} else if len(seriesEpisodes.MediaContainer.Metadata) <= 0 {
slog.Info("plexSyncWatched: Series has no episodes.", "series_name", show.Title, "series_id", show.GUID, "user_id", userId)
} else {
@@ -218,46 +258,44 @@ func startPlexSync(
slog.Debug("plexSyncWatched: Skipping import of unplayed episode.", "series_name", show.Title, "season_num", vs.ParentIndex, "episode_num", vs.Index, "user_id", userId)
continue
}
updateJobCurrentTask(jobId, userId, "syncing "+show.Title+" season "+strconv.Itoa(vs.ParentIndex)+" episode "+strconv.Itoa(vs.Index))
job.UpdateJobCurrentTask(jobId, userId, "syncing "+show.Title+" season "+strconv.Itoa(vs.ParentIndex)+" episode "+strconv.Itoa(vs.Index))
var episodeLastViewedAt time.Time
if vs.LastViewedAt != 0 {
episodeLastViewedAt = time.Unix(vs.LastViewedAt, 0)
}
_, err = addWatchedEpisodes(db, userId, WatchedEpisodeAddRequest{
_, err = s.wep.AddWatchedEpisodes(userId, episode.WatchedEpisodeAddRequest{
WatchedID: w.ID,
SeasonNumber: vs.ParentIndex,
EpisodeNumber: vs.Index,
Status: FINISHED,
addActivity: EPISODE_ADDED_PLEX,
addActivityDate: episodeLastViewedAt,
Status: entity.FINISHED,
AddActivity: entity.EPISODE_ADDED_PLEX,
AddActivityDate: episodeLastViewedAt,
})
if err != nil {
slog.Error("plexSyncWatched: Failed to import series episode.", "series_name", show.Title, "season_num", vs.ParentIndex, "episode_num", vs.Index, "user_id", userId, "error", err)
addJobError(jobId, userId, "series episode could not be imported (addWatchedEpisode request failed): "+show.Title+" "+vs.Title)
job.AddJobError(jobId, userId, "series episode could not be imported (addWatchedEpisode request failed): "+show.Title+" "+vs.Title)
}
}
}
}
}
}
updateJobStatus(jobId, userId, JOB_DONE)
job.UpdateJobStatus(jobId, userId, job.JOB_DONE)
}
func plexSyncWatched(
db *gorm.DB,
func (s *SyncService) PlexSyncWatched(
userId uint,
userPlexLocalAuth string,
) (PlexSyncResponse, error) {
jobId, err := addJob("plex_sync", userId)
jobId, err := job.AddJob("plex_sync", userId)
if err != nil {
slog.Error("startPlexSync: Failed to create a job", "error", err)
return PlexSyncResponse{}, errors.New("failed to create job")
}
updateJobStatus(jobId, userId, JOB_RUNNING)
job.UpdateJobStatus(jobId, userId, job.JOB_RUNNING)
go startPlexSync(
db,
go s.startPlexSync(
jobId,
userId,
userPlexLocalAuth,
@@ -0,0 +1,43 @@
package plexmiddleware
import (
"log/slog"
"github.com/gin-gonic/gin"
"github.com/sbondCo/Watcharr/config"
"github.com/sbondCo/Watcharr/database/entity"
"gorm.io/gorm"
)
// Plex access middleware, ensures user is a Plex user.
// To be ran after AuthRequired middleware with extra data.
func PlexAccessRequired(db *gorm.DB, cfg *config.ServerConfig) gin.HandlerFunc {
return func(c *gin.Context) {
userId := c.MustGet("userId").(uint)
slog.Debug("PlexAccessRequired middleware hit", "user_id", userId)
userType := c.MustGet("userType").(entity.UserType)
if cfg.PLEX_HOST == "" || cfg.PLEX_MACHINE_ID == "" {
slog.Error("PlexAccessRequired: Plex has not been configured.", "user_id", userId)
c.AbortWithStatus(401)
return
}
if userType != entity.PLEX_USER {
slog.Error("PlexAccessRequired: User is not a Plex user..", "user_id", userId, "user_type", userType)
c.AbortWithStatus(401)
return
}
userPlexService := new(entity.UserServices)
if res := db.Where("user_id = ? AND name = ?", userId, "plex").Take(&userPlexService); res.Error != nil {
slog.Error("PlexAccessRequired: Failed when attempting to get users plex service integration..", "user_id", userId, "user_type", userType)
c.AbortWithStatus(401)
return
}
if userPlexService.ClientID == "" || userPlexService.AuthToken == "" || userPlexService.AuthToken2 == "" {
slog.Error("PlexAccessRequired: User has missing details from service (clientId, authToken or authToken2)..", "user_id", userId, "client_id", userPlexService.ClientID)
c.AbortWithStatus(401)
return
}
c.Set("plexAuthToken", userPlexService.AuthToken)
c.Set("plexLocalAuthToken", userPlexService.AuthToken2)
}
}
+45
View File
@@ -0,0 +1,45 @@
package plex
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/sbondCo/Watcharr/feature/auth/authmiddleware"
"github.com/sbondCo/Watcharr/feature/plex/plexmiddleware"
"github.com/sbondCo/Watcharr/router"
)
type Router struct {
br *router.BaseRouter
ss *SyncService
}
func NewRouter(br *router.BaseRouter, ss *SyncService) *Router {
return &Router{
br,
ss,
}
}
func (r *Router) AddRoutes() {
plex := r.br.Router.Group("/plex").
Use(
authmiddleware.AuthRequired(r.br.DB, r.br.Cfg),
plexmiddleware.PlexAccessRequired(r.br.DB, r.br.Cfg),
)
// Sync users plex watched items to watchlist
plex.GET("/sync", r.GetSync)
}
// Sync users plex watched items to watchlist
func (r *Router) GetSync(c *gin.Context) {
userId := c.MustGet("userId").(uint)
userPlexLocalAuth := c.MustGet("plexLocalAuthToken").(string)
response, err := r.ss.PlexSyncWatched(userId, userPlexLocalAuth)
if err != nil {
c.JSON(http.StatusForbidden, router.ErrorResponse{Error: err.Error()})
return
}
c.JSON(http.StatusOK, response)
}
@@ -1,4 +1,4 @@
package main
package profile
import (
"encoding/json"
@@ -6,6 +6,7 @@ import (
"log/slog"
"time"
"github.com/sbondCo/Watcharr/database/entity"
"gorm.io/gorm"
)
@@ -17,15 +18,25 @@ type Profile struct {
ShowsWatchedRuntime uint32 `json:"showsWatchedRuntime"`
}
type Service struct {
db *gorm.DB
}
func NewService(db *gorm.DB) *Service {
return &Service{
db,
}
}
// Check if content has been previsouly watched by looking for related activity.
func hasBeenPreviouslyWatched(a *[]Activity) bool {
func (s *Service) hasBeenPreviouslyWatched(a *[]entity.Activity) bool {
wp := false
var relatedActivity []Activity
var relatedActivity []entity.Activity
for _, v := range *a {
if v.Type == ADDED_WATCHED ||
v.Type == IMPORTED_ADDED_WATCHED ||
v.Type == IMPORTED_WATCHED ||
v.Type == STATUS_CHANGED {
if v.Type == entity.ADDED_WATCHED ||
v.Type == entity.IMPORTED_ADDED_WATCHED ||
v.Type == entity.IMPORTED_WATCHED ||
v.Type == entity.STATUS_CHANGED {
relatedActivity = append(relatedActivity, v)
}
}
@@ -33,10 +44,10 @@ func hasBeenPreviouslyWatched(a *[]Activity) bool {
return false
}
for _, ra := range relatedActivity {
if ra.Type == IMPORTED_ADDED_WATCHED {
if ra.Type == entity.IMPORTED_ADDED_WATCHED {
wp = true
break
} else if ra.Type == ADDED_WATCHED || ra.Type == IMPORTED_WATCHED {
} else if ra.Type == entity.ADDED_WATCHED || ra.Type == entity.IMPORTED_WATCHED {
if ra.Data == "" {
continue
}
@@ -52,7 +63,7 @@ func hasBeenPreviouslyWatched(a *[]Activity) bool {
break
}
}
} else if ra.Type == STATUS_CHANGED {
} else if ra.Type == entity.STATUS_CHANGED {
if ra.Data == "FINISHED" {
wp = true
break
@@ -63,15 +74,15 @@ func hasBeenPreviouslyWatched(a *[]Activity) bool {
}
// Gets any data required for profile page
func getProfile(db *gorm.DB, userId uint) (Profile, error) {
user := new(User)
res := db.Model(&User{}).Where("id = ?", userId).Take(&user)
func (s *Service) getProfile(userId uint) (Profile, error) {
user := new(entity.User)
res := s.db.Model(&entity.User{}).Where("id = ?", userId).Take(&user)
if res.Error != nil {
slog.Error("Failed to get profile:", "error", res.Error.Error())
return Profile{}, errors.New("failed to get profile")
}
watched := new([]Watched)
res = db.Model(&Watched{}).Preload("Content").Preload("Activity").Where("user_id = ?", userId).Find(&watched)
watched := new([]entity.Watched)
res = s.db.Model(&entity.Watched{}).Preload("Content").Preload("Activity").Where("user_id = ?", userId).Find(&watched)
if res.Error != nil {
slog.Error("Profile: Failed to get watched for processing:", "error", res.Error.Error())
return Profile{}, errors.New("failed to get watched for processing")
@@ -84,9 +95,9 @@ func getProfile(db *gorm.DB, userId uint) (Profile, error) {
)
for _, w := range *watched {
isFinished := false
if w.Status == FINISHED {
if w.Status == entity.FINISHED {
isFinished = true
} else if *user.IncludePreviouslyWatched && hasBeenPreviouslyWatched(&w.Activity) {
} else if *user.IncludePreviouslyWatched && s.hasBeenPreviouslyWatched(&w.Activity) {
// If status is not finished and user has IncludePreviouslyWatched enabled,
// then we can also check if content hasBeenPreviouslyWatched.
isFinished = true
@@ -96,7 +107,7 @@ func getProfile(db *gorm.DB, userId uint) (Profile, error) {
continue
}
c := *w.Content
if c.Type == SHOW {
if c.Type == entity.SHOW {
showsWatched++
// This aint a science, just a very inaccurate guesstimate.
if c.NumberOfEpisodes != 0 {
@@ -107,7 +118,7 @@ func getProfile(db *gorm.DB, userId uint) (Profile, error) {
showsWatchedRuntime += showRuntime * c.NumberOfEpisodes
slog.Debug("calcualted", "show", c.Title, "runti", showRuntime*c.NumberOfEpisodes)
}
} else if c.Type == MOVIE {
} else if c.Type == entity.MOVIE {
moviesWatched++
moviesWatchedRuntime += c.Runtime
}

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