Skip to main content

lanzou_share/
notes.rs

1//! Unified JSON file notes stored in Lanzou descriptions (schema v1 only).
2//!
3//! ```json
4//! {"v":1,"kind":"raw","name":"a.txt","as":"a.txt","size":12}
5//! {"v":1,"kind":"convert","name":"a.dex","as":"a.dex.zip","mode":"zip","suffix":"zip","size":20}
6//! {"v":2,"kind":"part","id":"...","name":"big.bin","as":"big_s001.zip","index":1,"total":3,"size":1048576,
7//!  "nextId":"123","nextUrl":"https://.../xxx","npwd":"ab12"}
8//!
9//! Part chain: v1 `next` is always a file id; v2 uses `nextId` + `nextUrl` (+ `npwd`).
10//! Never treat v1 `next` as a URL.
11//! ```
12
13use serde::{Deserialize, Serialize};
14
15/// Note schema version.
16pub const NOTE_VERSION: u32 = 2;
17
18/// Unified note schema written to file descriptions.
19#[derive(Debug, Clone, Default, Serialize, Deserialize)]
20pub struct FileNote {
21    #[serde(default = "default_v")]
22    pub v: u32,
23    pub kind: String, // raw | convert | part
24    #[serde(default, skip_serializing_if = "String::is_empty")]
25    pub name: String,
26    #[serde(default, skip_serializing_if = "String::is_empty", rename = "as")]
27    pub as_name: String,
28    #[serde(default, skip_serializing_if = "String::is_empty")]
29    pub mode: String,
30    #[serde(default, skip_serializing_if = "String::is_empty")]
31    pub suffix: String,
32    #[serde(default, skip_serializing_if = "String::is_empty")]
33    pub id: String,
34    #[serde(default, skip_serializing_if = "is_zero_usize")]
35    pub index: usize,
36    #[serde(default, skip_serializing_if = "is_zero_usize")]
37    pub total: usize,
38    #[serde(default, skip_serializing_if = "is_zero_u64")]
39    pub size: u64,
40    /// v1 only: next part remote file id.
41    #[serde(default, skip_serializing_if = "String::is_empty")]
42    pub next: String,
43    /// v2: next part file id.
44    #[serde(default, skip_serializing_if = "String::is_empty", rename = "nextId")]
45    pub next_id: String,
46    /// v2: next part share URL.
47    #[serde(default, skip_serializing_if = "String::is_empty", rename = "nextUrl")]
48    pub next_url: String,
49    /// Password for next_url (kind=part).
50    #[serde(default, skip_serializing_if = "String::is_empty")]
51    pub npwd: String,
52}
53
54fn default_v() -> u32 {
55    NOTE_VERSION
56}
57fn is_zero_usize(n: &usize) -> bool {
58    *n == 0
59}
60fn is_zero_u64(n: &u64) -> bool {
61    *n == 0
62}
63
64/// JSON note for an upload that did not convert the suffix.
65pub fn format_raw_note(orig_name: &str, upload_name: &str, size: u64) -> String {
66    let as_name = if upload_name.is_empty() {
67        orig_name
68    } else {
69        upload_name
70    };
71    serde_json::to_string(&FileNote {
72        v: NOTE_VERSION,
73        kind: "raw".into(),
74        name: orig_name.into(),
75        as_name: as_name.into(),
76        size,
77        ..Default::default()
78    })
79    .unwrap_or_default()
80}
81
82/// JSON convert note.
83pub fn format_convert_note(
84    orig_name: &str,
85    upload_name: &str,
86    mode: &str,
87    suffix: &str,
88    size: u64,
89) -> String {
90    serde_json::to_string(&FileNote {
91        v: NOTE_VERSION,
92        kind: "convert".into(),
93        name: orig_name.into(),
94        as_name: upload_name.into(),
95        mode: mode.into(),
96        suffix: suffix.into(),
97        size,
98        ..Default::default()
99    })
100    .unwrap_or_default()
101}
102
103/// JSON part note.
104pub fn format_part_note(
105    group_id: &str,
106    orig_name: &str,
107    upload_name: &str,
108    index: usize,
109    total: usize,
110    size: u64,
111    next_file_id: &str,
112    next_share_url: &str,
113    next_pwd: &str,
114) -> String {
115    serde_json::to_string(&FileNote {
116        v: NOTE_VERSION,
117        kind: "part".into(),
118        id: group_id.into(),
119        name: orig_name.into(),
120        as_name: upload_name.into(),
121        index,
122        total,
123        size,
124        next_id: next_file_id.into(),
125        next_url: next_share_url.into(),
126        npwd: next_pwd.into(),
127        ..Default::default()
128    })
129    .unwrap_or_default()
130}
131
132/// Parsed part metadata.
133#[derive(Debug, Clone, Default)]
134pub struct PartMeta {
135    pub group_id: String,
136    pub name: String,
137    pub as_name: String,
138    pub index: usize,
139    pub total: usize,
140    pub size: u64,
141    pub next_id: String,
142    pub next_url: String,
143    pub npwd: String,
144}
145
146/// Parsed convert/raw metadata.
147#[derive(Debug, Clone, Default)]
148pub struct ConvertMeta {
149    pub name: String,
150    pub as_name: String,
151    pub mode: String,
152    pub suffix: String,
153    pub size: u64,
154    pub raw: bool,
155}
156
157/// Parse a v1 JSON note only (after HTML unescape).
158pub fn parse_file_note(desc: &str) -> Option<FileNote> {
159    let desc = clean_share_desc(desc);
160    if desc.is_empty() {
161        return None;
162    }
163    let i = desc.find('{')?;
164    let j = desc.rfind('}')?;
165    if j <= i {
166        return None;
167    }
168    let mut n: FileNote = serde_json::from_str(&desc[i..=j]).ok()?;
169    match n.kind.as_str() {
170        "raw" | "convert" | "part" => {}
171        _ => return None,
172    }
173    if n.v == 0 {
174        n.v = NOTE_VERSION;
175    }
176    if n.kind == "part" {
177        n = normalize_part_note(n);
178    }
179    Some(n)
180}
181
182pub fn strip_html_tags(s: &str) -> String {
183    let mut out = String::with_capacity(s.len());
184    let mut in_tag = false;
185    for c in s.chars() {
186        if c == '<' {
187            in_tag = true;
188            continue;
189        }
190        if in_tag {
191            if c == '>' {
192                in_tag = false;
193            }
194            continue;
195        }
196        out.push(c);
197    }
198    out
199}
200
201pub fn clean_share_desc(s: &str) -> String {
202    html_unescape(&strip_html_tags(s.trim()))
203}
204
205fn html_unescape(s: &str) -> String {
206
207
208    if !s.contains('&') {
209        return s.to_string();
210    }
211    s.replace("&quot;", "\"")
212        .replace("&#34;", "\"")
213        .replace("&apos;", "'")
214        .replace("&#39;", "'")
215        .replace("&lt;", "<")
216        .replace("&gt;", ">")
217        .replace("&amp;", "&")
218}
219
220
221/// v1 "next" is always a file id → next_id. Never map next → next_url.
222fn normalize_part_note(mut n: FileNote) -> FileNote {
223    if n.next_id.is_empty() && !n.next.is_empty() {
224        n.next_id = n.next.clone();
225    }
226    n
227}
228
229pub fn parse_part_note(desc: &str) -> Option<PartMeta> {
230    let n = parse_file_note(desc)?;
231    if n.kind != "part" || n.id.is_empty() || n.total < 1 || n.index < 1 {
232        return None;
233    }
234    Some(PartMeta {
235        group_id: n.id,
236        name: n.name,
237        as_name: n.as_name,
238        index: n.index,
239        total: n.total,
240        size: n.size,
241        next_id: n.next_id,
242        next_url: n.next_url,
243        npwd: n.npwd,
244    })
245}
246
247/// Convert or raw notes (raw treated as same-name convert for resolution).
248pub fn parse_convert_note(desc: &str) -> Option<ConvertMeta> {
249    let n = parse_file_note(desc)?;
250    match n.kind.as_str() {
251        "convert" => {
252            if n.name.is_empty() {
253                return None;
254            }
255            Some(ConvertMeta {
256                name: n.name,
257                as_name: n.as_name,
258                mode: n.mode,
259                suffix: n.suffix,
260                size: n.size,
261                raw: false,
262            })
263        }
264        "raw" => {
265            if n.name.is_empty() {
266                return None;
267            }
268            let as_name = if n.as_name.is_empty() {
269                n.name.clone()
270            } else {
271                n.as_name
272            };
273            Some(ConvertMeta {
274                name: n.name,
275                as_name,
276                size: n.size,
277                raw: true,
278                ..Default::default()
279            })
280        }
281        _ => None,
282    }
283}
284
285
286/// Pull the "文件描述" field from a share page HTML (often entity-encoded JSON).
287pub fn extract_share_description(html: &str) -> String {
288    if html.is_empty() {
289        return String::new();
290    }
291    const LABEL: &str = "文件描述";
292    if let Some(i) = html.find(LABEL) {
293        let mut rest = &html[i + LABEL.len()..];
294        rest = rest.trim_start_matches([':', ':', ' ', '\t', '\r', '\n']);
295        loop {
296            rest = rest.trim_start();
297            if rest.starts_with('<') {
298                if let Some(j) = rest.find('>') {
299                    rest = &rest[j + 1..];
300                    continue;
301                }
302            }
303            break;
304        }
305        if let Some(k) = rest.find('{') {
306            let mut depth = 0i32;
307            for (p, ch) in rest[k..].char_indices() {
308                match ch {
309                    '{' => depth += 1,
310                    '}' => {
311                        depth -= 1;
312                        if depth == 0 {
313                            return rest[k..=k + p].trim().to_string();
314                        }
315                    }
316                    _ => {}
317                }
318            }
319        }
320        for sep in ["</td>", "<td", "<div"] {
321            if let Some(j) = rest.find(sep) {
322                let cand = rest[..j]
323                    .replace("<br>", "")
324                    .replace("<br/>", "")
325                    .replace("<br />", "");
326                let cand = cand.trim();
327                if !cand.is_empty() {
328                    return cand.to_string();
329                }
330            }
331        }
332    }
333    for marker in ["\"kind\"", "&quot;kind&quot;", "\"v\":1", "&quot;v&quot;:1"] {
334        if let Some(k) = html.find(marker) {
335            if let Some(start) = html[..k + 1].rfind('{') {
336                let mut depth = 0i32;
337                for (p, ch) in html[start..].char_indices() {
338                    match ch {
339                        '{' => depth += 1,
340                        '}' => {
341                            depth -= 1;
342                            if depth == 0 {
343                                return html[start..=start + p].trim().to_string();
344                            }
345                        }
346                        _ => {}
347                    }
348                }
349            }
350        }
351    }
352    String::new()
353}