swls_core/systems/
imports.rs1use std::collections::{HashMap, HashSet};
16
17use bevy_ecs::prelude::*;
18use sophia_api::{
19 prelude::{Any, Dataset},
20 quad::Quad as _,
21 term::Term as _,
22};
23
24use crate::{
25 lsp_types::Url,
26 prelude::*,
27 systems::spawn_document,
28 util::{cache, ns::owl},
29};
30
31pub fn import_url(fs: &Fs, iri: &Url) -> Option<Url> {
33 match iri.scheme() {
34 "http" | "https" => fs.0.cache_url(iri),
35 _ => Some(iri.clone()),
36 }
37}
38
39const KNOWN_EXTENSIONS: &[&str] = &[".ttl", ".nt", ".owl", ".trig", ".n3", ".jsonld"];
42
43fn import_language(url: &Url) -> Option<String> {
46 let path = url.path();
47 if KNOWN_EXTENSIONS.iter().any(|ext| path.ends_with(ext)) {
48 None
49 } else {
50 Some(String::from("turtle"))
51 }
52}
53
54const ACCEPT: &str = "text/turtle, application/n-triples;q=0.9, text/plain;q=0.1";
57
58pub(crate) fn unsupported_syntax(content: &str) -> Option<&'static str> {
61 let start = content.trim_start();
62 if start.starts_with("<?xml") || start.starts_with("<rdf:RDF") {
63 Some("RDF/XML")
64 } else if start.len() >= 5 && start[..5].eq_ignore_ascii_case("<html")
65 || start.len() >= 9 && start[..9].eq_ignore_ascii_case("<!doctype")
66 {
67 Some("HTML")
68 } else {
69 None
70 }
71}
72
73async fn fetch_remote(iri: &Url, client: &impl Client) -> Option<String> {
75 let headers = HashMap::from([(String::from("Accept"), String::from(ACCEPT))]);
76 let resp = match client.fetch(iri.as_str(), &headers).await {
77 Ok(resp) => resp,
78 Err(e) => {
79 tracing::warn!("Fetching import {} failed: {}", iri, e);
80 return None;
81 }
82 };
83 if resp.status != 200 {
84 tracing::warn!("Fetching import {} failed with status {}", iri, resp.status);
85 return None;
86 }
87 let content_type = resp
88 .headers
89 .iter()
90 .find(|(k, _)| k.eq_ignore_ascii_case("content-type"))
91 .map(|(_, v)| v.to_ascii_lowercase());
92 if let Some(ct) = content_type.as_deref() {
93 if ct.contains("rdf+xml") || ct.contains("html") || ct.contains("json") {
94 tracing::warn!("Import {} is served as {}, which swls cannot read", iri, ct);
95 return None;
96 }
97 }
98 if let Some(syntax) = unsupported_syntax(&resp.body) {
99 tracing::warn!("Import {} is {}, which swls cannot read", iri, syntax);
100 return None;
101 }
102 Some(resp.body)
103}
104
105async fn load_import(iri: Url, label: &Url, fs: &Fs, client: &impl Client) -> Option<String> {
107 match iri.scheme() {
108 "http" | "https" => cache::cached(fs, label, || fetch_remote(&iri, client)).await,
109 _ => {
110 let content = fs.0.read_file(&iri).await?;
111 if let Some(syntax) = unsupported_syntax(&content) {
112 tracing::warn!("Import {} is {}, which swls cannot read", iri, syntax);
113 return None;
114 }
115 Some(content)
116 }
117 }
118}
119
120pub fn open_imports<C: Client + Resource>(
122 query: Query<&Triples, Changed<Triples>>,
123 mut opened: Local<HashSet<String>>,
124 sender: Res<CommandSender>,
125 fs: Res<Fs>,
126 client: Res<C>,
127) {
128 for triples in &query {
129 for iri in triples
130 .quads_matching(Any, [owl::imports], Any, Any)
131 .flatten()
132 .flat_map(|s| s.o().iri())
133 .flat_map(|s| Url::parse(s.as_str()))
134 {
135 if !opened.insert(iri.as_str().to_string()) {
136 continue;
137 }
138 let Some(label) = import_url(&fs, &iri) else {
139 continue;
140 };
141
142 let fs = fs.clone();
143 let sender = sender.clone();
144 let c = client.as_ref().clone();
145 client.spawn(async move {
146 let Some(content) = load_import(iri.clone(), &label, &fs, &c).await else {
147 tracing::warn!("No content found for import {}", iri);
148 return;
149 };
150 tracing::debug!("Loaded import {} as {}", iri, label);
151 let language = import_language(&label);
152 spawn_document(label, content, language, &sender.0, |_, _| {});
155 });
156 }
157 }
158}
159
160#[cfg(test)]
161mod tests {
162 use super::*;
163
164 #[test]
165 fn detects_unreadable_syntaxes() {
166 assert_eq!(
167 unsupported_syntax("<?xml version=\"1.0\"?>"),
168 Some("RDF/XML")
169 );
170 assert_eq!(unsupported_syntax(" <rdf:RDF>"), Some("RDF/XML"));
171 assert_eq!(unsupported_syntax("<!DOCTYPE html><html>"), Some("HTML"));
172 assert_eq!(unsupported_syntax("<HTML>"), Some("HTML"));
173 assert_eq!(unsupported_syntax("@prefix ex: <http://e/> ."), None);
174 assert_eq!(
175 unsupported_syntax("<http://a> <http://b> <http://c> ."),
176 None
177 );
178 }
179
180 #[test]
181 fn language_follows_known_extensions() {
182 let lang = |u: &str| import_language(&Url::parse(u).unwrap());
183 assert_eq!(lang("file:///a/onto.jsonld"), None);
184 assert_eq!(lang("file:///a/onto.ttl"), None);
185 assert_eq!(lang("file:///a/onto"), Some(String::from("turtle")));
186 }
187}