lemmy_api_common 0.19.20

A link aggregator for the fediverse
Documentation
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
use crate::{
  context::LemmyContext,
  lemmy_db_schema::traits::Crud,
  post::{LinkMetadata, OpenGraphData},
  send_activity::{ActivityChannel, SendActivityData},
  utils::{local_site_opt_to_sensitive, proxy_image_link},
};
use activitypub_federation::config::Data;
use chrono::{DateTime, Utc};
use encoding_rs::{Encoding, UTF_8};
use futures::StreamExt;
use lemmy_db_schema::{
  newtypes::DbUrl,
  source::{
    images::{ImageDetailsForm, LocalImage, LocalImageForm},
    local_site::LocalSite,
    local_user::LocalUser,
    post::{Post, PostUpdateForm},
  },
};
use lemmy_utils::{
  error::{LemmyError, LemmyErrorType, LemmyResult},
  settings::structs::{PictrsImageMode, Settings},
  REQWEST_TIMEOUT,
  VERSION,
};
use mime::{Mime, TEXT_HTML};
use reqwest::{
  header::{CONTENT_TYPE, LOCATION, RANGE},
  redirect::Policy,
  Client,
  ClientBuilder,
  Response,
};
use reqwest_middleware::ClientWithMiddleware;
use serde::{Deserialize, Serialize};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use tokio::net::lookup_host;
use tracing::{info, warn};
use url::{Host, Url};
use urlencoding::encode;
use webpage::HTML;

pub fn client_builder(settings: &Settings) -> ClientBuilder {
  let user_agent = format!("Lemmy/{VERSION}; +{}", settings.get_protocol_and_hostname());

  Client::builder()
    .user_agent(user_agent.clone())
    .timeout(REQWEST_TIMEOUT)
    .connect_timeout(REQWEST_TIMEOUT)
    // Workaround for https://github.com/LemmyNet/lemmy/issues/5742
    .http1_only()
    .redirect(Policy::none())
}

/// Fetches metadata for the given link and optionally generates thumbnail.
#[tracing::instrument(skip_all)]
pub async fn fetch_link_metadata(
  url: &Url,
  context: &LemmyContext,
  recursion: bool,
) -> LemmyResult<LinkMetadata> {
  if url.scheme() != "http" && url.scheme() != "https" {
    return Err(LemmyErrorType::InvalidUrl.into());
  }

  validate_link_ip(url).await?;
  info!("Fetching site metadata for url: {}", url);
  // We only fetch the first MB of data in order to not waste bandwidth especially for large
  // binary files. This high limit is particularly needed for youtube, which includes a lot of
  // javascript code before the opengraph tags. Mastodon also uses a 1 MB limit:
  // https://github.com/mastodon/mastodon/blob/295ad6f19a016b3f16e1201ffcbb1b3ad6b455a2/app/lib/request.rb#L213
  let bytes_to_fetch = 1024 * 1024;
  let response = context
    .client()
    .get(url.as_str())
    // we only need the first chunk of data. Note that we do not check for Accept-Range so the
    // server may ignore this and still respond with the full response
    .header(RANGE, format!("bytes=0-{}", bytes_to_fetch - 1)) /* -1 because inclusive */
    .send()
    .await?;

  // Manually follow one redirect, using internal IP check. Further redirects are ignored.
  let location = response
    .headers()
    .get(LOCATION)
    .and_then(|l| l.to_str().ok());
  if let (Some(location), false) = (location, recursion) {
    let url = location.parse()?;
    return Box::pin(fetch_link_metadata(&url, context, true)).await;
  }

  let mut content_type: Option<Mime> = response
    .headers()
    .get(CONTENT_TYPE)
    .and_then(|h| h.to_str().ok())
    .and_then(|h| h.parse().ok())
    // If we don't get a content_type from the response (e.g. if the server is down),
    // then try to infer the content_type from the file extension.
    .or(mime_guess::from_path(url.path()).first());

  let opengraph_data = {
    let is_html = content_type
      .as_ref()
      .map(|c| {
        // application/xhtml+xml is a subset of HTML
        let application_xhtml: Mime = "application/xhtml+xml".parse::<Mime>().unwrap_or(TEXT_HTML);
        let allowed_mime_types = [TEXT_HTML.essence_str(), application_xhtml.essence_str()];
        allowed_mime_types.contains(&c.essence_str())
      })
      .unwrap_or_default();

    if is_html {
      // Can't use .text() here, because it only checks the content header, not the actual bytes
      // https://github.com/LemmyNet/lemmy/issues/1964
      // So we want to do deep inspection of the actually returned bytes but need to be careful
      // not spend too much time parsing binary data as HTML
      // only take first bytes regardless of how many bytes the server returns
      let html_bytes = collect_bytes_until_limit(response, bytes_to_fetch).await?;
      extract_opengraph_data(&html_bytes, url)
        .map_err(|e| info!("{e}"))
        .unwrap_or_default()
    } else {
      let is_octet_type = content_type
        .as_ref()
        .map(|c| c.subtype() == "octet-stream")
        .unwrap_or_default();

      // Overwrite the content type if its an octet type
      if is_octet_type {
        // Don't need to fetch as much data for this as we do with opengraph
        let octet_bytes = collect_bytes_until_limit(response, 512).await?;
        content_type =
          infer::get(&octet_bytes).map_or(content_type, |t| t.mime_type().parse().ok());
      }

      Default::default()
    }
  };

  Ok(LinkMetadata {
    opengraph_data,
    content_type: content_type.map(|c| c.to_string()),
  })
}

