about summary refs log tree commit diff stats
path: root/src/file.rs
diff options
context:
space:
mode:
authorBenjamin Morrison <ben@gbmor.org>2023-06-20 23:29:12 -0400
committerBenjamin Morrison <ben@gbmor.org>2023-06-20 23:30:17 -0400
commitdc5cce23e9b0869455f546d968052bc200dd0011 (patch)
treebb3754de4483b4a50edc8a6a3d4585f305e4d1e2 /src/file.rs
downloadlaika-dc5cce23e9b0869455f546d968052bc200dd0011.tar.gz
init
Diffstat (limited to 'src/file.rs')
-rw-r--r--src/file.rs73
1 files changed, 73 insertions, 0 deletions
diff --git a/src/file.rs b/src/file.rs
new file mode 100644
index 0000000..4500473
--- /dev/null
+++ b/src/file.rs
@@ -0,0 +1,73 @@
+/* Copyright (C) 2023  Ben Morrison <ben@gbmor.org>
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program.  If not, see <https: *www.gnu.org/licenses/>.
+ */
+
+use std::io;
+
+use tokio::fs;
+
+use crate::err::Supernova;
+use crate::response;
+
+pub async fn get(path: &str) -> Result<(fs::File, String), Supernova> {
+    let metadata = match fs::metadata(path).await {
+        Ok(m) => m,
+        Err(e) => {
+            let code = match e.kind() {
+                io::ErrorKind::NotFound => response::Code::NotFound,
+                _ => response::Code::PermanentFailure,
+            };
+
+            let msg = format!("{}", e);
+            let wrapped_err = Supernova::boom(&msg).with_code(code);
+
+            return Err(wrapped_err);
+        }
+    };
+
+    let path = if metadata.is_dir() {
+        format!("{}/index.gmi", path)
+    } else {
+        path.to_string()
+    };
+
+    let fd = match fs::File::open(&path).await {
+        Ok(fd) => fd,
+        Err(e) => {
+            let code = match e.kind() {
+                io::ErrorKind::NotFound => response::Code::NotFound,
+                _ => response::Code::PermanentFailure,
+            };
+
+            let msg = format!("{}", e);
+            let wrapped_err = Supernova::boom(&msg).with_code(code);
+
+            return Err(wrapped_err);
+        }
+    };
+
+    let mime = match tree_magic_mini::from_filepath(path.as_ref()) {
+        Some(m) => {
+            if path.ends_with(".gmi") {
+                response::GEMINI_MIME
+            } else {
+                m
+            }
+        }
+        None => response::GEMINI_MIME,
+    };
+
+    Ok((fd, mime.to_string()))
+}