-
Notifications
You must be signed in to change notification settings - Fork 170
Import Watcharr JSON #1244
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
JodliDev
wants to merge
6
commits into
FuzzyGrim:dev
Choose a base branch
from
JodliDev:import_watcharr
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Import Watcharr JSON #1244
Changes from 1 commit
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
dea6491
Add option to import an exported Watcharr JSON
JodliDev 37f4e4b
Resolve Gemini code review suggestions
JodliDev d948782
Resolve Gemini code review suggestions
JodliDev 8360236
Merge remote-tracking branch 'origin/import_watcharr' into import_wat…
JodliDev 89e418d
Fix end_date not depending on correct state string
JodliDev da744a1
Remove dateutil dependency and use string manipulation instead
JodliDev File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -25,3 +25,4 @@ redis[hiredis]==7.1.0 | |
| requests==2.32.5 | ||
| requests-ratelimiter==0.8.0 | ||
| unidecode==1.4.0 | ||
| python-dateutil | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,130 @@ | ||
| import json | ||
| import logging | ||
|
|
||
| from dateutil import parser | ||
|
|
||
| from integrations.imports.yamtrack import YamtrackImporter | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class UnknownStateError(Exception): | ||
| """Custom exception for unexpected state string.""" | ||
|
|
||
|
|
||
| def importer(file, user, mode): | ||
| """Import media from Watcharr JSON file resuing the YamtrackImporter.""" | ||
| csv_importer = WatcharrImporter(file, user, mode) | ||
| return csv_importer.import_data() | ||
|
|
||
|
|
||
| def get_state(state): | ||
| """Convert the Watcharr status to a Yamtrack status.""" | ||
| match state: | ||
| case "FINISHED": | ||
| return "Completed" | ||
| case "WATCHING": | ||
| return "In progress" | ||
| case "PLANNED": | ||
| return "Planning" | ||
| case "PAUSED": | ||
| return "Paused" | ||
| case "DROPPED": | ||
| return "Dropped" | ||
| case _: | ||
| raise UnknownStateError | ||
|
JodliDev marked this conversation as resolved.
Outdated
|
||
|
|
||
|
|
||
| def to_date(date_str): | ||
| """Convert the Watcharr date to ISO 8601.""" | ||
| date = parser.parse(date_str) | ||
| return date.isoformat() | ||
|
|
||
|
|
||
| class WatcharrImporter(YamtrackImporter): | ||
| """Class to handle importing user data from JSON files.""" | ||
|
|
||
| def __init__(self, file, user, mode): | ||
| """Initialize the importer with file, user, and mode. | ||
|
|
||
| Args: | ||
| file: Uploaded CSV file object | ||
| user: Django user object to import data for | ||
| mode (str): Import mode ("new" or "overwrite") | ||
| """ | ||
| super().__init__(file, user, mode) | ||
| self._rows = [] | ||
|
|
||
| def _add_entry(self, media_type, content_entry, state_entry, dict_entry): | ||
| """Add a single entry to the list of rows.""" | ||
| dict_entry["media_type"] = media_type | ||
| dict_entry["source"] = "tmdb" | ||
| # when testing, in integrations/imports/helpers.py::update_season_references() | ||
| # existing_tv uses strings as keys: | ||
| dict_entry["media_id"] = str(content_entry["content"]["tmdbId"]) | ||
| dict_entry["title"] = content_entry["content"]["title"] | ||
|
|
||
| dict_entry["score"] = state_entry["rating"] | ||
| dict_entry["status"] = get_state(state_entry["status"]) | ||
| dict_entry["created_at"] = to_date(state_entry["createdAt"]) | ||
| dict_entry["progressed_at"] = to_date(state_entry["updatedAt"]) | ||
|
|
||
| dict_entry["image"] = "" | ||
| dict_entry["notes"] = "" | ||
| dict_entry["start_date"] = "" | ||
| dict_entry["end_date"] = "" | ||
|
|
||
| if "season_number" not in dict_entry: | ||
| dict_entry["season_number"] = "" | ||
| if "episode_number" not in dict_entry: | ||
| dict_entry["episode_number"] = "" | ||
| if "progress" not in dict_entry: | ||
| dict_entry["progress"] = "" | ||
|
JodliDev marked this conversation as resolved.
Outdated
|
||
|
|
||
| self._rows.append(dict_entry) | ||
|
|
||
| def get_iterator(self): | ||
| """Process the JSON file and return an array for YamtrackImporter.""" | ||
| self._rows = [] | ||
| json_structure = json.load(self.file) | ||
|
|
||
| for entry in json_structure: | ||
| try: | ||
| self._process_entry(entry) | ||
| except Exception as error: | ||
| error_msg = f"Error processing entry: {entry}" | ||
| logger.exception(error_msg) | ||
| self.warnings.append(f"{error_msg}. Error: {error}") | ||
| return self._rows | ||
|
|
||
| def _process_entry(self, entry): | ||
| """Process a single entry from the main array in the JSON file.""" | ||
| match entry["content"]["type"]: | ||
| case "movie": | ||
| self._add_entry( | ||
| "movie", | ||
| entry, | ||
| entry, | ||
| {"progress": 1 if entry["status"] == "FINISHED" else 0}, | ||
| ) | ||
|
JodliDev marked this conversation as resolved.
|
||
| case "tv": | ||
| self._add_entry("tv", entry, entry, {}) | ||
| if "watchedSeasons" in entry: | ||
| for season in entry["watchedSeasons"]: | ||
| self._add_entry( | ||
| "season", | ||
| entry, | ||
| season, | ||
| {"season_number": season["seasonNumber"]}, | ||
| ) | ||
| if "watchedEpisodes" in entry: | ||
| for episode in entry["watchedEpisodes"]: | ||
| self._add_entry( | ||
| "episode", | ||
| entry, | ||
| episode, | ||
| { | ||
| "season_number": episode["seasonNumber"], | ||
| "episode_number": episode["episodeNumber"], | ||
| }, | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| from pathlib import Path | ||
|
|
||
| from django.contrib.auth import get_user_model | ||
| from django.test import TestCase | ||
|
|
||
| from app.models import ( | ||
| TV, | ||
| Episode, | ||
| Movie, | ||
| Season, | ||
| ) | ||
| from integrations.imports import ( | ||
| watcharr, | ||
| ) | ||
|
|
||
| mock_path = Path(__file__).resolve().parent.parent / "mock_data" | ||
| app_mock_path = ( | ||
| Path(__file__).resolve().parent.parent.parent.parent / "app" / "tests" / "mock_data" | ||
| ) | ||
|
|
||
|
|
||
| class ImportWatcharr(TestCase): | ||
| """Test importing media from Watcharr JSON.""" | ||
|
|
||
| def setUp(self): | ||
| """Create user for the tests.""" | ||
| self.credentials = {"username": "test", "password": "12345"} | ||
| self.user = get_user_model().objects.create_user(**self.credentials) | ||
| with Path(mock_path / "import_watcharr.json").open("rb") as file: | ||
| self.import_results = watcharr.importer(file, self.user, "new") | ||
|
|
||
| def test_import_counts(self): | ||
| """Test basic counts of imported media.""" | ||
| self.assertEqual(TV.objects.filter(user=self.user).count(), 1) | ||
| self.assertEqual(Movie.objects.filter(user=self.user).count(), 2) | ||
| self.assertEqual(Season.objects.filter(user=self.user).count(), 3) | ||
| self.assertEqual( | ||
| Episode.objects.filter(related_season__user=self.user).count(), | ||
| 34, | ||
| ) | ||
|
JodliDev marked this conversation as resolved.
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.