/// Resolve the domain and throw an error if it points to any internal IP.
pub async fn validate_link_ip(url: &Url) -> LemmyResult<()> {
  if cfg!(debug_assertions) {
    return Ok(());
  }
  // Resolve the domain and throw an error if it points to any internal IP,
  // using logic from nightly IpAddr::is_global.

  // TODO: Replace with IpAddr::is_global() once stabilized
  //       https://doc.rust-lang.org/std/net/enum.IpAddr.html#method.is_global
  let mut ip = vec![];
  match url.host().ok_or(LemmyErrorType::UrlWithoutDomain)? {
    Host::Domain(domain) => ip.extend(
      lookup_host((domain.to_owned(), 80))
        .await?
        .map(|s| s.ip().to_canonical()),
    ),
    Host::Ipv4(ipv4) => ip.push(ipv4.into()),
    Host::Ipv6(ipv6) => ip.push(ipv6.into()),
  };

  let invalid_ip = ip.into_iter().any(|addr| match addr {
    IpAddr::V4(addr) => v4_is_invalid(addr),
    IpAddr::V6(addr) => v6_is_invalid(addr),
  });
  if invalid_ip {
    return Err(LemmyErrorType::InvalidUrl.into());
  }
  Ok(())
}

fn v4_is_invalid(v4: Ipv4Addr) -> bool {
  v4.is_private()
    || v4.is_loopback()
    || v4.is_link_local()
    || v4.is_multicast()
    || v4.is_documentation()
    || v4.is_unspecified()
    || v4.is_broadcast()
}

fn v6_is_invalid(v6: Ipv6Addr) -> bool {
  let is_documentation = matches!(
    v6.segments(),
    [0x2001, 0xdb8, ..] | [0x3fff, 0..=0x0fff, ..]
  );
  is_documentation
    || v6.is_loopback()
    || v6.is_multicast()
        || (v6.segments()[0] & 0xfe00) == 0xfc00 // is_unique_local
        || (v6.segments()[0] & 0xffc0) == 0xfe80 // is_unicast_link_local
    || v6.is_unspecified()
    || v6.to_ipv4_mapped().is_some_and(v4_is_invalid)
}

async fn collect_bytes_until_limit(
  response: Response,
  requested_bytes: usize,
) -> Result<Vec<u8>, LemmyError> {
  let mut stream = response.bytes_stream();
  let mut bytes = Vec::with_capacity(requested_bytes);
  while let Some(chunk) = stream.next().await {
    let chunk = chunk.map_err(LemmyError::from)?;
    // we may go over the requested size here but the important part is we don't keep aggregating
    // more chunks than needed
    bytes.extend_from_slice(&chunk);
    if bytes.len() >= requested_bytes {
      bytes.truncate(requested_bytes);
      break;
    }
  }
  Ok(bytes)
}

