linkspace/commons/
username.rs

1use crate::prelude::*;
2use crate::query::LkQuery;
3use linkspace_core::thread_local::with_id;
4
5fn default_id(key: &PubKey) -> String {
6    format!("b:{}", key.b64())
7}
8
9fn first_line(bytes: &[u8]) -> &[u8] {
10    bytes
11        .split_once(|b| *b == b'\n')
12        .map(|o| o.0)
13        .unwrap_or(bytes)
14}
15
16/// Self signed username.
17/// If present it returns username:... with a UTF8 lossy decoding of the data before the first '\n', or b:PUBKEY if none are known.
18/// If you want more control or more fields use lkc_username_query or query directly
19pub fn lkc_username(key: PubKey) -> LkResult<String> {
20    Ok(
21        system::lks_scan_one_ref(&lkc_username_query(Some(key))?, &mut |p| {
22            format!("username:{}", String::from_utf8_lossy(first_line(p.data())))
23        })?
24        .unwrap_or_else(|| default_id(&key)),
25    )
26}
27pub fn lkc_username_query(key: Option<PubKey>) -> LkResult<LkQuery> {
28    let space = (USERNAME, LkPath::EMPTY).try_as_space(&())?;
29    let mut q = crate::query::lkq_path(&space, key);
30
31    crate::query::lkq_add_mut(
32        &mut q,
33        &[":scan space-desc/:1", ":watch [f:username].[wg]"],
34        &(),
35    )?;
36    Ok(q)
37}
38
39pub static USERNAME: Domain = abf(b"username");
40
41pub fn lkc_username_set(name: &str) -> LkResult<PointBox> {
42    let space = (USERNAME, LkPath::EMPTY).try_as_space(&())?;
43    with_id(|key| {
44        point::lk_keypoint_ref(
45            key,
46            space.domain,
47            space.group,
48            LkPath::EMPTY,
49            name.as_bytes(),
50            &[],
51            now(),
52        )
53        .map(|p| p.as_box().with_xheader(&XFlags::REPLACABLE))
54    })?
55}