Skip to content

Instantly share code, notes, and snippets.

@mariolima
Created August 27, 2022 21:18
Show Gist options
  • Save mariolima/f48cdbe51e8f1cb393c27fa22ee8f28f to your computer and use it in GitHub Desktop.
Save mariolima/f48cdbe51e8f1cb393c27fa22ee8f28f to your computer and use it in GitHub Desktop.
from datetime import datetime, timedelta
import requests
import json
import time
from plexapi.server import PlexServer
baseurl = 'https://my-plex-server.com'
token = 'plex-api-token'
plex = PlexServer(baseurl, token)
def movie(m):
return {
"movies": [
{
"watched_at": (m.lastViewedAt-timedelta(hours = 1)).strftime('%Y-%m-%dT%H:%M:%S.%f%z'),
"title": m.title,
"year": m.year,
"ids": {
"imdb": m.guids[0].id.split('/')[2]
}
}
]
}
def episode(ep):
show=ep.show()
return {
"shows": [
{
"title": "",
"year": 2007,
"ids": {
"tvdb": int(show.guids[2].id.split('/')[2])
},
"seasons": [
{
"number": ep.seasonNumber,
"episodes": [
{
"watched_at": (ep.lastViewedAt-timedelta(hours = 1)).strftime('%Y-%m-%dT%H:%M:%S.%f%z'),
"number": ep.index
}
]
}
]
}
]
}
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer trakt-api-auth-bearer',
'trakt-api-version': '2',
'trakt-api-key': 'trakt-api-key'
}
def getLastUpdate():
text=requests.get('https://api.trakt.tv/sync/last_activities', headers=headers).text
print(text)
data = json.loads(text)
last = data['all'].split('.')[0]
return datetime.strptime(last,'%Y-%m-%dT%H:%M:%S')
last = getLastUpdate()
print(last)
for mov in plex.library.search(unwatched=False,libtype='movie'):
if last > (mov.lastViewedAt-timedelta(hours = 1)):
continue
data = movie(mov)
print(json.dumps(data, indent=4))
data = requests.post('https://api.trakt.tv/sync/history', data=json.dumps(movie(mov),indent=4), headers=headers)
print(data.text)
for ep in plex.library.search(unwatched=False,libtype='episode'):
if '4K' in ep.librarySectionTitle:
continue
if last > (ep.lastViewedAt-timedelta(hours = 1)):
continue
try:
data = episode(ep)
except:
continue
print(json.dumps(data, indent=4))
data = requests.post('https://api.trakt.tv/sync/history', data=json.dumps(episode(ep),indent=4), headers=headers)
print(data.text)
time.sleep(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment