-
Notifications
You must be signed in to change notification settings - Fork 4.5k
Expand file tree
/
Copy pathchannels.rs
More file actions
183 lines (159 loc) · 5.35 KB
/
Copy pathchannels.rs
File metadata and controls
183 lines (159 loc) · 5.35 KB
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
//! Channel REST API.
//!
//! Endpoints:
//! GET /api/channels — list accessible channels for the authenticated user
//! POST /api/channels — create a new channel for the authenticated user
use std::collections::HashMap;
use std::sync::Arc;
use axum::{
extract::Json as ExtractJson,
extract::State,
http::{HeaderMap, StatusCode},
response::Json,
};
use nostr::util::hex as nostr_hex;
use serde::Deserialize;
use sprout_db::channel::{ChannelRecord, ChannelType, ChannelVisibility};
use crate::state::AppState;
use super::{api_error, extract_auth_pubkey, internal_error};
/// Returns all channels accessible to the authenticated user.
///
/// For DM channels, resolves participant display names and pubkeys.
pub async fn channels_handler(
State(state): State<Arc<AppState>>,
headers: HeaderMap,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
let (_pubkey, pubkey_bytes) = extract_auth_pubkey(&headers, &state).await?;
let channels = state
.db
.get_accessible_channels(&pubkey_bytes)
.await
.map_err(|e| internal_error(&format!("db error: {e}")))?;
let mut result = Vec::with_capacity(channels.len());
for ch in &channels {
let (participants, participant_pubkeys) = if ch.channel_type == "dm" {
resolve_dm_participants(&state, ch.id).await
} else {
(vec![], vec![])
};
result.push(channel_record_to_json(
ch,
participants,
participant_pubkeys,
));
}
Ok(Json(serde_json::json!(result)))
}
/// Request body for creating a new channel.
#[derive(Debug, Deserialize)]
pub struct CreateChannelBody {
/// Human-readable channel name.
pub name: String,
/// Requested channel type (`stream` or `forum`).
pub channel_type: String,
/// Channel visibility (`open` or `private`).
pub visibility: String,
/// Optional channel description.
pub description: Option<String>,
}
/// Creates a new stream or forum channel for the authenticated user.
pub async fn create_channel(
State(state): State<Arc<AppState>>,
headers: HeaderMap,
ExtractJson(body): ExtractJson<CreateChannelBody>,
) -> Result<(StatusCode, Json<serde_json::Value>), (StatusCode, Json<serde_json::Value>)> {
let (_pubkey, pubkey_bytes) = extract_auth_pubkey(&headers, &state).await?;
let name = body.name.trim();
if name.is_empty() {
return Err(api_error(
StatusCode::BAD_REQUEST,
"channel name is required",
));
}
let channel_type = match body.channel_type.as_str() {
"stream" => ChannelType::Stream,
"forum" => ChannelType::Forum,
_ => {
return Err(api_error(
StatusCode::BAD_REQUEST,
"channel_type must be 'stream' or 'forum'",
))
}
};
let visibility = match body.visibility.as_str() {
"open" => ChannelVisibility::Open,
"private" => ChannelVisibility::Private,
_ => {
return Err(api_error(
StatusCode::BAD_REQUEST,
"visibility must be 'open' or 'private'",
))
}
};
let description = body
.description
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty());
let channel = state
.db
.create_channel(name, channel_type, visibility, description, &pubkey_bytes)
.await
.map_err(|e| internal_error(&format!("db error: {e}")))?;
Ok((
StatusCode::CREATED,
Json(channel_record_to_json(&channel, vec![], vec![])),
))
}
fn channel_record_to_json(
channel: &ChannelRecord,
participants: Vec<String>,
participant_pubkeys: Vec<String>,
) -> serde_json::Value {
serde_json::json!({
"id": channel.id.to_string(),
"name": &channel.name,
"channel_type": &channel.channel_type,
"description": channel.description.clone().unwrap_or_default(),
"participants": participants,
"participant_pubkeys": participant_pubkeys,
})
}
/// Fetch DM participants and resolve their display names.
async fn resolve_dm_participants(
state: &AppState,
channel_id: uuid::Uuid,
) -> (Vec<String>, Vec<String>) {
let members = state.db.get_members(channel_id).await.unwrap_or_else(|e| {
tracing::error!("channels: failed to load members for channel {channel_id}: {e}");
vec![]
});
let member_pubkeys: Vec<Vec<u8>> = members.iter().map(|m| m.pubkey.clone()).collect();
let user_records = state
.db
.get_users_bulk(&member_pubkeys)
.await
.unwrap_or_else(|e| {
tracing::error!("channels: failed to load user records for DM participants: {e}");
vec![]
});
let user_map: HashMap<String, String> = user_records
.into_iter()
.filter_map(|u| {
let hex = nostr_hex::encode(&u.pubkey);
u.display_name.map(|name| (hex, name))
})
.collect();
let mut names = Vec::new();
let mut pk_hexes = Vec::new();
for m in &members {
let hex = nostr_hex::encode(&m.pubkey);
let name = user_map
.get(&hex)
.cloned()
.unwrap_or_else(|| hex[..8.min(hex.len())].to_string());
names.push(name);
pk_hexes.push(hex);
}
(names, pk_hexes)
}