Skip to content
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

Support rewatch feature #631

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ Automatically scrobble all TV episodes and movies you are watching to Trakt.tv!

- Automatically scrobble what you're watching
- [Mobile apps](http://trakt.tv/downloads) for iPhone, iPad, Android, and Windows Phone
- Share what you're watching (in real time) and rating to facebook and twitter
- Share what you're watching (in real time) and rating to Facebook and Twitter
- Personalized calendar so you never miss a TV show
- Follow your friends and people you're interesed in
- Follow your friends and people you're interested in
- Use watchlists so you don't forget what to watch
- Track your media collections and impress your friends
- Create custom lists around any topics you choose
Expand All @@ -51,7 +51,7 @@ Remote streaming content will scrobble assuming the metadata is correctly set in

### Installation

If your not a developer, you should only install this from the official Kodi repo via Kodi itself. If you are a dev, here is how you install the dev version:
If you're not a developer, you should only install this from the official Kodi repo via Kodi itself. If you are a dev, here is how you install the dev version:

1. Download the zip ([download it here](../../zipball/main))
2. Install script.trakt by zip. Go to _Settings_ > _Add-ons_ > _Install from zip file_ > Choose the just downloaded zip
Expand Down
8 changes: 8 additions & 0 deletions resources/language/resource.language.en_US/strings.po
Original file line number Diff line number Diff line change
Expand Up @@ -777,3 +777,11 @@ msgstr ""
#~ msgctxt "#32161"
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How do I generate the correct po files and add the missing translations?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The base translation file is en_gb so you should only be editing that

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm noticing errors in git due to there being a en_US and en_us language folder for example.

warning: the following paths have collided (e.g. case-sensitive paths
on a case-insensitive filesystem) and only one from the same
colliding group is in the working tree:

  'resources/language/resource.language.es_AR/strings.po'
  'resources/language/resource.language.es_ar/strings.po'
  'resources/language/resource.language.es_MX/strings.po'
  'resources/language/resource.language.es_mx/strings.po'
  'resources/language/resource.language.nb_NO/strings.po'
  'resources/language/resource.language.nb_no/strings.po'
  'resources/language/resource.language.pt_BR/strings.po'
  'resources/language/resource.language.pt_br/strings.po'

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

that's probably a windows thing

#~ msgid "Enter the PIN provided in the box below."
#~ msgstr "Enter the PIN provided in the box below."

msgctxt "#32192"
msgid "Remove watched status from Kodi when rewatching"
msgstr "Remove watched status from Kodi when rewatching"

msgctxt "#32193"
msgid "Include specials"
msgstr "Include specials"
20 changes: 12 additions & 8 deletions resources/lib/kodiUtilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,11 +165,13 @@ def kodiRpcToTraktMediaObject(type, data, mode='collected'):
data['ids'] = utilities.guessBestTraktId(id, type)[0]

if 'lastplayed' in data:
episode['watched_at'] = utilities.convertDateTimeToUTC(
data['lastplayed'])
episode['last_watched_at'] = utilities.to_iso8601_datetime(
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The key watched_at was inconsistent with Trakt's last_watched_at so I updated it.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Kodi's timestamps were in a different format from those the Trakt.py library provides so this was updated.

utilities.from_datetime(data['lastplayed'])
)
if 'dateadded' in data:
episode['collected_at'] = utilities.convertDateTimeToUTC(
data['dateadded'])
episode['collected_at'] = utilities.to_iso8601_datetime(
utilities.from_datetime(data['dateadded'])
)
if 'runtime' in data:
episode['runtime'] = data['runtime']
episode['rating'] = data['userrating'] if 'userrating' in data and data['userrating'] > 0 else 0
Expand All @@ -184,11 +186,13 @@ def kodiRpcToTraktMediaObject(type, data, mode='collected'):
if checkExclusion(data.pop('file')):
return
if 'lastplayed' in data:
data['watched_at'] = utilities.convertDateTimeToUTC(
data.pop('lastplayed'))
data['last_watched_at'] = utilities.to_iso8601_datetime(
utilities.from_datetime(data.pop('lastplayed'))
)
if 'dateadded' in data:
data['collected_at'] = utilities.convertDateTimeToUTC(
data.pop('dateadded'))
data['collected_at'] = utilities.to_iso8601_datetime(
utilities.from_datetime(data.pop('dateadded'))
)
if data['playcount'] is None:
data['plays'] = 0
else:
Expand Down
14 changes: 10 additions & 4 deletions resources/lib/syncEpisodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,9 +208,11 @@ def __traktLoadShows(self):
int(y), line2=kodiUtilities.getString(32102) % (i, x))