/// Generates and saves a post thumbnail and metadata.
///
/// Takes a callback to generate a send activity task, so that post can be federated with metadata.
///
/// TODO: `federated_thumbnail` param can be removed once we federate full metadata and can
///       write it to db directly, without calling this function.
///       https://github.com/LemmyNet/lemmy/issues/4598
pub async fn generate_post_link_metadata(
  post: Post,
  custom_thumbnail: Option<Url>,
  send_activity: impl FnOnce(Post) -> Option<SendActivityData> + Send + 'static,
  local_site: Option<LocalSite>,
  context: Data<LemmyContext>,
) -> LemmyResult<()> {
  let metadata = match &post.url {
    Some(url) => fetch_link_metadata(url, &context, false)
      .await
      .unwrap_or_default(),
    _ => Default::default(),
  };

  let is_image_post = metadata
    .content_type
    .as_ref()
    .is_some_and(|content_type| content_type.starts_with("image"));

  // Decide if we are allowed to generate local thumbnail
  let allow_sensitive = local_site_opt_to_sensitive(&local_site);
  let allow_generate_thumbnail = allow_sensitive || !post.nsfw;

  // Proxy the post url itself if it is an image
  let url = if let (true, Some(url)) = (is_image_post, post.url.clone()) {
    Some(Some(proxy_image_link(url.into(), &context).await?))
  } else {
    None
  };

  let image_url = if is_image_post {
    post.url
  } else {
    metadata.opengraph_data.image.clone()
  };

  // Attempt to generate a thumbnail depending on the instance settings. Either by proxying,
  // storing image persistently in pict-rs or returning the remote url directly as thumbnail.
  let thumbnail_url = if let (false, Some(url)) = (is_image_post, custom_thumbnail) {
    proxy_image_link(url.clone(), &context)
      .await
      .map_err(|e| warn!("Failed to proxy thumbnail: {e}"))
      .ok()
      .or(Some(url.into()))
  } else if let (true, Some(url)) = (allow_generate_thumbnail, image_url.clone()) {
    generate_pictrs_thumbnail(&url, &context)
      .await
      .map_err(|e| warn!("Failed to generate thumbnail: {e}"))
      .ok()
      .map(Into::into)
      .or(image_url)
  } else {
    image_url.clone()
  };

  let form = PostUpdateForm {
    url,
    embed_title: Some(metadata.opengraph_data.title),
    embed_description: Some(metadata.opengraph_data.description),
    embed_video_url: Some(metadata.opengraph_data.embed_video_url),
    thumbnail_url: Some(thumbnail_url),
    url_content_type: Some(metadata.content_type),
    ..Default::default()
  };
  let updated_post = Post::update(&mut context.pool(), post.id, &form).await?;
  if let Some(send_activity) = send_activity(updated_post) {
    ActivityChannel::submit_activity(send_activity, &context).await?;
  }
  Ok(())
}

/// Extract site metadata from HTML Opengraph attributes.
fn extract_opengraph_data(html_bytes: &[u8], url: &Url) -> LemmyResult<OpenGraphData> {
  let html = String::from_utf8_lossy(html_bytes);

  let mut page = HTML::from_string(html.to_string(), None)?;

  // If the web page specifies that it isn't actually UTF-8, re-decode the received bytes with the
  // proper encoding. If the specified encoding cannot be found, fall back to the original UTF-8
  // version.
  if let Some(charset) = page.meta.get("charset") {
    if charset != UTF_8.name() {
      if let Some(encoding) = Encoding::for_label(charset.as_bytes()) {
        page = HTML::from_string(encoding.decode(html_bytes).0.into(), None)?;
      }
    }
  }

  let page_title = page.title;
  let page_description = page.description;

  let og_description = page
    .opengraph
    .properties
    .get("description")
    .map(std::string::ToString::to_string);
  let og_title = page
    .opengraph
    .properties
    .get("title")
    .map(std::string::ToString::to_string);
  let og_image = page
    .opengraph
    .images
    .first()
    // join also works if the target URL is absolute
    .and_then(|ogo| url.join(&ogo.url).ok());
  let og_embed_url = page
    .opengraph
    .videos
    .first()
    // join also works if the target URL is absolute
    .and_then(|v| url.join(&v.url).ok());

  Ok(OpenGraphData {
    title: og_title.or(page_title),
    description: og_description.or(page_description),
    image: og_image.map(Into::into),
    embed_video_url: og_embed_url.map(Into::into),
  })
}

