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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
use crate::{Event, EventKind, PreEvent, PublicKey, Tag, UncheckedUrl, Unixtime};

/// NIP-92/94 File Metadata
#[derive(Clone, Debug, Hash, PartialEq)]
pub struct FileMetadata {
    /// The URL this metadata applies to
    pub url: UncheckedUrl,

    /// Mime type (lowercase), see https://developer.mozilla.org/en-US/docs/Web/HTTP/MIME_types/Common_types
    pub m: Option<String>,

    /// SHA-256 hex-encoded hash
    pub x: Option<String>,

    /// original SHA-256 hex-encoded hash prior to transformations
    pub ox: Option<String>,

    /// Size of file in bytes
    pub size: Option<u64>,

    /// Dimensions of the image
    pub dim: Option<(usize, usize)>,

    /// Magnet URI
    pub magnet: Option<UncheckedUrl>,

    /// Torrent infohash
    pub i: Option<String>,

    /// Blurhash
    pub blurhash: Option<String>,

    /// Thumbnail URL
    pub thumb: Option<UncheckedUrl>,

    /// Preview image (same dimensions)
    pub image: Option<UncheckedUrl>,

    /// Summary text
    pub summary: Option<String>,

    /// Alt description
    pub alt: Option<String>,

    /// Fallback URLs
    pub fallback: Vec<UncheckedUrl>,

    /// Service
    pub service: Option<String>,
}

impl FileMetadata {
    /// Create a new empty (except the URL) FileMetadata
    pub fn new(url: UncheckedUrl) -> FileMetadata {
        FileMetadata {
            url,
            m: None,
            x: None,
            ox: None,
            size: None,
            dim: None,
            magnet: None,
            i: None,
            blurhash: None,
            thumb: None,
            image: None,
            summary: None,
            alt: None,
            fallback: vec![],
            service: None,
        }
    }

    /// Create a NIP-94 FileMetadata PreEvent from this FileMetadata
    pub fn to_nip94_preevent(&self, pubkey: PublicKey) -> PreEvent {
        let mut tags = vec![Tag::new(&["url", &self.url.0])];

        if let Some(m) = &self.m {
            tags.push(Tag::new(&["m", m]));
        }

        if let Some(x) = &self.x {
            tags.push(Tag::new(&["x", x]));
        }

        if let Some(ox) = &self.ox {
            tags.push(Tag::new(&["ox", ox]));
        }

        if let Some(size) = self.size {
            tags.push(Tag::new(&["size", &format!("{size}")]));
        }

        if let Some(dim) = self.dim {
            tags.push(Tag::new(&["dim", &format!("{}x{}", dim.0, dim.1)]));
        }

        if let Some(magnet) = &self.magnet {
            tags.push(Tag::new(&["magnet", &magnet.0]));
        }

        if let Some(i) = &self.i {
            tags.push(Tag::new(&["i", i]));
        }

        if let Some(blurhash) = &self.blurhash {
            tags.push(Tag::new(&["blurhash", blurhash]));
        }

        if let Some(thumb) = &self.thumb {
            tags.push(Tag::new(&["thumb", &thumb.0]));
        }

        if let Some(image) = &self.image {
            tags.push(Tag::new(&["image", &image.0]));
        }

        if let Some(summary) = &self.summary {
            tags.push(Tag::new(&["summary", summary]));
        }

        if let Some(alt) = &self.alt {
            tags.push(Tag::new(&["alt", alt]));
        }

        for fallback in &self.fallback {
            tags.push(Tag::new(&["fallback", &fallback.0]));
        }

        if let Some(service) = &self.service {
            tags.push(Tag::new(&["service", service]));
        }

        PreEvent {
            pubkey,
            created_at: Unixtime::now(),
            kind: EventKind::FileMetadata,
            content: "".to_owned(),
            tags,
        }
    }

    /// Turn a kind-1063 (FileMetadata) event into a FileMetadata structure
    pub fn from_nip94_event(event: &Event) -> Option<FileMetadata> {
        if event.kind != EventKind::FileMetadata {
            return None;
        }

        let mut fm = FileMetadata::new(UncheckedUrl("".to_owned()));

        for tag in &event.tags {
            match tag.tagname() {
                "url" => fm.url = UncheckedUrl(tag.value().to_owned()),
                "m" => fm.m = Some(tag.value().to_owned()),
                "x" => fm.x = Some(tag.value().to_owned()),
                "ox" => fm.ox = Some(tag.value().to_owned()),
                "size" => {
                    if let Ok(u) = tag.value().parse::<u64>() {
                        fm.size = Some(u);
                    }
                }
                "dim" => {
                    let parts: Vec<&str> = tag.value().split('x').collect();
                    if parts.len() == 2 {
                        if let Ok(w) = parts[0].parse::<usize>() {
                            if let Ok(h) = parts[1].parse::<usize>() {
                                fm.dim = Some((w, h));
                            }
                        }
                    }
                }
                "magnet" => fm.magnet = Some(UncheckedUrl(tag.value().to_owned())),
                "i" => fm.i = Some(tag.value().to_owned()),
                "blurhash" => fm.blurhash = Some(tag.value().to_owned()),
                "thumb" => fm.thumb = Some(UncheckedUrl(tag.value().to_owned())),
                "image" => fm.image = Some(UncheckedUrl(tag.value().to_owned())),
                "summary" => fm.summary = Some(tag.value().to_owned()),
                "alt" => fm.alt = Some(tag.value().to_owned()),
                "fallback" => fm.fallback.push(UncheckedUrl(tag.value().to_owned())),
                "service" => fm.service = Some(tag.value().to_owned()),
                _ => continue,
            }
        }

        if !fm.url.0.is_empty() {
            Some(fm)
        } else {
            None
        }
    }

