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
use crate::{
	context::{self, RemoteContext},
	Error, ErrorCode, RemoteDocument,
};
use futures::future::{BoxFuture, FutureExt};
use iref::{Iri, IriBuf};
use json::JsonValue;
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufReader, Read};
use std::path::{Path, PathBuf};

/// Document loader.
pub trait Loader {
	/// The type of documents that can be loaded.
	type Document;

	/// Load the document behind the given URL.
	fn load<'a>(
		&'a mut self,
		url: Iri<'_>,
	) -> BoxFuture<'a, Result<RemoteDocument<Self::Document>, Error>>;
}

impl<L: Send + Sync + Loader<Document = JsonValue>> context::Loader for L {
	type Output = JsonValue;

	fn load_context<'a>(
		&'a mut self,
		url: Iri,
	) -> BoxFuture<'a, Result<RemoteContext<JsonValue>, Error>> {
		let url = IriBuf::from(url);
		async move {
			match self.load(url.as_iri()).await {
				Ok(remote_doc) => {
					let (doc, url) = remote_doc.into_parts();
					if let JsonValue::Object(obj) = doc {
						if let Some(context) = obj.get("@context") {
							Ok(RemoteContext::from_parts(url, context.clone()))
						} else {
							Err(ErrorCode::InvalidRemoteContext.into())
						}
					} else {
						Err(ErrorCode::InvalidRemoteContext.into())
					}
				}
				Err(_) => Err(ErrorCode::LoadingRemoteContextFailed.into()),
			}
		}
		.boxed()
	}
}

/// Dummy loader.
///
/// A dummy loader that does not load anything.
/// Can be useful when you know that you will never need to load remote ressources.
///
/// Raises an `LoadingDocumentFailed` at every attempt to load a ressource.
pub struct NoLoader;

impl Loader for NoLoader {
	type Document = JsonValue;

	fn load<'a>(
		&'a mut self,
		_url: Iri<'_>,
	) -> BoxFuture<'a, Result<RemoteDocument<Self::Document>, Error>> {
		async move { Err(ErrorCode::LoadingDocumentFailed.into()) }.boxed()
	}
}

/// File-system loader.
///
/// This is a special JSON-LD document loader that can load document from the file system by
/// attaching a directory to specific URLs.
pub struct FsLoader {
	cache: HashMap<IriBuf, RemoteDocument>,
	mount_points: HashMap<PathBuf, IriBuf>,
}

impl FsLoader {
	pub fn new() -> FsLoader {
		FsLoader {
			cache: HashMap::new(),
			mount_points: HashMap::new(),
		}
	}

	pub fn mount<P: AsRef<Path>>(&mut self, url: Iri, path: P) {
		self.mount_points.insert(path.as_ref().into(), url.into());
	}
}

impl Default for FsLoader {
	fn default() -> Self {
		Self::new()
	}
}

impl Loader for FsLoader {
	type Document = JsonValue;

	fn load<'a>(
		&'a mut self,
		url: Iri<'_>,
	) -> BoxFuture<'a, Result<RemoteDocument<Self::Document>, Error>> {
		let url: IriBuf = url.into();
		async move {
			match self.cache.get(&url) {
				Some(doc) => Ok(doc.clone()),
				None => {
					for (path, target_url) in &self.mount_points {
						let url_ref = url.as_iri_ref();
						if let Some((suffix, _, _)) = url_ref.suffix(target_url.as_iri_ref()) {
							let mut filepath = path.clone();
							for seg in suffix.as_path().segments() {
								filepath.push(seg.as_str())
							}

							if let Ok(file) = File::open(filepath) {
								let mut buf_reader = BufReader::new(file);
								let mut contents = String::new();
								if buf_reader.read_to_string(&mut contents).is_ok() {
									if let Ok(doc) = json::parse(contents.as_str()) {
										let remote_doc = RemoteDocument::new(doc, url.as_iri());
										self.cache.insert(url.clone(), remote_doc.clone());
										return Ok(remote_doc);
									} else {
										return Err(ErrorCode::LoadingDocumentFailed.into());
									}
								} else {
									return Err(ErrorCode::LoadingDocumentFailed.into());
								}
							} else {
								return Err(ErrorCode::LoadingDocumentFailed.into());
							}
						}
					}

					Err(ErrorCode::LoadingDocumentFailed.into())
				}
			}
		}
		.boxed()
	}
}