#[derive(Deserialize, Serialize, Debug)]
pub struct PictrsResponse {
  pub files: Option<Vec<PictrsFile>>,
  pub msg: String,
}

#[derive(Deserialize, Serialize, Debug)]
pub struct PictrsFile {
  pub file: String,
  pub delete_token: String,
  pub details: PictrsFileDetails,
}

impl PictrsFile {
  pub fn thumbnail_url(&self, protocol_and_hostname: &str) -> Result<Url, url::ParseError> {
    Url::parse(&format!(
      "{protocol_and_hostname}/pictrs/image/{}",
      self.file
    ))
  }
}

/// Stores extra details about a Pictrs image.
#[derive(Deserialize, Serialize, Debug)]
pub struct PictrsFileDetails {
  /// In pixels
  pub width: u16,
  /// In pixels
  pub height: u16,
  pub content_type: String,
  pub created_at: DateTime<Utc>,
}

impl PictrsFileDetails {
  /// Builds the image form. This should always use the thumbnail_url,
  /// Because the post_view joins to it
  pub fn build_image_details_form(&self, thumbnail_url: &Url) -> ImageDetailsForm {
    ImageDetailsForm {
      link: thumbnail_url.clone().into(),
      width: self.width.into(),
      height: self.height.into(),
      content_type: self.content_type.clone(),
    }
  }
}

#[derive(Deserialize, Serialize, Debug)]
struct PictrsPurgeResponse {
  msg: String,
}

/// Purges an image from pictrs
/// Note: This should often be coerced from a Result to .ok() in order to fail softly, because:
/// - It might fail due to image being not local
/// - It might not be an image
/// - Pictrs might not be set up
pub async fn purge_image_from_pictrs(image_url: &Url, context: &LemmyContext) -> LemmyResult<()> {
  validate_link_ip(image_url).await?;
  is_image_content_type(context.client(), image_url).await?;

  let alias = image_url
    .path_segments()
    .ok_or(LemmyErrorType::ImageUrlMissingPathSegments)?
    .next_back()
    .ok_or(LemmyErrorType::ImageUrlMissingLastPathSegment)?;

  let pictrs_config = context.settings().pictrs_config()?;
  let purge_url = format!("{}internal/purge?alias={}", pictrs_config.url, alias);

  let pictrs_api_key = pictrs_config
    .api_key
    .ok_or(LemmyErrorType::PictrsApiKeyNotProvided)?;
  let response = context
    .client()
    .post(&purge_url)
    .timeout(REQWEST_TIMEOUT)
    .header("x-api-token", pictrs_api_key)
    .send()
    .await?;

  let response: PictrsPurgeResponse = response.json().await.map_err(LemmyError::from)?;

  match response.msg.as_str() {
    "ok" => Ok(()),
    _ => Err(LemmyErrorType::PictrsPurgeResponseError(response.msg))?,
  }
}

pub async fn delete_image_from_pictrs(
  alias: &str,
  delete_token: &str,
  context: &LemmyContext,
) -> LemmyResult<()> {
  let pictrs_config = context.settings().pictrs_config()?;
  let url = format!(
    "{}image/delete/{}/{}",
    pictrs_config.url, &delete_token, &alias
  );
  context
    .client()
    .delete(&url)
    .timeout(REQWEST_TIMEOUT)
    .send()
    .await
    .map_err(LemmyError::from)?;
  Ok(())
}

