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 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
//! Links.
use crate::{media_type, Error, Result};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use url::Url;
/// Child links.
pub const CHILD_REL: &str = "child";
/// Item link.
pub const ITEM_REL: &str = "item";
/// Parent link.
pub const PARENT_REL: &str = "parent";
/// Root link.
pub const ROOT_REL: &str = "root";
/// Self link.
pub const SELF_REL: &str = "self";
/// Collection link.
pub const COLLECTION_REL: &str = "collection";
/// This object describes a relationship with another entity.
///
/// Data providers are advised to be liberal with the links section, to describe
/// things like the [Catalog](crate::Catalog) an [Item](crate::Item) is in,
/// related `Item`s, parent or child `Item`s (modeled in different ways, like an
/// 'acquisition' or derived data). It is allowed to add additional fields such
/// as a title and type.
///
/// This link structure includes a few fields from the [STAC API
/// specification](https://github.com/radiantearth/stac-api-spec/tree/main/item-search#pagination).
/// Generally we keep STAC API structures in the [stac-api
/// crate](https://github.com/gadomski/stac-rs/stac-api), but in this case it
/// was simpler to include these attributes in the base [Link] rather to create a new one.
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct Link {
/// The actual link in the format of an URL.
///
/// Relative and absolute links are both allowed.
pub href: String,
/// Relationship between the current document and the linked document.
///
/// See the chapter on ["Relation
/// types"](https://github.com/radiantearth/stac-spec/blob/master/item-spec/item-spec.md#relation-types)
/// in the STAC spec for more information.
pub rel: String,
/// [Media type](crate::media_type) of the referenced entity.
#[serde(rename = "type")]
#[serde(skip_serializing_if = "Option::is_none")]
pub r#type: Option<String>,
/// A human readable title to be used in rendered displays of the link.
#[serde(skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
/// The HTTP method of the request, usually GET or POST. Defaults to GET.
///
/// From the STAC API spec.
#[serde(skip_serializing_if = "Option::is_none")]
pub method: Option<String>,
/// A dictionary of header values that must be included in the next request
///
/// From the STAC API spec.
#[serde(skip_serializing_if = "Option::is_none")]
pub headers: Option<Map<String, Value>>,
/// A JSON object containing fields/values that must be included in the body
/// of the next request.
///
/// From the STAC API spec.
#[serde(skip_serializing_if = "Option::is_none")]
pub body: Option<Map<String, Value>>,
/// If true, the headers/body fields in the next link must be merged into
/// the original request and be sent combined in the next request. Defaults
/// to false
///
/// From the STAC API spec.
#[serde(skip_serializing_if = "Option::is_none")]
pub merge: Option<bool>,
/// Additional fields on the link.
#[serde(flatten)]
pub additional_fields: Map<String, Value>,
}
/// Implemented by any object that has links.
pub trait Links {
/// Returns a reference to this object's links.
///
/// # Examples
///
/// [Value](crate::Value) implements Links:
///
/// ```
/// use stac::Links;
/// let item: stac::Item = stac::read("data/simple-item.json").unwrap();
/// let links = item.links();
/// ```
fn links(&self) -> &[Link];
/// Returns a mutable reference to this object's links.
///
/// # Examples
///
/// [Value](crate::Value) implements Links:
///
/// ```
/// use stac::Links;
/// let mut item: stac::Item = stac::read("data/simple-item.json").unwrap();
/// let links = item.links_mut();
/// links.clear();
/// ```
fn links_mut(&mut self) -> &mut Vec<Link>;
/// Returns the first link with the given rel type.
///
/// # Examples
///
/// ```
/// use stac::Links;
/// let item: stac::Item = stac::read("data/simple-item.json").unwrap();
/// let link = item.link("root").unwrap();
/// ```
fn link(&self, rel: &str) -> Option<&Link> {
self.links().iter().find(|link| link.rel == rel)
}
/// Sets a link of the given rel type.
///
/// This will remove all other links of that rel type, so should only be
/// used for e.g. "root", not e.g. "child".
///
/// # Examples
///
/// ```
/// use stac::{Links, Link};
/// let mut item: stac::Item = stac::read("data/simple-item.json").unwrap();
/// item.set_link(Link::root("a/href"));
/// ```
fn set_link(&mut self, link: Link) {
self.links_mut().retain(|l| l.rel != link.rel);
self.links_mut().push(link)
}
/// Returns this object's root link.
///
/// This is the first link with a rel="root".
///
/// # Examples
///
/// ```
/// use stac::Links;
/// let item: stac::Item = stac::read("data/simple-item.json").unwrap();
/// let link = item.root_link().unwrap();
/// ```
fn root_link(&self) -> Option<&Link> {
self.links().iter().find(|link| link.is_root())
}
/// Returns this object's self link.
///
/// This is the first link with a rel="self".
///
/// # Examples
///
/// ```
/// use stac::Links;
/// let item: stac::Item = stac::read("data/simple-item.json").unwrap();
/// let link = item.root_link().unwrap();
/// ```
fn self_link(&self) -> Option<&Link> {
self.links().iter().find(|link| link.is_self())
}
/// Returns this object's parent link.
///
/// This is the first link with a rel="parent".
///
/// # Examples
///
/// ```
/// use stac::Links;
/// let item: stac::Item = stac::read("data/simple-item.json").unwrap();
/// let link = item.parent_link().unwrap();
/// ```
fn parent_link(&self) -> Option<&Link> {
self.links().iter().find(|link| link.is_parent())
}
/// Returns an iterator over this object's child links.
///
/// # Examples
///
/// ```
/// use stac::Links;
/// let collection: stac::Collection = stac::read("data/collection.json").unwrap();
/// let links: Vec<_> = collection.iter_child_links().collect();
/// ```
fn iter_child_links(&self) -> Box<dyn Iterator<Item = &Link> + '_> {
Box::new(self.links().iter().filter(|link| link.is_child()))
}
/// Returns an iterator over this object's item links.
///
/// # Examples
///
/// ```
/// use stac::Links;
/// let collection: stac::Collection = stac::read("data/collection.json").unwrap();
/// let links: Vec<_> = collection.iter_item_links().collect();
/// ```
fn iter_item_links(&self) -> Box<dyn Iterator<Item = &Link> + '_> {
Box::new(self.links().iter().filter(|link| link.is_item()))
}
/// Makes all relative links absolute with respect to an href.
///
/// # Examples
///
/// ```
/// use stac::{Links, Catalog, Error, Href};
///
/// let mut catalog: stac::Catalog = stac::read("data/catalog.json").unwrap();
/// assert!(!catalog.root_link().unwrap().is_absolute());
/// catalog.make_relative_links_absolute("data/catalog.json").unwrap();
/// assert!(catalog.root_link().unwrap().is_absolute());
/// ```
fn make_relative_links_absolute(&mut self, href: impl ToString) -> Result<()> {
let href = make_absolute(href.to_string(), None)?;
for link in self.links_mut() {
link.href = make_absolute(std::mem::take(&mut link.href), Some(&href))?;
}
Ok(())
}
/// Removes all relative links.
///
/// This can be useful e.g. if you're relocating a STAC object, but it
/// doesn't have a href, so the relative links wouldn't make any sense.
/// Returns all removed links.
///
/// # Examples
///
/// ```
/// use stac::{Catalog, Links, Link};
/// let mut catalog = Catalog::new("an-id", "a description");
/// catalog.links.push(Link::new("./child.json", "child"));
/// catalog.remove_relative_links();
/// assert!(catalog.links.is_empty());
/// ```
fn remove_relative_links(&mut self) -> Vec<Link> {
let mut i = 0;
let mut removed = Vec::new();
// Replace with `drain_filter` when it is stabilized.
while i < self.links().len() {
if !self.links()[i].is_absolute() {
removed.push(self.links_mut().remove(i));
} else {
i += 1;
}
}
removed
}
}
impl Link {
/// Creates a new link with the provided href and rel type.
///
/// # Examples
///
/// ```
/// # use stac::Link;
/// let link = Link::new("an-href", "a-rel");
/// assert_eq!(link.href, "an-href");
/// assert_eq!(link.rel, "a-rel");
/// ```
pub fn new(href: impl ToString, rel: impl ToString) -> Link {
Link {
href: href.to_string(),
rel: rel.to_string(),
r#type: None,
title: None,
method: None,
headers: None,
body: None,
merge: None,
additional_fields: Map::new(),
}
}
/// Sets this link's media type to JSON.
///
/// # Examples
///
/// ```
/// use stac::{Link, media_type};
/// let link = Link::new("a/href", "rel-type").json();
/// assert_eq!(link.r#type.unwrap(), media_type::JSON);
/// ```
pub fn json(mut self) -> Link {
self.r#type = Some(media_type::JSON.to_string());
self
}
/// Returns true if this link's media type is JSON.
///
/// # Examples
///
/// ```
/// use stac::{Link, media_type};
/// let link = Link::new("a/href", "rel-type").json();
/// assert!(link.is_json());
/// ```
pub fn is_json(&self) -> bool {
self.r#type
.as_ref()
.map(|t| t == media_type::JSON)
.unwrap_or(false)
}
/// Sets this link's media type to GeoJSON.
///
/// # Examples
///
/// ```
/// use stac::{Link, media_type};
/// let link = Link::new("a/href", "rel-type").geojson();
/// assert_eq!(link.r#type.unwrap(), media_type::GEOJSON);
/// ```
pub fn geojson(mut self) -> Link {
self.r#type = Some(media_type::GEOJSON.to_string());
self
}
/// Returns true if this link's media type is GeoJSON.
///
/// # Examples
///
/// ```
/// use stac::{Link, media_type};
/// let link = Link::new("a/href", "rel-type").geojson();
/// assert!(link.is_geojson());
/// ```
pub fn is_geojson(&self) -> bool {
self.r#type
.as_ref()
.map(|t| t == media_type::GEOJSON)
.unwrap_or(false)
}
/// Sets this link's media type.
///
/// # Examples
///
/// ```
/// use stac::{Link, media_type};
/// let link = Link::new("a/href", "rel-type").r#type(media_type::GEOJSON.to_string());
/// assert_eq!(link.r#type.unwrap(), media_type::GEOJSON);
/// ```
pub fn r#type(mut self, r#type: impl Into<Option<String>>) -> Link {
self.r#type = r#type.into();
self
}
/// Sets this link's title.
///
/// # Examples
///
/// ```
/// use stac::Link;
/// let link = Link::new("a/href", "rel-type").title("a title".to_string());
/// assert_eq!(link.title.unwrap(), "a title");
/// ```
pub fn title(mut self, title: impl Into<Option<String>>) -> Link {
self.title = title.into();
self
}
/// Creates a new root link with JSON media type.
///
/// # Examples
///
/// ```
/// # use stac::{Link, media_type};
/// let link = Link::root("an-href");
/// assert!(link.is_root());
/// assert_eq!(link.r#type.as_ref().unwrap(), media_type::JSON);
/// ```
pub fn root(href: impl ToString) -> Link {
Link::new(href, ROOT_REL).json()
}
/// Creates a new self link with JSON media type.
///
/// # Examples
///
/// ```
/// # use stac::{Link, media_type};
/// let link = Link::self_("an-href");
/// assert!(link.is_self());
/// assert_eq!(link.r#type.as_ref().unwrap(), media_type::JSON);
/// ```
pub fn self_(href: impl ToString) -> Link {
Link::new(href, SELF_REL).json()
}
/// Creates a new child link with JSON media type.
///
/// # Examples
///
/// ```
/// # use stac::{Link, media_type};
/// let link = Link::child("an-href");
/// assert!(link.is_child());
/// assert_eq!(link.r#type.as_ref().unwrap(), media_type::JSON);
/// ```
pub fn child(href: impl ToString) -> Link {
Link::new(href, CHILD_REL).json()
}
/// Creates a new item link with JSON media type.
///
/// # Examples
///
/// ```
/// # use stac::{Link, media_type};
/// let link = Link::item("an-href");
/// assert!(link.is_item());
/// assert_eq!(link.r#type.as_ref().unwrap(), media_type::JSON);
/// ```
pub fn item(href: impl ToString) -> Link {
Link::new(href, ITEM_REL).json()
}
/// Creates a new parent link with JSON media type.
///
/// # Examples
///
/// ```
/// # use stac::{Link, media_type};
/// let link = Link::parent("an-href");
/// assert!(link.is_parent());
/// assert_eq!(link.r#type.as_ref().unwrap(), media_type::JSON);
/// ```
pub fn parent(href: impl ToString) -> Link {
Link::new(href, PARENT_REL).json()
}
/// Creates a new collection link with JSON media type.
///
/// # Examples
///
/// ```
/// # use stac::{Link, media_type};
/// let link = Link::collection("an-href");
/// assert!(link.is_collection());
/// assert_eq!(link.r#type.as_ref().unwrap(), media_type::JSON);
/// ```
pub fn collection(href: impl ToString) -> Link {
Link::new(href, COLLECTION_REL).json()
}
/// Returns true if this link's rel is `"item"`.
///
/// # Examples
///
/// ```
/// # use stac::Link;
/// let link = Link::new("an-href", "item");
/// assert!(link.is_item());
/// let link = Link::new("an-href", "not-an-item");
/// assert!(!link.is_item());
/// ```
pub fn is_item(&self) -> bool {
self.rel == ITEM_REL
}
/// Returns true if this link's rel is `"child"`.
///
/// # Examples
///
/// ```
/// # use stac::Link;
/// let link = Link::new("an-href", "child");
/// assert!(link.is_child());
/// let link = Link::new("an-href", "not-a-child");
/// assert!(!link.is_child());
/// ```
pub fn is_child(&self) -> bool {
self.rel == CHILD_REL
}
/// Returns true if this link's rel is `"parent"`.
///
/// # Examples
///
/// ```
/// # use stac::Link;
/// let link = Link::new("an-href", "parent");
/// assert!(link.is_parent());
/// let link = Link::new("an-href", "not-a-parent");
/// assert!(!link.is_parent());
/// ```
pub fn is_parent(&self) -> bool {
self.rel == PARENT_REL
}
/// Returns true if this link's rel is `"root"`.
///
/// # Examples
///
/// ```
/// # use stac::Link;
/// let link = Link::new("an-href", "root");
/// assert!(link.is_root());
/// let link = Link::new("an-href", "not-a-root");
/// assert!(!link.is_root());
/// ```
pub fn is_root(&self) -> bool {
self.rel == ROOT_REL
}
/// Returns true if this link's rel is `"self"`.
///
/// # Examples
///
/// ```
/// # use stac::Link;
/// let link = Link::new("an-href", "self");
/// assert!(link.is_self());
/// let link = Link::new("an-href", "not-a-self");
/// assert!(!link.is_self());
/// ```
pub fn is_self(&self) -> bool {
self.rel == SELF_REL
}
/// Returns true if this link's rel is `"collection"`.
///
/// # Examples
///
/// ```
/// # use stac::Link;
/// let link = Link::new("an-href", "collection");
/// assert!(link.is_collection());
/// let link = Link::new("an-href", "not-a-collection");
/// assert!(!link.is_collection());
/// ```
pub fn is_collection(&self) -> bool {
self.rel == COLLECTION_REL
}
/// Returns true if this link is structural (i.e. not child, parent, item,
/// root, or self).
///
/// # Examples
///
/// ```
/// # use stac::Link;
/// let link = Link::new("an-href", "self");
/// assert!(link.is_structural());
/// let link = Link::new("an-href", "child");
/// assert!(link.is_structural());
/// let link = Link::new("an-href", "not-a-root");
/// assert!(!link.is_structural());
pub fn is_structural(&self) -> bool {
self.is_child() || self.is_item() || self.is_parent() || self.is_root() || self.is_self()
}
/// Returns true if this link's href is an absolute path or url.
///
/// # Examples
///
/// ```
/// use stac::Link;
///
/// assert!(Link::new("/a/local/path/item.json", "rel").is_absolute());
/// assert!(Link::new("http://stac-rs.test/item.json", "rel").is_absolute());
/// assert!(!Link::new("./not/an/absolute/path", "rel").is_absolute());
/// ```
pub fn is_absolute(&self) -> bool {
is_absolute(&self.href)
}
/// Sets a link's href's query to anything serializable by [serde_urlencoded].
///
/// Raises an error if the href is not parseable as a url. Requires the
/// `set_query` feature to be enabled.
///
/// # Examples
///
/// ```
/// # use stac::Link;
/// let mut link = Link::new("http://stac-rs.test/", "a-rel");
/// link.set_query([("foo", "bar")]).unwrap();
/// assert_eq!(link.href, "http://stac-rs.test/?foo=bar");
/// ```
#[cfg(feature = "set_query")]
pub fn set_query<Q>(&mut self, query: Q) -> Result<()>
where
Q: Serialize,
{
let mut url: Url = self.href.parse()?;
let query = serde_urlencoded::to_string(query)?;
url.set_query(Some(&query));
self.href = url.to_string();
Ok(())
}
}
fn is_absolute(href: &str) -> bool {
Url::parse(&href).is_ok() || href.starts_with('/')
}
fn make_absolute(href: String, base: Option<&str>) -> Result<String> {
// TODO if we make this interface public, make this an impl Option
if is_absolute(&href) {
Ok(href)
} else if let Some(base) = base {
if let Ok(base) = Url::parse(base) {
base.join(&href)
.map(|url| url.to_string())
.map_err(Error::from)
} else {
let (base, _) = base.split_at(base.rfind('/').unwrap_or(0));
if base.is_empty() {
Ok(normalize_path(&href))
} else {
Ok(normalize_path(&format!("{}/{}", base, href)))
}
}
} else {
std::fs::canonicalize(href)
.map(|p| p.to_string_lossy().into_owned())
.map_err(Error::from)
}
}
fn normalize_path(path: &str) -> String {
let mut parts = if path.starts_with('/') {
Vec::new()
} else {
vec![""]
};
for part in path.split('/') {
match part {
"." => {}
".." => {
let _ = parts.pop();
}
s => parts.push(s),
}
}
parts.join("/")
}
#[cfg(test)]
mod tests {
use super::Link;
#[test]
fn new() {
let link = Link::new("an-href", "a-rel");
assert_eq!(link.href, "an-href");
assert_eq!(link.rel, "a-rel");
assert!(link.r#type.is_none());
assert!(link.title.is_none());
}
#[test]
fn skip_serializing() {
let link = Link::new("an-href", "a-rel");
let value = serde_json::to_value(link).unwrap();
assert!(value.get("type").is_none());
assert!(value.get("title").is_none());
}
#[test]
#[cfg(feature = "set_query")]
fn set_query_pair() {
let mut link = Link::new("http://stac-rs.test/an-href", "a-rel");
link.set_query([("foo", "bar")]).unwrap();
assert_eq!(link.href, "http://stac-rs.test/an-href?foo=bar");
link.set_query([("baz", "boz")]).unwrap();
assert_eq!(link.href, "http://stac-rs.test/an-href?baz=boz");
}
mod links {
use crate::{Catalog, Item, Link, Links};
#[test]
fn link() {
let mut item = Item::new("an-item");
assert!(item.link("root").is_none());
item.links.push(Link::new("an-href", "root"));
assert!(item.link("root").is_some());
}
#[test]
fn root() {
let mut item = Item::new("an-item");
assert!(item.root_link().is_none());
item.links.push(Link::new("an-href", "root"));
assert!(item.root_link().is_some());
}
#[test]
fn self_() {
let mut item = Item::new("an-item");
assert!(item.self_link().is_none());
item.links.push(Link::new("an-href", "self"));
assert!(item.self_link().is_some());
}
#[test]
fn make_relative_links_absolute_path() {
let mut catalog: Catalog = crate::read("data/catalog.json").unwrap();
catalog
.make_relative_links_absolute("data/catalog.json")
.unwrap();
for link in catalog.links() {
assert!(link.is_absolute());
}
}
#[test]
fn make_relative_links_absolute_url() {
let mut catalog: Catalog = crate::read("data/catalog.json").unwrap();
catalog
.make_relative_links_absolute("http://stac-rs.test/catalog.json")
.unwrap();
for link in catalog.links() {
assert!(link.is_absolute());
}
assert_eq!(
catalog.root_link().unwrap().href,
"http://stac-rs.test/catalog.json"
);
}
#[test]
fn remove_relative_links() {
let mut catalog = Catalog::new("an-id", "a description");
catalog.links.push(Link::new("./child.json", "child"));
catalog.links.push(Link::new("/child.json", "child"));
catalog
.links
.push(Link::new("http://stac-rs.test/child.json", "child"));
let removed = catalog.remove_relative_links();
assert_eq!(catalog.links.len(), 2);
assert_eq!(removed.len(), 1);
}
}
}