    /// Convert into an 'imeta' tag
    pub fn to_imeta_tag(&self) -> Tag {
        let mut tag = Tag::new(&["imeta"]);

        tag.push_value(format!("url {}", self.url));

        if let Some(m) = &self.m {
            tag.push_value(format!("m {}", m));
        }

        if let Some(x) = &self.x {
            tag.push_value(format!("x {}", x));
        }

        if let Some(ox) = &self.ox {
            tag.push_value(format!("ox {}", ox));
        }

        if let Some(size) = &self.size {
            tag.push_value(format!("size {}", size));
        }

        if let Some(dim) = &self.dim {
            tag.push_value(format!("dim {}x{}", dim.0, dim.1));
        }

        if let Some(magnet) = &self.magnet {
            tag.push_value(format!("magnet {}", magnet));
        }

        if let Some(i) = &self.i {
            tag.push_value(format!("i {}", i));
        }

        if let Some(blurhash) = &self.blurhash {
            tag.push_value(format!("blurhash {}", blurhash));
        }

        if let Some(thumb) = &self.thumb {
            tag.push_value(format!("thumb {}", thumb));
        }

        if let Some(image) = &self.image {
            tag.push_value(format!("image {}", image));
        }

        if let Some(summary) = &self.summary {
            tag.push_value(format!("summary {}", summary));
        }

        if let Some(alt) = &self.alt {
            tag.push_value(format!("alt {}", alt));
        }

        for fallback in &self.fallback {
            tag.push_value(format!("fallback {}", fallback));
        }

        if let Some(service) = &self.service {
            tag.push_value(format!("service {}", service));
        }

        tag
    }

    /// Import from an 'imeta' tag
    pub fn from_imeta_tag(tag: &Tag) -> Option<FileMetadata> {
        let mut fm = FileMetadata::new(UncheckedUrl("".to_owned()));

        for i in 0..tag.len() {
            let parts: Vec<&str> = tag.get_index(i).splitn(2, ' ').collect();
            if parts.len() < 2 {
                continue;
            }
            match parts[0] {
                "url" => fm.url = UncheckedUrl(parts[1].to_owned()),
                "m" => fm.m = Some(parts[1].to_owned()),
                "x" => fm.x = Some(parts[1].to_owned()),
                "ox" => fm.ox = Some(parts[1].to_owned()),
                "size" => {
                    if let Ok(u) = parts[1].parse::<u64>() {
                        fm.size = Some(u);
                    }
                }
                "dim" => {
                    let parts: Vec<&str> = parts[1].split('x').collect();
                    if parts.len() == 2 {
                        if let Ok(w) = parts[0].parse::<usize>() {
                            if let Ok(h) = parts[1].parse::<usize>() {
                                fm.dim = Some((w, h));
                            }
                        }
                    }
                }
                "magnet" => fm.magnet = Some(UncheckedUrl(parts[1].to_owned())),
                "i" => fm.i = Some(parts[1].to_owned()),
                "blurhash" => fm.blurhash = Some(parts[1].to_owned()),
                "thumb" => fm.thumb = Some(UncheckedUrl(parts[1].to_owned())),
                "image" => fm.image = Some(UncheckedUrl(parts[1].to_owned())),
                "summary" => fm.summary = Some(parts[1].to_owned()),
                "alt" => fm.alt = Some(parts[1].to_owned()),
                "fallback" => fm.fallback.push(UncheckedUrl(parts[1].to_owned())),
                "service" => fm.service = Some(parts[1].to_owned()),
                _ => continue,
            }
        }

        if !fm.url.0.is_empty() {
            Some(fm)
        } else {
            None
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_nip94_event() {
        let mut fm = FileMetadata::new(UncheckedUrl("https://nostr.build/blahblahblah".to_owned()));
        fm.x = Some("12345".to_owned());
        fm.service = Some("http".to_owned());
        fm.size = Some(10124);
        fm.alt = Some("a crackerjack".to_owned());

        use crate::{PrivateKey, Signer};
        let private_key = PrivateKey::generate();
        let public_key = private_key.public_key();

        let pre_event = fm.to_nip94_preevent(public_key);
        let event = private_key.sign_event(pre_event).unwrap();
        let fm2 = FileMetadata::from_nip94_event(&event).unwrap();

        assert_eq!(fm, fm2);
    }

    #[test]
    fn test_imeta_tag() {
        let mut fm = FileMetadata::new(UncheckedUrl("https://nostr.build/blahblahblah".to_owned()));
        fm.x = Some("12345".to_owned());
        fm.service = Some("http".to_owned());
        fm.size = Some(10124);
        fm.alt = Some("a crackerjack".to_owned());

        let tag = fm.to_imeta_tag();
        let fm2 = FileMetadata::from_imeta_tag(&tag).unwrap();
        assert_eq!(fm, fm2);
    }
}