/// Retrieves the image with local pict-rs and generates a thumbnail. Returns the thumbnail url.
#[tracing::instrument(skip_all)]
async fn generate_pictrs_thumbnail(image_url: &Url, context: &LemmyContext) -> LemmyResult<Url> {
  validate_link_ip(image_url).await?;
  let pictrs_config = context.settings().pictrs_config()?;

  match pictrs_config.image_mode() {
    PictrsImageMode::None => return Ok(image_url.clone()),
    PictrsImageMode::ProxyAllImages => {
      return Ok(proxy_image_link(image_url.clone(), context).await?.into())
    }
    _ => {}
  };

  // fetch remote non-pictrs images for persistent thumbnail link
  // TODO: should limit size once supported by pictrs
  let fetch_url = format!(
    "{}image/download?url={}&resize={}",
    pictrs_config.url,
    encode(image_url.as_str()),
    context.settings().pictrs_config()?.max_thumbnail_size
  );

  let res = context
    .client()
    .get(&fetch_url)
    .timeout(REQWEST_TIMEOUT)
    .send()
    .await?
    .json::<PictrsResponse>()
    .await?;

  let files = res.files.unwrap_or_default();

  let image = files
    .first()
    .ok_or(LemmyErrorType::PictrsResponseError(res.msg))?;

  let form = LocalImageForm {
    // This is none because its an internal request.
    // IE, a local user shouldn't get to delete the thumbnails for their link posts
    local_user_id: None,
    pictrs_alias: image.file.clone(),
    pictrs_delete_token: image.delete_token.clone(),
  };
  let protocol_and_hostname = context.settings().get_protocol_and_hostname();
  let thumbnail_url = image.thumbnail_url(&protocol_and_hostname)?;

  // Also store the details for the image
  let details_form = image.details.build_image_details_form(&thumbnail_url);
  LocalImage::create(&mut context.pool(), &form, &details_form).await?;

  Ok(thumbnail_url)
}

/// Fetches the image details for pictrs proxied images
///
/// We don't need to check for image mode, as that's already been done
#[tracing::instrument(skip_all)]
pub async fn fetch_pictrs_proxied_image_details(
  image_url: &Url,
  context: &LemmyContext,
) -> LemmyResult<PictrsFileDetails> {
  validate_link_ip(image_url).await?;
  let pictrs_url = context.settings().pictrs_config()?.url;
  let encoded_image_url = encode(image_url.as_str());

  // Pictrs needs you to fetch the proxied image before you can fetch the details
  let proxy_url = format!("{pictrs_url}image/original?proxy={encoded_image_url}");

  let res = context
    .client()
    .get(&proxy_url)
    .timeout(REQWEST_TIMEOUT)
    .send()
    .await?
    .status();
  if !res.is_success() {
    Err(LemmyErrorType::NotAnImageType)?
  }

  let details_url = format!("{pictrs_url}image/details/original?proxy={encoded_image_url}");

  let res = context
    .client()
    .get(&details_url)
    .timeout(REQWEST_TIMEOUT)
    .send()
    .await?
    .json()
    .await?;

  Ok(res)
}

// TODO: get rid of this by reading content type from db
#[tracing::instrument(skip_all)]
async fn is_image_content_type(client: &ClientWithMiddleware, url: &Url) -> LemmyResult<()> {
  let response = client.get(url.as_str()).send().await?;
  if response
    .headers()
    .get("Content-Type")
    .ok_or(LemmyErrorType::NoContentTypeHeader)?
    .to_str()?
    .starts_with("image/")
  {
    Ok(())
  } else {
    Err(LemmyErrorType::NotAnImageType)?
  }
}

// Ignores errors because images may have been stored externally.
async fn delete_old_image(
  context: &Data<LemmyContext>,
  local_user: &LocalUser,
  image_url: &DbUrl,
) -> LemmyResult<()> {
  let image = LocalImage::delete_by_url_and_user(&mut context.pool(), local_user, image_url)
    .await
    .ok();
  if let Some(image) = image {
    delete_image_from_pictrs(&image.pictrs_alias, &image.pictrs_delete_token, context).await?
  }
  Ok(())
}

