forked from ASK-ME-ABOUT-LOOM/purgeomatic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
delete.movies.unwatched.py
138 lines (118 loc) · 4.31 KB
/
delete.movies.unwatched.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
import os
import config
import json
import requests
from datetime import datetime
import jq
import sys
c = config.Config()
if not c.check("tautulliAPIkey", "radarrAPIkey"):
print("ERROR: Required Tautulli/Radarr API key not set. Cannot continue.")
sys.exit(1)
c.apicheck(c.radarrHost, c.radarrAPIkey)
protected = []
if os.path.exists("./protected"):
with open("./protected", "r") as file:
while line := file.readline():
protected.append(int(line.rstrip()))
print("--------------------------------------")
print(datetime.now().isoformat())
def purge(movie):
deletesize = 0
tmdbid = None
r = requests.get(
f"{c.tautulliHost}/api/v2/?apikey={c.tautulliAPIkey}&cmd=get_metadata&rating_key={movie['rating_key']}"
)
guids = jq.compile(".[].data.guids").input(r.json()).first()
try:
if guids:
tmdbid = [i for i in guids if i.startswith("tmdb://")][0].split(
"tmdb://", 1
)[1]
except Exception as e:
print(
f"WARNING: {movie['title']}: Unexpected GUID metadata from Tautulli. Please refresh your library's metadata in Plex. Using less-accurate 'search mode' for this title. Error message: "
+ str(e)
)
guids = []
f = requests.get(f"{c.radarrHost}/api/v3/movie?apiKey={c.radarrAPIkey}")
try:
if guids:
radarr = (
jq.compile(f".[] | select(.tmdbId == {tmdbid})").input(f.json()).first()
)
else:
radarr = (
jq.compile(f".[] | select(.title == \"{movie['title']}\")")
.input(f.json())
.first()
)
if radarr["tmdbId"] in protected:
return deletesize
if not c.dryrun:
response = requests.delete(
f"{c.radarrHost}/api/v3/movie/"
+ str(radarr["id"])
+ f"?apiKey={c.radarrAPIkey}&deleteFiles=true"
)
try:
if not c.dryrun and c.overseerrAPIkey is not None:
headers = {"X-Api-Key": f"{c.overseerrAPIkey}"}
o = requests.get(
f"{c.overseerrHost}/api/v1/movie/" + str(radarr["tmdbId"]),
headers=headers,
)
overseerr = json.loads(o.text)
o = requests.delete(
f"{c.overseerrHost}/api/v1/media/"
+ str(overseerr["mediaInfo"]["id"]),
headers=headers,
)
except Exception as e:
print("ERROR: Unable to connect to overseerr. Error message: " + str(e))
action = "DELETED"
if c.dryrun:
action = "DRY RUN"
deletesize = int(movie["file_size"]) / 1073741824
print(
action
+ ": "
+ movie["title"]
+ " | "
+ str("{:.2f}".format(deletesize))
+ "GB"
+ " | Radarr ID: "
+ str(radarr["id"])
+ " | TMDB ID: "
+ str(radarr["tmdbId"])
)
except StopIteration:
pass
except Exception as e:
print("ERROR: " + movie["title"] + ": " + str(e))
return deletesize
today = round(datetime.now().timestamp())
totalsize = 0
r = requests.get(
f"{c.tautulliHost}/api/v2/?apikey={c.tautulliAPIkey}&cmd=get_library_media_info§ion_id={c.tautulliMovieSectionID}&length={c.tautulliNumRows}&refresh=true"
)
movies = json.loads(r.text)
try:
for movie in movies["response"]["data"]["data"]:
if movie["last_played"]:
lp = round((today - int(movie["last_played"])) / 86400)
if lp > c.daysSinceLastWatch:
totalsize = totalsize + purge(movie)
else:
if c.daysWithoutWatch > 0:
if movie["added_at"] and movie["play_count"] is None:
aa = round((today - int(movie["added_at"])) / 86400)
if aa > c.daysWithoutWatch:
totalsize = totalsize + purge(movie)
except Exception as e:
print(
"ERROR: There was a problem connecting to Tautulli/Radarr/Overseerr. Please double-check that your connection settings and API keys are correct.\n\nError message:\n"
+ str(e)
)
sys.exit(1)
print("Total space reclaimed: " + str("{:.2f}".format(totalsize)) + "GB")