# will keep the data in python structures - just like the KODI response
show = show.to_dict()

showsWatched['shows'].append(show)
show_dict = show.to_dict()
# reset_at is not included when calling `.to_dict()`
# but needed for watched shows to know whether to reset the watched state
show_dict['reset_at'] = utilities.to_iso8601_datetime(show.reset_at) if hasattr(show, 'reset_at') else None
Copy link
Author

@beschoenen beschoenen Dec 29, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The reset_at is now needed on a show, and while Show extends Media in the trakt.py library, it is not included when calling to_dict() on a show.

showsWatched['shows'].append(show_dict)

i = 0
x = float(len(traktShowsRated))
Expand Down Expand Up @@ -425,6 +427,10 @@ def __addEpisodesToKodiWatched(self, traktShows, kodiShows, kodiShowsCollected,
updateKodiTraktShows = copy.deepcopy(traktShows)
updateKodiKodiShows = copy.deepcopy(kodiShows)

if kodiUtilities.getSettingAsBool('kodi_episode_reset'):
utilities.updateTraktLastWatchedBasedOnResetAt(
updateKodiTraktShows, updateSpecials=kodiUtilities.getSettingAsBool('kodi_episode_reset_specials'))

kodiShowsUpdate = utilities.compareEpisodes(updateKodiTraktShows, updateKodiKodiShows, kodiUtilities.getSettingAsBool(
"scrobble_fallback"), watched=True, restrict=True, collected=kodiShowsCollected)

Expand All @@ -446,7 +452,7 @@ def __addEpisodesToKodiWatched(self, traktShows, kodiShows, kodiShowsCollected,
for season in show['seasons']:
for episode in season['episodes']:
episodes.append({'episodeid': episode['ids']['episodeid'], 'playcount': episode['plays'],
"lastplayed": utilities.convertUtcToDateTime(episode['last_watched_at'])})
"lastplayed": utilities.to_datetime(utilities.from_iso8601_datetime(episode['last_watched_at']))})

# split episode list into chunks of 50
chunksize = 50
Expand Down
2 changes: 1 addition & 1 deletion resources/lib/syncMovies.py
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@ def __addMoviesToKodiWatched(self, traktMovies, kodiMovies, fromPercent, toPerce
# split movie list into chunks of 50
chunksize = 50
chunked_movies = utilities.chunks([{"jsonrpc": "2.0", "method": "VideoLibrary.SetMovieDetails", "params": {"movieid": kodiMoviesToUpdate[i]['movieid'], "playcount": kodiMoviesToUpdate[i]
['plays'], "lastplayed": utilities.convertUtcToDateTime(kodiMoviesToUpdate[i]['last_watched_at'])}, "id": i} for i in range(len(kodiMoviesToUpdate))], chunksize)
['plays'], "lastplayed": utilities.to_datetime(utilities.from_iso8601_datetime(kodiMoviesToUpdate[i]['last_watched_at']))}, "id": i} for i in range(len(kodiMoviesToUpdate))], chunksize)
i = 0
x = float(len(kodiMoviesToUpdate))
for chunk in chunked_movies:
Expand Down
98 changes: 64 additions & 34 deletions resources/lib/utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import dateutil.parser
from datetime import datetime
from dateutil.tz import tzutc, tzlocal
import arrow
razzeee marked this conversation as resolved.
Show resolved Hide resolved

# make strptime call prior to doing anything, to try and prevent threading
# errors
Expand Down Expand Up @@ -181,40 +182,49 @@ def findEpisodeMatchInList(id, seasonNumber, episodeNumber, list, idType):
return {}


def convertDateTimeToUTC(toConvert):
if toConvert:
dateFormat = "%Y-%m-%d %H:%M:%S"
try:
naive = datetime.strptime(toConvert, dateFormat)
except TypeError:
naive = datetime(*(time.strptime(toConvert, dateFormat)[0:6]))