/// When adding a new avatar, banner or similar image, delete the old one.
pub async fn replace_image(
  new_image: &Option<Option<DbUrl>>,
  old_image: &Option<DbUrl>,
  context: &Data<LemmyContext>,
  local_user: &LocalUser,
) -> LemmyResult<()> {
  if let Some(old_image) = old_image {
    if *new_image == Some(None) {
      delete_old_image(context, local_user, old_image).await?;
    } else if let Some(Some(new_image)) = new_image {
      // Note: Oftentimes front ends will include the current image in the form.
      // In this case, deleting `old_image` would also be deletion of `new_image`,
      // so the deletion must be skipped for the image to be kept.
      if new_image != old_image {
        delete_old_image(context, local_user, old_image).await?;
      }
    }
  }
  Ok(())
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
#[allow(clippy::indexing_slicing)]
mod tests {

  use crate::{
    context::LemmyContext,
    request::{extract_opengraph_data, fetch_link_metadata},
  };
  use pretty_assertions::assert_eq;
  use serial_test::serial;
  use url::Url;

  // These helped with testing
  #[tokio::test]
  #[serial]
  async fn test_link_metadata() {
    let context = LemmyContext::init_test_context().await;
    let sample_url = Url::parse("https://gitlab.com/IzzyOnDroid/repo/-/wikis/FAQ").unwrap();
    let sample_res = fetch_link_metadata(&sample_url, &context, false)
      .await
      .unwrap();
    assert_eq!(
      Some("FAQ · Wiki · IzzyOnDroid / repo · GitLab".to_string()),
      sample_res.opengraph_data.title
    );
    assert_eq!(
      Some("The F-Droid compatible repo at https://apt.izzysoft.de/fdroid/".to_string()),
      sample_res.opengraph_data.description
    );
    assert_eq!(
      Some(
        Url::parse("https://gitlab.com/uploads/-/system/project/avatar/4877469/iod_logo.png")
          .unwrap()
          .into()
      ),
      sample_res.opengraph_data.image
    );
    assert_eq!(None, sample_res.opengraph_data.embed_video_url);
    assert_eq!(
      Some(mime::TEXT_HTML_UTF_8.to_string()),
      sample_res.content_type
    );
  }

  #[test]
  fn test_resolve_image_url() {
    // url that lists the opengraph fields
    let url = Url::parse("https://example.com/one/two.html").unwrap();

    // root relative url
    let html_bytes = b"<!DOCTYPE html><html><head><meta property='og:image' content='/image.jpg'></head><body></body></html>";
    let metadata = extract_opengraph_data(html_bytes, &url).expect("Unable to parse metadata");
    assert_eq!(
      metadata.image,
      Some(Url::parse("https://example.com/image.jpg").unwrap().into())
    );

    // base relative url
    let html_bytes = b"<!DOCTYPE html><html><head><meta property='og:image' content='image.jpg'></head><body></body></html>";
    let metadata = extract_opengraph_data(html_bytes, &url).expect("Unable to parse metadata");
    assert_eq!(
      metadata.image,
      Some(
        Url::parse("https://example.com/one/image.jpg")
          .unwrap()
          .into()
      )
    );

    // absolute url
    let html_bytes = b"<!DOCTYPE html><html><head><meta property='og:image' content='https://cdn.host.com/image.jpg'></head><body></body></html>";
    let metadata = extract_opengraph_data(html_bytes, &url).expect("Unable to parse metadata");
    assert_eq!(
      metadata.image,
      Some(Url::parse("https://cdn.host.com/image.jpg").unwrap().into())
    );

    // protocol relative url
    let html_bytes = b"<!DOCTYPE html><html><head><meta property='og:image' content='//example.com/image.jpg'></head><body></body></html>";
    let metadata = extract_opengraph_data(html_bytes, &url).expect("Unable to parse metadata");
    assert_eq!(
      metadata.image,
      Some(Url::parse("https://example.com/image.jpg").unwrap().into())
    );
  }
}