-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
280 lines (220 loc) · 12.1 KB
/
app.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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import logging
from logging.handlers import TimedRotatingFileHandler
from datetime import datetime, timedelta
import os
import json
import requests
from requests.exceptions import HTTPError
from flask import Flask, request
from dotenv import load_dotenv
load_dotenv()
app = Flask(__name__)
# Set up logging
log_directory = '/app/log'
log_filename = os.path.join(log_directory, 'jellyfin_telegram-notifier.log')
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# Ensure the log directory exists
os.makedirs(log_directory, exist_ok=True)
# Create a handler for rotating log files daily
rotating_handler = TimedRotatingFileHandler(log_filename, when="midnight", interval=1, backupCount=7)
rotating_handler.setLevel(logging.INFO)
rotating_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
# Add the rotating handler to the logger
logging.getLogger().addHandler(rotating_handler)
# Constants
TELEGRAM_BOT_TOKEN = os.environ["TELEGRAM_BOT_TOKEN"]
TELEGRAM_CHAT_ID = os.environ["TELEGRAM_CHAT_ID"]
JELLYFIN_BASE_URL = os.environ["JELLYFIN_BASE_URL"]
JELLYFIN_API_KEY = os.environ["JELLYFIN_API_KEY"]
YOUTUBE_API_KEY = os.environ["YOUTUBE_API_KEY"]
EPISODE_PREMIERED_WITHIN_X_DAYS = int(os.environ["EPISODE_PREMIERED_WITHIN_X_DAYS"])
SEASON_ADDED_WITHIN_X_DAYS = int(os.environ["SEASON_ADDED_WITHIN_X_DAYS"])
# Path for the JSON file to store notified items
notified_items_file = '/app/data/notified_items.json'
# Function to load notified items from the JSON file
def load_notified_items():
if os.path.exists(notified_items_file):
with open(notified_items_file, 'r') as file:
return json.load(file)
return {}
# Function to save notified items to the JSON file
def save_notified_items(notified_items_to_save):
with open(notified_items_file, 'w') as file:
json.dump(notified_items_to_save, file)
notified_items = load_notified_items()
def send_telegram_photo(photo_id, caption):
base_photo_url = f"{JELLYFIN_BASE_URL}/Items/{photo_id}/Images"
primary_photo_url = f"{base_photo_url}/Primary"
# Download the image from the jellyfin
image_response = requests.get(primary_photo_url)
# Upload the image to the Telegram bot
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendPhoto"
data = {
"chat_id": TELEGRAM_CHAT_ID,
"caption": caption,
"parse_mode": "Markdown"
}
files = {'photo': ('photo.jpg', image_response.content, 'image/jpeg')}
response = requests.post(url, data=data, files=files)
return response
def get_item_details(item_id):
headers = {'accept': 'application/json', }
params = {'api_key': JELLYFIN_API_KEY, }
url = f"{JELLYFIN_BASE_URL}/emby/Items?Recursive=true&Fields=DateCreated, Overview&Ids={item_id}"
response = requests.get(url, headers=headers, params=params)
response.raise_for_status() # Check if request was successful
return response.json()
def is_within_last_x_days(date_str, x):
days_ago = datetime.now() - timedelta(days=x)
return date_str >= days_ago.isoformat()
def is_not_within_last_x_days(date_str, x):
days_ago = datetime.now() - timedelta(days=x)
return date_str < days_ago.isoformat()
def get_youtube_trailer_url(query):
base_search_url = "https://www.googleapis.com/youtube/v3/search"
if not YOUTUBE_API_KEY:
return None
api_key = YOUTUBE_API_KEY
params = {
'part': 'snippet',
'q': query,
'type': 'video',
'key': api_key
}
response = requests.get(base_search_url, params=params)
response.raise_for_status() # Check for HTTP errors before processing the data
response_data = response.json()
video_id = response_data.get("items", [{}])[0].get('id', {}).get('videoId')
return f"https://www.youtube.com/watch?v={video_id}" if video_id else "Video not found!"
def item_already_notified(item_type, item_name, release_year):
key = f"{item_type}:{item_name}:{release_year}"
return key in notified_items
def mark_item_as_notified(item_type, item_name, release_year, max_entries=100):
key = f"{item_type}:{item_name}:{release_year}"
notified_items[key] = True
# Check if the number of entries in notified_items exceeds the limit
if len(notified_items) > max_entries:
# Get a list of keys (notification identifiers) sorted by their insertion order (oldest first)
keys_sorted_by_insertion_order = sorted(notified_items, key=notified_items.get)
# Remove the oldest entry from the dictionary
oldest_key = keys_sorted_by_insertion_order[0]
del notified_items[oldest_key]
logging.info(f"Key '{oldest_key}' has been deleted from notified_items")
# Save the updated notified items to the JSON file
save_notified_items(notified_items)
@app.route("/webhook", methods=["POST"])
def announce_new_releases_from_jellyfin():
try:
payload = json.loads(request.data)
item_type = payload.get("ItemType")
item_name = payload.get("Name")
release_year = payload.get("Year")
series_name = payload.get("SeriesName")
season_epi = payload.get("EpisodeNumber00")
season_num = payload.get("SeasonNumber00")
if item_type == "Movie":
if not item_already_notified(item_type, item_name, release_year):
movie_id = payload.get("ItemId")
overview = payload.get("Overview")
runtime = payload.get("RunTime")
# Remove release_year from movie_name if present
movie_name = item_name
movie_name_cleaned = movie_name.replace(f" ({release_year})", "").strip()
trailer_url = get_youtube_trailer_url(f"{movie_name_cleaned} Trailer {release_year}")
notification_message = (
f"*🍿New Movie Added🍿*\n\n*{movie_name_cleaned}* *({release_year})*\n\n{overview}\n\n"
f"Runtime\n{runtime}")
if trailer_url:
notification_message += f"\n\n[🎥]({trailer_url})[Trailer]({trailer_url})"
send_telegram_photo(movie_id, notification_message)
mark_item_as_notified(item_type, item_name, release_year)
logging.info(f"(Movie) {movie_name} {release_year} "
f"notification was sent to telegram.")
return "Movie notification was sent to telegram"
if item_type == "Season":
if not item_already_notified(item_type, item_name, release_year):
season_id = payload.get("ItemId")
season = item_name
season_details = get_item_details(season_id)
series_id = season_details["Items"][0].get("SeriesId")
series_details = get_item_details(series_id)
# Remove release_year from series_name if present
series_name_cleaned = series_name.replace(f" ({release_year})", "").strip()
# Get series overview if season overview is empty
overview_to_use = payload.get("Overview") if payload.get("Overview") else series_details["Items"][0].get(
"Overview")
notification_message = (
f"*New Season Added*\n\n*{series_name_cleaned}* *({release_year})*\n\n"
f"*{season}*\n\n{overview_to_use}\n\n")
response = send_telegram_photo(season_id, notification_message)
if response.status_code == 200:
mark_item_as_notified(item_type, item_name, release_year)
logging.info(f"(Season) {series_name_cleaned} {season} "
f"notification was sent to telegram.")
return "Season notification was sent to telegram"
else:
send_telegram_photo(series_id, notification_message)
mark_item_as_notified(item_type, item_name, release_year)
logging.warning(f"{series_name_cleaned} {season} image does not exists, falling back to series image")
logging.info(f"(Season) {series_name_cleaned} {season} notification was sent to telegram")
return "Season notification was sent to telegram"
if item_type == "Episode":
if not item_already_notified(item_type, item_name, release_year):
item_id = payload.get("ItemId")
file_details = get_item_details(item_id)
season_id = file_details["Items"][0].get("SeasonId")
episode_premiere_date = file_details["Items"][0].get("PremiereDate", "0000-00-00T").split("T")[0]
season_details = get_item_details(season_id)
series_id = season_details["Items"][0].get("SeriesId")
season_date_created = season_details["Items"][0].get("DateCreated", "0000-00-00T").split("T")[0]
epi_name = item_name
overview = payload.get("Overview")
if not is_not_within_last_x_days(season_date_created, SEASON_ADDED_WITHIN_X_DAYS):
logging.info(f"(Episode) {series_name} Season {season_num} "
f"was added within the last {SEASON_ADDED_WITHIN_X_DAYS} "
f"days. Not sending notification.")
return (f"Season was added within the last {SEASON_ADDED_WITHIN_X_DAYS} "
f"days. Not sending notification.")
if episode_premiere_date and is_within_last_x_days(episode_premiere_date,
EPISODE_PREMIERED_WITHIN_X_DAYS):
notification_message = (
f"*New Episode Added*\n\n*Release Date*: {episode_premiere_date}\n\n*Series*: {series_name} *S*"
f"{season_num}*E*{season_epi}\n*Episode Title*: {epi_name}\n\n{overview}\n\n"
)
response = send_telegram_photo(season_id, notification_message)
if response.status_code == 200:
mark_item_as_notified(item_type, item_name, release_year)
logging.info(f"(Episode) {series_name} S{season_num}E{season_epi} notification sent to Telegram!")
return "Notification sent to Telegram!"
else:
send_telegram_photo(series_id, notification_message)
logging.warning(f"(Episode) {series_name} season image does not exists, "
f"falling back to series image")
mark_item_as_notified(item_type, item_name, release_year)
logging.info(f"(Episode) {series_name} S{season_num}E{season_epi} notification sent to Telegram!")
return "Notification sent to Telegram!"
else:
logging.info(f"(Episode) {series_name} S{season_num}E{season_epi} "
f"was premiered more than {EPISODE_PREMIERED_WITHIN_X_DAYS} "
f"days ago. Not sending notification.")
return (f"Episode was added more than {EPISODE_PREMIERED_WITHIN_X_DAYS} "
f"days ago. Not sending notification.")
if item_type == "Movie":
logging.info(f"(Movie) {item_name} Notification Was Already Sent")
elif item_type == "Season":
logging.info(f"(Season) {series_name} {item_name} Notification Was Already Sent")
elif item_type == "Episode":
logging.info(f"(Episode) {series_name} S{season_num}E{season_epi} Notification Was Already Sent")
else:
logging.error('Item type not supported')
return "Item type not supported."
# Handle specific HTTP errors
except HTTPError as http_err:
logging.error(f"HTTP error occurred: {http_err}")
return str(http_err)
# Handle generic exceptions
except Exception as e:
logging.error(f"Error: {str(e)}")
return f"Error: {str(e)}"
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)