try:
local = naive.replace(tzinfo=tzlocal())
utc = local.astimezone(tzutc())
except ValueError:
logger.debug(
'convertDateTimeToUTC() ValueError: movie/show was collected/watched outside of the unix timespan. Fallback to datetime utcnow')
utc = datetime.utcnow()
return str(utc)
else:
return toConvert


def convertUtcToDateTime(toConvert):
if toConvert:
dateFormat = "%Y-%m-%d %H:%M:%S"
try:
naive = dateutil.parser.parse(toConvert)
utc = naive.replace(tzinfo=tzutc())
local = utc.astimezone(tzlocal())
except ValueError:
logger.debug(
'convertUtcToDateTime() ValueError: movie/show was collected/watched outside of the unix timespan. Fallback to datetime now')
local = datetime.now()
return local.strftime(dateFormat)
else:
return toConvert
def to_datetime(value):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I replaced the existing datetime transformation methods with these 4 new ones, the iso8601 methods come from the trakt.py library.

if not value:
return None

return value.strftime('%Y-%m-%d %H:%M:%S')


def from_datetime(value):
if not value:
return None

if arrow is None:
raise Exception('"arrow" module is not available')

# Parse datetime
dt = arrow.get(value, 'YYYY-MM-DD HH:mm:ss')

# Return datetime object
return dt.datetime


def to_iso8601_datetime(value):
if not value:
return None

return value.strftime('%Y-%m-%dT%H:%M:%S') + '.000-00:00'


def from_iso8601_datetime(value):
if not value:
return None

if arrow is None:
raise Exception('"arrow" module is not available')

# Parse ISO8601 datetime
dt = arrow.get(value, 'YYYY-MM-DDTHH:mm:ss.SZZ')

# Convert to UTC
dt = dt.to('UTC')

# Return datetime object
return dt.datetime


def createError(ex):
Expand Down Expand Up @@ -412,6 +422,12 @@ def compareEpisodes(shows_col1, shows_col2, matchByTitleAndYear, watched=False,
if season in season_col2:
b = season_col2[season]
diff = list(set(a).difference(set(b)))
for key in a:
# update lastplayed in KODI if they don't match trakt
if not key in b or a[key]['last_watched_at'] != b[key]['last_watched_at']:
Copy link
Author

@beschoenen beschoenen Dec 29, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not a 100% sure is this is the correct solution. This will update any out of date timestamps not just ones to be removed.

diff.append(key)
# make unique
diff = list(set(diff))
if playback:
t = list(set(a).intersection(set(b)))
if len(t) > 0:
Expand Down Expand Up @@ -571,3 +587,17 @@ def _fuzzyMatch(string1, string2, match_percent=55.0):
s = difflib.SequenceMatcher(None, string1, string2)
s.find_longest_match(0, len(string1), 0, len(string2))
return (difflib.SequenceMatcher(None, string1, string2).ratio() * 100) >= match_percent


def updateTraktLastWatchedBasedOnResetAt(traktShows, updateSpecials=False):
for show in traktShows['shows']:
if show['reset_at']:
reset_at = from_iso8601_datetime(show['reset_at'])
for season in show['seasons']:
if not updateSpecials and season['number'] == 0:
continue
for episode in season['episodes']:
last_watched = from_iso8601_datetime(episode['last_watched_at'])
if last_watched and last_watched < reset_at:
episode['last_watched_at'] = None
episode['plays'] = 0
17 changes: 17 additions & 0 deletions resources/settings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -580,6 +580,23 @@
<default>true</default>
<level>1</level>
</setting>
<setting id="kodi_episode_reset" type="boolean" label="32192" help="" parent="kodi_episode_playcount">
<control type="toggle" />
<default>false</default>
<level>1</level>
<dependencies>
<dependency type="visible" setting="kodi_episode_playcount">true</dependency>
</dependencies>
</setting>
<setting id="kodi_episode_reset_specials" type="boolean" label="32193" help="" parent="kodi_episode_reset">
<control type="toggle" />
<default>false</default>
<level>1</level>
<dependencies>
<dependency type="visible" setting="kodi_episode_playcount">true</dependency>
<dependency type="enable" setting="kodi_episode_reset">true</dependency>
</dependencies>
</setting>
<setting id="trakt_episode_playback" type="boolean" label="32118" help="">
<control type="toggle" />
<default>false</default>
Expand Down