this repo has no description
1use crate::api::read_after_write::{
2 extract_repo_rev, format_munged_response, get_local_lag, get_records_since_rev,
3 proxy_to_appview, FeedOutput, FeedViewPost, LikeRecord, PostView, RecordDescript,
4};
5use crate::state::AppState;
6use axum::{
7 extract::{Query, State},
8 http::StatusCode,
9 response::{IntoResponse, Response},
10 Json,
11};
12use serde::Deserialize;
13use serde_json::Value;
14use std::collections::HashMap;
15use tracing::warn;
16
17#[derive(Deserialize)]
18pub struct GetActorLikesParams {
19 pub actor: String,
20 pub limit: Option<u32>,
21 pub cursor: Option<String>,
22}
23
24fn insert_likes_into_feed(feed: &mut Vec<FeedViewPost>, likes: &[RecordDescript<LikeRecord>]) {
25 for like in likes {
26 let like_time = &like.indexed_at.to_rfc3339();
27 let idx = feed
28 .iter()
29 .position(|fi| &fi.post.indexed_at < like_time)
30 .unwrap_or(feed.len());
31 let placeholder_post = PostView {
32 uri: like.record.subject.uri.clone(),
33 cid: like.record.subject.cid.clone(),
34 author: crate::api::read_after_write::AuthorView {
35 did: String::new(),
36 handle: String::new(),
37 display_name: None,
38 avatar: None,
39 extra: HashMap::new(),
40 },
41 record: Value::Null,
42 indexed_at: like.indexed_at.to_rfc3339(),
43 embed: None,
44 reply_count: 0,
45 repost_count: 0,
46 like_count: 0,
47 quote_count: 0,
48 extra: HashMap::new(),
49 };
50 feed.insert(
51 idx,
52 FeedViewPost {
53 post: placeholder_post,
54 reply: None,
55 reason: None,
56 feed_context: None,
57 extra: HashMap::new(),
58 },
59 );
60 }
61}
62
63pub async fn get_actor_likes(
64 State(state): State<AppState>,
65 headers: axum::http::HeaderMap,
66 Query(params): Query<GetActorLikesParams>,
67) -> Response {
68 let auth_header = headers.get("Authorization").and_then(|h| h.to_str().ok());
69 let auth_user = if let Some(h) = auth_header {
70 if let Some(token) = crate::auth::extract_bearer_token_from_header(Some(h)) {
71 crate::auth::validate_bearer_token(&state.db, &token).await.ok()
72 } else {
73 None
74 }
75 } else {
76 None
77 };
78 let auth_did = auth_user.as_ref().map(|u| u.did.clone());
79 let auth_key_bytes = auth_user.as_ref().and_then(|u| u.key_bytes.clone());
80 let mut query_params = HashMap::new();
81 query_params.insert("actor".to_string(), params.actor.clone());
82 if let Some(limit) = params.limit {
83 query_params.insert("limit".to_string(), limit.to_string());
84 }
85 if let Some(cursor) = ¶ms.cursor {
86 query_params.insert("cursor".to_string(), cursor.clone());
87 }
88 let proxy_result =
89 match proxy_to_appview("app.bsky.feed.getActorLikes", &query_params, auth_did.as_deref().unwrap_or(""), auth_key_bytes.as_deref()).await {
90 Ok(r) => r,
91 Err(e) => return e,
92 };
93 if !proxy_result.status.is_success() {
94 return proxy_result.into_response();
95 }
96 let rev = match extract_repo_rev(&proxy_result.headers) {
97 Some(r) => r,
98 None => return proxy_result.into_response(),
99 };
100 let mut feed_output: FeedOutput = match serde_json::from_slice(&proxy_result.body) {
101 Ok(f) => f,
102 Err(e) => {
103 warn!("Failed to parse actor likes response: {:?}", e);
104 return proxy_result.into_response();
105 }
106 };
107 let requester_did = match &auth_did {
108 Some(d) => d.clone(),
109 None => return (StatusCode::OK, Json(feed_output)).into_response(),
110 };
111 let actor_did = if params.actor.starts_with("did:") {
112 params.actor.clone()
113 } else {
114 let hostname = std::env::var("PDS_HOSTNAME").unwrap_or_else(|_| "localhost".to_string());
115 let suffix = format!(".{}", hostname);
116 let short_handle = if params.actor.ends_with(&suffix) {
117 params.actor.strip_suffix(&suffix).unwrap_or(¶ms.actor)
118 } else {
119 ¶ms.actor
120 };
121 match sqlx::query_scalar!("SELECT did FROM users WHERE handle = $1", short_handle)
122 .fetch_optional(&state.db)
123 .await
124 {
125 Ok(Some(did)) => did,
126 Ok(None) => return (StatusCode::OK, Json(feed_output)).into_response(),
127 Err(e) => {
128 warn!("Database error resolving actor handle: {:?}", e);
129 return proxy_result.into_response();
130 }
131 }
132 };
133 if actor_did != requester_did {
134 return (StatusCode::OK, Json(feed_output)).into_response();
135 }
136 let local_records = match get_records_since_rev(&state, &requester_did, &rev).await {
137 Ok(r) => r,
138 Err(e) => {
139 warn!("Failed to get local records: {}", e);
140 return proxy_result.into_response();
141 }
142 };
143 if local_records.likes.is_empty() {
144 return (StatusCode::OK, Json(feed_output)).into_response();
145 }
146 insert_likes_into_feed(&mut feed_output.feed, &local_records.likes);
147 let lag = get_local_lag(&local_records);
148 format_munged_response(feed_output, lag)
149}