open_graph/
lib.rs

1#![forbid(unsafe_code, future_incompatible)]
2#![deny(missing_debug_implementations, bad_style)]
3#![deny(missing_docs)]
4#![cfg_attr(test, deny(warnings))]
5
6//! ## Example
7//!
8//! ```rust
9//! ```
10
11mod object_type;
12pub use crate::object_type::ObjectType;
13
14use failure::{ensure, Error, ResultExt};
15use url::Url;
16
17/// OpenGraph Object
18pub trait Object {
19  /// Convert the Object to a string.
20  fn build(self) -> String;
21}
22
23/// The canonical URL for your page.
24///
25/// This should be the undecorated URL, without session variables, user
26/// identifying parameters, or counters. Likes and Shares for this URL will
27/// aggregate at this URL. For example, mobile domain URLs should point to the
28/// desktop version of the URL as the canonical URL to aggregate Likes and
29/// Shares across different versions of the page.
30#[inline]
31pub fn create_url<'s>(content: impl Into<&'s str>) -> String {
32  create("og:url", content.into())
33}
34
35/// The title of your article without any branding such as your site name.
36#[inline]
37pub fn create_title<'s>(content: impl Into<&'s str>) -> String {
38  create("og:title", content.into())
39}
40
41/// A brief description of the content, usually between 2 and 4 sentences.
42#[inline]
43pub fn create_description<'s>(content: impl Into<&'s str>) -> String {
44  create("og:description", content.into())
45}
46
47/// The URL of the image that appears when someone shares the content.
48#[inline]
49pub fn create_image<'s>(content: impl Into<&'s str>) -> Result<String, Error> {
50  let url = Url::parse(content.into()).context("String must be a valid URL")?;
51  Ok(create("og:image", url.as_str()))
52}
53
54/// Equivalent to `og:image`.
55#[inline]
56pub fn create_image_url<'s>(
57  content: impl Into<&'s str>,
58) -> Result<String, Error> {
59  let url = Url::parse(content.into()).context("String must be a valid URL")?;
60  Ok(create("og:image:url", url.as_str()))
61}
62
63/// https:// URL for the image.
64#[inline]
65pub fn create_secure_image_url<'s>(
66  content: impl Into<&'s str>,
67) -> Result<String, Error> {
68  let url = Url::parse(content.into()).context("String must be a valid URL")?;
69  ensure!(
70    url.scheme() == "https",
71    "URL must start with https://. Use `.image_url()` instead."
72  );
73  Ok(create("og:image:secure_url", url.as_str()))
74}
75
76/// MIME type of the image. One of image/jpeg, image/gif or image/png
77#[inline]
78pub fn create_image_type<'s>(
79  content: impl Into<&'s str>,
80) -> Result<String, Error> {
81  let url = Url::parse(content.into()).context("String must be a valid URL")?;
82  Ok(create("og:image:url", url.as_str()))
83}
84
85/// Create an HTML Open Graph tag
86#[inline]
87fn create(name: &str, content: &str) -> String {
88  format!(r#"<meta property="{}" content="{}" />"#, name, content)
89}