1use std::collections::HashSet;
3use std::{str::FromStr, sync::Arc};
4
5use actix_web::{
6 HttpRequest, HttpResponse, Responder, Scope, delete, get, post,
7 web::{self, Data, Json, Path as PathParam, Query},
8};
9use agent_storage::{FamilyId, FamilyStore, FileUserIdentityStore, UserId, UserIdentityStore};
10use media_tools::{
11 MediaProfileId, MediaStore, TraktError, TraktOAuthService, TraktSyncError, TraktSyncService,
12};
13use serde::Deserialize;
14use serde_json::json;
15
16use crate::auth::TelegramAuth;
17
18#[derive(Clone, Default)]
20pub struct MediaApiState {
21 pub media: Option<MediaStore>,
22 pub families: Option<Arc<dyn FamilyStore>>,
23 pub trakt_oauth: Option<Arc<TraktOAuthService>>,
24 pub trakt_sync: Option<TraktSyncService>,
25}
26
27#[derive(Debug, Deserialize)]
28pub struct TraktLinkRequest {
29 pub family_id: Option<String>,
30 pub profile_id: String,
31}
32
33#[derive(Debug, Deserialize)]
34pub struct TraktCallbackQuery {
35 pub state: String,
36 pub code: Option<String>,
37 pub error: Option<String>,
38}
39
40#[derive(Debug, Deserialize)]
41pub struct TraktProfileRequest {
42 pub family_id: Option<String>,
43}
44
45#[derive(Debug, Deserialize)]
46pub struct TraktSyncQuery {
47 pub family_id: Option<String>,
48}
49
50#[get("/trakt/profiles")]
51async fn list_trakt_profiles(
52 request: HttpRequest,
53 auth: Data<TelegramAuth>,
54 identities: Data<Arc<FileUserIdentityStore>>,
55 state: Data<MediaApiState>,
56) -> impl Responder {
57 let user_id = match current_user_id(&request, &auth, &identities) {
58 Ok(user_id) => user_id,
59 Err(response) => return response,
60 };
61 let Some(media) = state.media.as_ref() else {
62 return HttpResponse::ServiceUnavailable().body("Media storage is not configured");
63 };
64 let personal = match media.get_or_create_personal_profile(user_id).await {
65 Ok(profile) => profile,
66 Err(error) => return HttpResponse::InternalServerError().body(error.to_string()),
67 };
68 if state.trakt_oauth.is_none() {
69 return HttpResponse::ServiceUnavailable().body("Trakt OAuth is not configured");
70 }
71 let mut profiles = Vec::new();
72 let personal_link = match media
73 .get_external_connection_link(personal.id, "trakt")
74 .await
75 {
76 Ok(link) => link,
77 Err(error) => return HttpResponse::InternalServerError().body(error.to_string()),
78 };
79 let personal_sync = match media.get_provider_sync_state(personal.id, "trakt").await {
80 Ok(sync) => sync,
81 Err(error) => return HttpResponse::InternalServerError().body(error.to_string()),
82 };
83 profiles.push(json!({
84 "profile_id": personal.id,
85 "profile_name": personal.name,
86 "family_id": null,
87 "family_name": "Personal",
88 "trakt": personal_link.map(|link| json!({
89 "username": link.provider_subject,
90 "display_name": link.display_name,
91 "linked_at": link.linked_at,
92 })),
93 "sync": personal_sync,
94 }));
95 let memberships = if let Some(families) = state.families.as_ref() {
96 match families.list_families(user_id).await {
97 Ok(families) => families,
98 Err(error) => return HttpResponse::InternalServerError().body(error.to_string()),
99 }
100 } else {
101 Vec::new()
102 };
103 for family in memberships {
104 let family_profiles = match media.list_profiles(family.id).await {
105 Ok(profiles) => profiles,
106 Err(error) => return HttpResponse::InternalServerError().body(error.to_string()),
107 };
108 for profile in family_profiles
109 .into_iter()
110 .filter(|profile| profile.active && profile.user_id == Some(user_id))
111 {
112 let link = match media
113 .get_external_connection_link(profile.id, "trakt")
114 .await
115 {
116 Ok(link) => link,
117 Err(error) => return HttpResponse::InternalServerError().body(error.to_string()),
118 };
119 let sync = match media.get_provider_sync_state(profile.id, "trakt").await {
120 Ok(sync) => sync,
121 Err(error) => return HttpResponse::InternalServerError().body(error.to_string()),
122 };
123 profiles.push(json!({
124 "profile_id": profile.id,
125 "profile_name": profile.name,
126 "family_id": family.id,
127 "family_name": family.name.clone(),
128 "trakt": link.map(|link| json!({
129 "username": link.provider_subject,
130 "display_name": link.display_name,
131 "linked_at": link.linked_at,
132 })),
133 "sync": sync,
134 }));
135 }
136 }
137 HttpResponse::Ok().json(profiles)
138}
139
140#[post("/trakt/link")]
141async fn start_trakt_link(
142 request: HttpRequest,
143 auth: Data<TelegramAuth>,
144 identities: Data<Arc<FileUserIdentityStore>>,
145 state: Data<MediaApiState>,
146 body: Json<TraktLinkRequest>,
147) -> impl Responder {
148 let Some(oauth) = state.trakt_oauth.as_ref() else {
149 return HttpResponse::ServiceUnavailable().body("Trakt OAuth is not configured");
150 };
151 let owner_id = match current_user_id(&request, &auth, &identities) {
152 Ok(user_id) => user_id,
153 Err(response) => return response,
154 };
155 let profile_id = match MediaProfileId::from_str(&body.profile_id) {
156 Ok(id) => id,
157 Err(error) => return HttpResponse::BadRequest().body(error.to_string()),
158 };
159 let result = match body.family_id.as_deref() {
160 Some(value) => match parse_id::<FamilyId>(value) {
161 Ok(family_id) => oauth.begin_link(owner_id, family_id, profile_id).await,
162 Err(error) => return HttpResponse::BadRequest().body(error),
163 },
164 None => oauth.begin_personal_link(owner_id, profile_id).await,
165 };
166 match result {
167 Ok(authorization) => HttpResponse::Ok().json(authorization),
168 Err(error) => trakt_error_response(error),
169 }
170}
171
172#[get("/trakt/callback")]
173async fn complete_trakt_link(
174 request: HttpRequest,
175 auth: Data<TelegramAuth>,
176 identities: Data<Arc<FileUserIdentityStore>>,
177 state: Data<MediaApiState>,
178 query: Query<TraktCallbackQuery>,
179) -> impl Responder {
180 let Some(oauth) = state.trakt_oauth.as_ref() else {
181 return HttpResponse::ServiceUnavailable().body("Trakt OAuth is not configured");
182 };
183 if let Some(error) = query.error.as_deref() {
184 return HttpResponse::BadRequest().body(format!("Trakt authorization was denied: {error}"));
185 }
186 let Some(code) = query.code.as_deref() else {
187 return HttpResponse::BadRequest()
188 .body("Trakt callback did not include an authorization code");
189 };
190 let owner_id = match current_user_id(&request, &auth, &identities) {
191 Ok(user_id) => user_id,
192 Err(response) => return response,
193 };
194 match oauth.complete_link(owner_id, &query.state, code).await {
195 Ok(link) => HttpResponse::Ok().json(link),
196 Err(error) => trakt_error_response(error),
197 }
198}
199
200#[get("/trakt/profiles/{profile_id}/summary")]
201async fn trakt_profile_summary(
202 request: HttpRequest,
203 auth: Data<TelegramAuth>,
204 identities: Data<Arc<FileUserIdentityStore>>,
205 state: Data<MediaApiState>,
206 profile_id: PathParam<String>,
207 query: Query<TraktSyncQuery>,
208) -> impl Responder {
209 let owner_id = match current_user_id(&request, &auth, &identities) {
210 Ok(user_id) => user_id,
211 Err(response) => return response,
212 };
213 let profile_id = match MediaProfileId::from_str(&profile_id) {
214 Ok(id) => id,
215 Err(error) => return HttpResponse::BadRequest().body(error.to_string()),
216 };
217 let Some(media) = state.media.as_ref() else {
218 return HttpResponse::ServiceUnavailable().body("Media storage is not configured");
219 };
220 let Some(oauth) = state.trakt_oauth.as_ref() else {
221 return HttpResponse::ServiceUnavailable().body("Trakt OAuth is not configured");
222 };
223 let validation = match query.family_id.as_deref() {
224 Some(value) => match parse_id::<FamilyId>(value) {
225 Ok(family_id) => {
226 oauth
227 .validate_profile_owner(owner_id, family_id, profile_id)
228 .await
229 }
230 Err(error) => return HttpResponse::BadRequest().body(error),
231 },
232 None => {
233 oauth
234 .validate_personal_profile_owner(owner_id, profile_id)
235 .await
236 }
237 };
238 if let Err(error) = validation {
239 return trakt_error_response(error);
240 }
241
242 let history = match media.list_watch_history(profile_id).await {
243 Ok(items) => items,
244 Err(error) => return HttpResponse::InternalServerError().body(error.to_string()),
245 };
246 let ratings = match media.list_ratings(profile_id).await {
247 Ok(items) => items,
248 Err(error) => return HttpResponse::InternalServerError().body(error.to_string()),
249 };
250 let watchlist = match media.list_watchlist(profile_id).await {
251 Ok(items) => items,
252 Err(error) => return HttpResponse::InternalServerError().body(error.to_string()),
253 };
254
255 let mut seen = HashSet::new();
256 let mut watched_movies = 0;
257 let mut watched_shows = 0;
258 let mut recently_watched = Vec::new();
259 for event in history
260 .iter()
261 .filter(|event| event.source == media_tools::WatchHistorySource::Trakt)
262 {
263 if !seen.insert(event.media_item_id) {
264 continue;
265 }
266 let item = match media.get_media_item(event.media_item_id).await {
267 Ok(Some(item)) => item,
268 Ok(None) => continue,
269 Err(error) => return HttpResponse::InternalServerError().body(error.to_string()),
270 };
271 match item.kind {
272 media_tools::MediaKind::Movie => watched_movies += 1,
273 media_tools::MediaKind::TvShow => watched_shows += 1,
274 }
275 if recently_watched.len() < 5 {
276 recently_watched.push(json!({
277 "title": &item.title,
278 "kind": match item.kind {
279 media_tools::MediaKind::Movie => "movie",
280 media_tools::MediaKind::TvShow => "tv_show",
281 },
282 "watched_at": &event.watched_at,
283 }));
284 }
285 }
286
287 let ratings_count = ratings
288 .iter()
289 .filter(|rating| rating.source == media_tools::WatchHistorySource::Trakt)
290 .count();
291 let watchlist_count = watchlist
292 .iter()
293 .filter(|item| item.source == media_tools::WatchHistorySource::Trakt)
294 .count();
295
296 HttpResponse::Ok().json(json!({
297 "watched_movies": watched_movies,
298 "watched_shows": watched_shows,
299 "ratings": ratings_count,
300 "watchlist_items": watchlist_count,
301 "recently_watched": recently_watched,
302 }))
303}
304
305#[post("/trakt/profiles/{profile_id}/sync")]
306async fn sync_trakt_profile(
307 request: HttpRequest,
308 auth: Data<TelegramAuth>,
309 identities: Data<Arc<FileUserIdentityStore>>,
310 state: Data<MediaApiState>,
311 profile_id: PathParam<String>,
312 query: Query<TraktSyncQuery>,
313) -> impl Responder {
314 let Some(sync) = state.trakt_sync.as_ref() else {
315 return HttpResponse::ServiceUnavailable().body("Trakt synchronization is not configured");
316 };
317 let owner_id = match current_user_id(&request, &auth, &identities) {
318 Ok(user_id) => user_id,
319 Err(response) => return response,
320 };
321 let profile_id = match MediaProfileId::from_str(&profile_id) {
322 Ok(id) => id,
323 Err(error) => return HttpResponse::BadRequest().body(error.to_string()),
324 };
325 let Some(oauth) = state.trakt_oauth.as_ref() else {
326 return HttpResponse::ServiceUnavailable().body("Trakt OAuth is not configured");
327 };
328 let validation = match query.family_id.as_deref() {
329 Some(value) => match parse_id::<FamilyId>(value) {
330 Ok(family_id) => {
331 oauth
332 .validate_profile_owner(owner_id, family_id, profile_id)
333 .await
334 }
335 Err(error) => return HttpResponse::BadRequest().body(error),
336 },
337 None => {
338 oauth
339 .validate_personal_profile_owner(owner_id, profile_id)
340 .await
341 }
342 };
343 if let Err(error) = validation {
344 return trakt_error_response(error);
345 }
346 match sync.sync_profile(owner_id, profile_id).await {
347 Ok(summary) => HttpResponse::Ok().json(summary),
348 Err(error) => trakt_sync_error_response(error),
349 }
350}
351
352#[delete("/trakt/profiles/{profile_id}")]
353async fn unlink_trakt_profile(
354 request: HttpRequest,
355 auth: Data<TelegramAuth>,
356 identities: Data<Arc<FileUserIdentityStore>>,
357 state: Data<MediaApiState>,
358 profile_id: PathParam<String>,
359 body: Json<TraktProfileRequest>,
360) -> impl Responder {
361 let Some(oauth) = state.trakt_oauth.as_ref() else {
362 return HttpResponse::ServiceUnavailable().body("Trakt OAuth is not configured");
363 };
364 let owner_id = match current_user_id(&request, &auth, &identities) {
365 Ok(user_id) => user_id,
366 Err(response) => return response,
367 };
368 let profile_id = match MediaProfileId::from_str(&profile_id) {
369 Ok(id) => id,
370 Err(error) => return HttpResponse::BadRequest().body(error.to_string()),
371 };
372 let result = match body.family_id.as_deref() {
373 Some(value) => match parse_id::<FamilyId>(value) {
374 Ok(family_id) => oauth.unlink_profile(owner_id, family_id, profile_id).await,
375 Err(error) => return HttpResponse::BadRequest().body(error),
376 },
377 None => oauth.unlink_personal_profile(owner_id, profile_id).await,
378 };
379 match result {
380 Ok(()) => HttpResponse::NoContent().finish(),
381 Err(error) => trakt_error_response(error),
382 }
383}
384
385pub fn media_api() -> Scope {
387 web::scope("/media")
388 .service(list_trakt_profiles)
389 .service(start_trakt_link)
390 .service(complete_trakt_link)
391 .service(trakt_profile_summary)
392 .service(sync_trakt_profile)
393 .service(unlink_trakt_profile)
394}
395
396fn current_user_id(
397 request: &HttpRequest,
398 auth: &TelegramAuth,
399 identities: &FileUserIdentityStore,
400) -> Result<UserId, HttpResponse> {
401 let owner = auth
402 .owner_for_request(request)
403 .ok_or_else(|| HttpResponse::Unauthorized().finish())?;
404 let subject = owner
405 .strip_prefix("telegram:")
406 .filter(|value| !value.is_empty())
407 .ok_or_else(|| HttpResponse::Unauthorized().finish())?;
408 let identity = identities
409 .find_identity("telegram", subject)
410 .map_err(|_| HttpResponse::InternalServerError().finish())?
411 .ok_or_else(|| HttpResponse::Unauthorized().finish())?;
412 Ok(identity.user_id)
413}
414
415fn parse_id<T: for<'de> serde::Deserialize<'de>>(value: &str) -> Result<T, String> {
416 serde_json::from_value(serde_json::Value::String(value.to_owned()))
417 .map_err(|error| error.to_string())
418}
419
420fn trakt_error_response(error: TraktError) -> HttpResponse {
421 match &error {
422 TraktError::Forbidden => HttpResponse::Forbidden().body(error.to_string()),
423 TraktError::ConnectionUnavailable => HttpResponse::NotFound().body(error.to_string()),
424 TraktError::MediaStorage(
425 media_tools::MediaStoreError::PendingNotFound
426 | media_tools::MediaStoreError::PendingExpired,
427 ) => HttpResponse::BadRequest().body(error.to_string()),
428 _ => HttpResponse::BadRequest().body(error.to_string()),
429 }
430}
431
432fn trakt_sync_error_response(error: TraktSyncError) -> HttpResponse {
433 match &error {
434 TraktSyncError::Forbidden => HttpResponse::Forbidden().body(error.to_string()),
435 TraktSyncError::NotLinked => HttpResponse::NotFound().body(error.to_string()),
436 TraktSyncError::RateLimited { .. } => {
437 HttpResponse::TooManyRequests().body(error.to_string())
438 }
439 _ => HttpResponse::BadGateway().body(error.to_string()),
440 }
441}