diff --git a/Cargo.toml b/Cargo.toml index f212fe1..a2b57f8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name="microbin" -version="0.2.0" +version="1.0.0" edition="2021" [dependencies] @@ -20,4 +20,6 @@ sanitize-filename = "0.3.0" log = "0.4" env_logger = "0.9.0" actix-web-httpauth = "0.6.0" -lazy_static = "1.4.0" \ No newline at end of file +lazy_static = "1.4.0" +syntect = "5.0" + diff --git a/README.MD b/README.MD index 9c4501d..2df97b9 100644 --- a/README.MD +++ b/README.MD @@ -2,24 +2,94 @@ ![Screenshot](git/index.png) -MicroBin is a super tiny and simple self hosted pastebin app written in Rust. The executable is around 6MB and it uses 2MB memory (plus your pastas, because they are all stored in the memory at the moment). +MicroBin is a super tiny, feature rich, configurable, self-contained and self-hosted paste bin web application. It is very easy to set up and use, and will only require a few megabytes of memory and disk storage. It takes only a couple minutes to set it up, why not give it a try now? ### Features - Is very small -- File uploads -- Raw pasta content (/raw/[animals]) -- URL shortening and redirection -- Automatic dark mode (follows system preferences) -- Very simple database (json + files) for portability and easy backups - Animal names instead of random numbers for pasta identifiers (64 animals) -- Automatically expiring pastas -- Never expiring pastas +- File uploads (eg. server.com/file/pig-dog-cat) +- Raw pasta text (eg. server.com/raw/pig-dog-cat) +- URL shortening and redirection +- Very simple database (JSON + files) for portability, easy backups and integration - Listing and manually removing pastas (/pastalist) +- Private and public pastas +- Editable and final pastas +- Never expiring pastas +- Automatically expiring pastas +- Syntax highlighting +- Entirely self-contained executable, MicroBin is a single file! +- Automatic dark mode (follows system preferences) - Very little CSS and absolutely no JS (see [water.css](https://github.com/kognise/water.css)) +- Most of the above can be toggled on and off! + +## 1 Usage + +### What is a "pasta" anyway? + +In microbin, a pasta can be: +- A text that you want to paste from one machine to another, eg. some code, +- A file that you want to share, eg. a video that is too large for Discord, a zip with a code project in it or an image, +- A URL redirect. + +### When is MicroBin useful? + +You can use MicroBin +- As a URL shortener/redirect service, +- To send long texts to other people, +- To send large files to other people, +- To serve content on the web, eg. configuration files for testing, images, or any other file content using the Raw functionality, +- To move files between your desktop and a server you access from the console, +- As a "postbox" service where people can upload their files or texts, but they cannot see or remove what others sent you - just disable the pastalist page +- To take notes! Simply create an editable pasta. + +...and many other things, why not get creative? + +### Creating a Pasta + +Navigate to the root of your server, for example https://microbin.myserver.com/. This should show you a form where you will at the very least see an expiration selector, a file attachment input, a content text field and a green save button. Depending on your configuration there miight also be a syntax highlight selector, an editable checkbox and a private ceckbox. + +Use the expiration dropdown to choose how long you want your pasta to exist. When the selected time has expired, it will be removed from the server. The content can be any text, including plain text, code, html, even a URL. A URL is a special case, because when you open the pasta again, it will redirect you to that URL instead of showing it as a text. Entering content is optional, and so is the file attachment. If you want, you can even submit a pasta completely empty. + +You will be redirected to the URL of the pasta, which will end with a few animal names. If you remember those animals, you can simply type them in on another machine and open your pasta elsewhere. + +If you have editable pastas enabled and you check the editable checkbox, then later on there will be an option to change the text content of your pasta. Selecting the private checkbox will simply prevent your pasta to show up on the pasta list page, if that is enabled. + +If you have syntax higlighting enabled, then select your language from the dropdown, or leave it as none if you just want to upload plain with no highlighting. + +### Listing Pastas + +If you have pasta listing enabled, then there is a pasta list option in the navigation bar, which will list all the pastas on the server in two groups: regular pastas and URL redirects (pastas containing nothing but a URL). If you have private pastas enabled, they will not show up here at all. + +From the pasta list page, you will be able to view individual pastas by clicking on their animal identifiers on the lest, view their raw contrent by clicking on the Raw button, remove them, and if you have editable pastas enabled, then open them in edit view. + +### Use MicroBin from the console with cURL + +Simple text Pasta: `curl -d "expiration=10min&content=This is a test pasta" -X POST https://microbin.myserver.com/create` + +File contents: `curl -d "expiration=10min&content=$( < mypastafile.txt )" -X POST https://microbin.myserver.com/create` + +Available expiration options: +`1min`, `10min`, `1hour`, `24hour`, `1week`, `never` + +Use cURL to read the pasta: `curl https://microbin.myserver.com/rawpasta/fish-pony-crow`, + +or to download the pasta: `curl https://microbin.myserver.com/rawpasta/fish-pony-crow > output.txt` (use /file instead of /rawpasta to download attached file). + +## 2 Installation + +### Building MicroBin -### Installation Simply clone the repository, build it with `cargo build --release` and run the `microbin` executable in the created `target/release/` directory. It will start on port 8080. You can change the port with `-p` or `--port` CL arguments. For other arguments see [the Wiki](https://github.com/szabodanika/microbin/wiki). +``` +git clone https://github.com/szabodanika/microbin.git +cd microbin +cargo build --release +./target/release/microbin -p 80 +``` + +### MicroBin as a service + To install it as a service on your Linux machine, create a file called `/etc/systemd/system/microbin.service`, paste this into it with the `[username]` and `[path to installation directory]` replaced with the actual values. ``` @@ -39,28 +109,140 @@ ExecStart=[path to installation directory]/target/release/microbin WantedBy=multi-user.target ``` -Then start the service with `systemctl start microbin` and enable it on boot with `systemctl enable microbin`. - -### Create Pasta with cURL - -Simple text Pasta: `curl -d "expiration=10min&content=This is a test pasta" -X POST https://microbin.myserver.com/create` - -File contents: `curl -d "expiration=10min&content=$( < mypastafile.txt )" -X POST https://microbin.myserver.com/create` - -Available expiration options: -`1min`, `10min`, `1hour`, `24hour`, `1week`, `never` - -Use cURL to read the pasta: `curl https://microbin.myserver.com/rawpasta/fish-pony-crow`, - -or to download the pasta: `curl https://microbin.myserver.com/rawpasta/fish-pony-crow > output.txt` (use /file instead of /rawpasta to download attached file). +Here is my `microbin.service` for example, with some optional arguments: -### Needed improvements -- ~~Persisting pastas on disk (currently they are lost on restart)~~ (added on 2 May 2022) -- ~~Configuration with command line arguments (ports, enable-disable pasta list, footer, etc)~~ (added on 7 May 2022) -- ~~File uploads~~ (added on 2 May 2022) -- ~~URL shortening~~ (added on 23 April 2022) -- Removing pasta after N reads -- CLI tool (beyond wget) -- Better instructions and documentation - on GitHub and built in +``` +[Unit] +Description=MicroBin +After=network.target +[Service] +Type=simple +Restart=always +User=ubuntu +RootDirectory=/ + +# This is the directory where I want to run microbin. It will store all the pastas here. +WorkingDirectory=/home/ubuntu/server/microbin + +# This is the location of my executable - I also have 2 optional features enabled +ExecStart=/home/ubuntu/server/microbin/target/release/microbin --editable --linenumbers --highlightsyntax + +# I keep my installation in the home directory, so I need to add this +ProtectHome=off + +[Install] +WantedBy=multi-user.target +``` + +Then start the service with `systemctl start microbin` and enable it on boot with `systemctl enable microbin`. To update your MicroBin, simply update or clone the repository again, build it again, and then restart the service with `systemctl restart microbin`. An update will never affect your existing pastas, unless there is a breaking change in the data model (in which case MicroBin just won't be able to import your DB), which will always be mentioned explicitly. + +### NGINX configuration + +``` +server { + # I have HTTPS enabled using certbot - you can use HTTP of course if you want! + listen 443 ssl; # managed by Certbot + + server_name microbin.myserver.com; + + location / { + # Make sure to change the port if you are not running MicroBin at 8080! + proxy_pass http://127.0.0.1:8080$request_uri; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + } + + # Limit content size - I have 1GB because my MicroBin server is private, no one else will use it. + client_max_body_size 1024M; + + ssl_certificate /etc/letsencrypt/live/microbin.myserver.com/fullchain.pem; # managed by Certbot + ssl_certificate_key /etc/letsencrypt/live/microbin.myserver.com/privkey.pem; # managed by Certbot + include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot + ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot +} + +``` + +## 3 Command Line Arguments + +There is an ever expanding list of customisations built into MicroBin so you can use it the way you want. Instead of a configuration file, we simply use arguments that you pass to the executable, making the workflow even simpler. Read the following options and if you cannot find what you need, you can always open an issue at our GitHub repository and request a new feature! + +### --auth-username [AUTH_USERNAME] + +Require username for HTTP Basic Authentication when visiting the service. If `--auth-username` is set but `--auth-password ` is not, just leave the password field empty when logging in. You can also just go to https://username:password@yourserver.net or https://username@yourserver.net if password is not set instead of typing into the password + +### --auth-password [AUTH_PASSWORD] + +Require password for HTTP Basic Authentication when visiting the service. Will not have any affect unless `--auth-username` is also set. If `--auth-username` is set but `--auth-password ` is not, just leave the password field empty when logging in. You can also just go to https://username:password@yourserver.net or https://username@yourserver.net if password is not set instead of typing into the password prompt. + +### --editable + +Enables editable pastas. You will still be able to make finalised pastas but there will be an extra checkbox to make your new pasta editable from the pasta list or the pasta view page. + +### --footer_text [TEXT] + +Replaces the default footer text with your own. If you want to hide the footer, use --hide-footer instead. + +### -h, --help + +Show all commands in the terminal. + +### --hide-footer + +Hides the footer on every page. + +### --hide-header + +Hides the navigation bar on every page. + +### --hide-logo + +Hides the MicroBin logo from the navigation bar on every page. + +### --no-listing + +Disables the /pastalist endpoint, essentially making all pastas private. + +### --highlightsyntax + +Enables syntax highlighting support. When creating a new pasta, a new dropdown selector will be added where you can select your pasta's syntax, or just leave it empty for no highlighting. + +### -p, --port [PORT] + +Default value: 8080 + +Sets the port for the server will be listening on. + +### --private + +Enables private pastas. Adds a new checkbox to make your pasta private, which then won't show up on the pastalist page. With the URL to your pasta, it will still be accessible. + +### --pure-html + +Disables main CSS styling, just uses a few in-line stylings for the layout. With this option you will lose dark-mode support. + +### --readonly + +Disables adding/editing/removing pastas entirely. + +### --title [TITLE] + +Replaces "MicroBin" with your title of choice in the navigation bar. + +### -t, --threads [THREADS] + +Default value: 1 + +Number of workers MicroBin is allowed to have. Increase this to the number of CPU cores you have if you want to go beast mode, but for personal use one worker is enough. + +### -V, --version + +Displays your MicroBin's version information. + +### --wide + +Changes the maximum width of the UI from 720 pixels to 1080 pixels. diff --git a/git/index.png b/git/index.png index 350f814..b1e2384 100644 Binary files a/git/index.png and b/git/index.png differ diff --git a/src/args.rs b/src/args.rs new file mode 100644 index 0000000..15546df --- /dev/null +++ b/src/args.rs @@ -0,0 +1,58 @@ +use clap::Parser; +use lazy_static::lazy_static; + +lazy_static! { + pub static ref ARGS: Args = Args::parse(); +} + +#[derive(Parser, Debug, Clone)] +#[clap(author, version, about, long_about = None)] +pub struct Args { + #[clap(long)] + pub auth_username: Option, + + #[clap(long)] + pub auth_password: Option, + + #[clap(long)] + pub editable: bool, + + #[clap(long)] + pub footer_text: Option, + + #[clap(long)] + pub hide_footer: bool, + + #[clap(long)] + pub hide_header: bool, + + #[clap(long)] + pub hide_logo: bool, + + #[clap(long)] + pub no_listing: bool, + + #[clap(long)] + pub highlightsyntax: bool, + + #[clap(short, long, default_value_t = 8080)] + pub port: u32, + + #[clap(long)] + pub private: bool, + + #[clap(long)] + pub pure_html: bool, + + #[clap(long)] + pub readonly: bool, + + #[clap(long)] + pub title: Option, + + #[clap(short, long, default_value_t = 1)] + pub threads: u8, + + #[clap(long)] + pub wide: bool, +} diff --git a/src/endpoints/create.rs b/src/endpoints/create.rs new file mode 100644 index 0000000..64c6ab6 --- /dev/null +++ b/src/endpoints/create.rs @@ -0,0 +1,142 @@ +use crate::dbio::save_to_file; +use crate::util::animalnumbers::to_animal_names; +use crate::util::misc::is_valid_url; +use crate::{AppState, Pasta, ARGS}; +use actix_multipart::Multipart; +use actix_web::{get, web, Error, HttpResponse, Responder}; +use askama::Template; +use futures::TryStreamExt; +use rand::Rng; +use std::io::Write; +use std::time::{SystemTime, UNIX_EPOCH}; + +#[derive(Template)] +#[template(path = "index.html")] +struct IndexTemplate<'a> { + args: &'a ARGS, +} + +#[get("/")] +pub async fn index() -> impl Responder { + HttpResponse::Found() + .content_type("text/html") + .body(IndexTemplate { args: &ARGS }.render().unwrap()) +} + +pub async fn create( + data: web::Data, + mut payload: Multipart, +) -> Result { + if ARGS.readonly { + return Ok(HttpResponse::Found() + .append_header(("Location", "/")) + .finish()); + } + + let mut pastas = data.pastas.lock().unwrap(); + + let timenow: i64 = match SystemTime::now().duration_since(UNIX_EPOCH) { + Ok(n) => n.as_secs(), + Err(_) => { + log::error!("SystemTime before UNIX EPOCH!"); + 0 + } + } as i64; + + let mut new_pasta = Pasta { + id: rand::thread_rng().gen::() as u64, + content: String::from("No Text Content"), + file: String::from("no-file"), + extension: String::from(""), + private: false, + editable: false, + created: timenow, + pasta_type: String::from(""), + expiration: 0, + }; + + while let Some(mut field) = payload.try_next().await? { + match field.name() { + "editable" => { + // while let Some(_chunk) = field.try_next().await? {} + new_pasta.editable = true; + continue; + } + "private" => { + // while let Some(_chunk) = field.try_next().await? {} + new_pasta.private = true; + continue; + } + "expiration" => { + while let Some(chunk) = field.try_next().await? { + new_pasta.expiration = match std::str::from_utf8(&chunk).unwrap() { + "1min" => timenow + 60, + "10min" => timenow + 60 * 10, + "1hour" => timenow + 60 * 60, + "24hour" => timenow + 60 * 60 * 24, + "1week" => timenow + 60 * 60 * 24 * 7, + "never" => 0, + _ => { + log::error!("{}", "Unexpected expiration time!"); + 0 + } + }; + } + + continue; + } + "content" => { + while let Some(chunk) = field.try_next().await? { + new_pasta.content = std::str::from_utf8(&chunk).unwrap().to_string(); + new_pasta.pasta_type = if is_valid_url(new_pasta.content.as_str()) { + String::from("url") + } else { + String::from("text") + }; + } + continue; + } + "syntax-highlight" => { + while let Some(chunk) = field.try_next().await? { + new_pasta.extension = std::str::from_utf8(&chunk).unwrap().to_string(); + } + continue; + } + "file" => { + let content_disposition = field.content_disposition(); + + let filename = match content_disposition.get_filename() { + Some("") => continue, + Some(filename) => filename.replace(' ', "_").to_string(), + None => continue, + }; + + std::fs::create_dir_all(format!("./pasta_data/{}", &new_pasta.id_as_animals())) + .unwrap(); + + let filepath = format!("./pasta_data/{}/{}", &new_pasta.id_as_animals(), &filename); + + new_pasta.file = filename; + + let mut f = web::block(|| std::fs::File::create(filepath)).await??; + + while let Some(chunk) = field.try_next().await? { + f = web::block(move || f.write_all(&chunk).map(|_| f)).await??; + } + + new_pasta.pasta_type = String::from("text"); + } + _ => {} + } + } + + let id = new_pasta.id; + + pastas.push(new_pasta); + + save_to_file(&pastas); + + Ok(HttpResponse::Found() + .append_header(("Location", format!("/pasta/{}", to_animal_names(id)))) + .finish()) +} diff --git a/src/endpoints/edit.rs b/src/endpoints/edit.rs new file mode 100644 index 0000000..21693d5 --- /dev/null +++ b/src/endpoints/edit.rs @@ -0,0 +1,99 @@ +use crate::args::Args; +use crate::dbio::save_to_file; +use crate::endpoints::errors::ErrorTemplate; +use crate::util::animalnumbers::to_u64; +use crate::util::misc::remove_expired; +use crate::{AppState, Pasta, ARGS}; +use actix_multipart::Multipart; +use actix_web::{get, post, web, Error, HttpResponse}; +use askama::Template; +use futures::TryStreamExt; + +#[derive(Template)] +#[template(path = "edit.html", escape = "none")] +struct EditTemplate<'a> { + pasta: &'a Pasta, + args: &'a Args, +} + +#[get("/edit/{id}")] +pub async fn get_edit(data: web::Data, id: web::Path) -> HttpResponse { + let mut pastas = data.pastas.lock().unwrap(); + + let id = to_u64(&*id.into_inner()).unwrap_or(0); + + remove_expired(&mut pastas); + + for pasta in pastas.iter() { + if pasta.id == id { + if !pasta.editable { + return HttpResponse::Found() + .append_header(("Location", "/")) + .finish(); + } + return HttpResponse::Found().content_type("text/html").body( + EditTemplate { + pasta: &pasta, + args: &ARGS, + } + .render() + .unwrap(), + ); + } + } + + HttpResponse::Found() + .content_type("text/html") + .body(ErrorTemplate { args: &ARGS }.render().unwrap()) +} + +#[post("/edit/{id}")] +pub async fn post_edit( + data: web::Data, + id: web::Path, + mut payload: Multipart, +) -> Result { + if ARGS.readonly { + return Ok(HttpResponse::Found() + .append_header(("Location", "/")) + .finish()); + } + + let id = to_u64(&*id.into_inner()).unwrap_or(0); + + let mut pastas = data.pastas.lock().unwrap(); + + remove_expired(&mut pastas); + + let mut new_content = String::from(""); + + while let Some(mut field) = payload.try_next().await? { + match field.name() { + "content" => { + while let Some(chunk) = field.try_next().await? { + new_content = std::str::from_utf8(&chunk).unwrap().to_string(); + } + } + _ => {} + } + } + + for (i, pasta) in pastas.iter().enumerate() { + if pasta.id == id { + if pasta.editable { + pastas[i].content.replace_range(.., &*new_content); + save_to_file(&pastas); + + return Ok(HttpResponse::Found() + .append_header(("Location", format!("/pasta/{}", pastas[i].id_as_animals()))) + .finish()); + } else { + break; + } + } + } + + Ok(HttpResponse::Found() + .content_type("text/html") + .body(ErrorTemplate { args: &ARGS }.render().unwrap())) +} diff --git a/src/endpoints/errors.rs b/src/endpoints/errors.rs new file mode 100644 index 0000000..ceda5b2 --- /dev/null +++ b/src/endpoints/errors.rs @@ -0,0 +1,16 @@ +use actix_web::{Error, HttpResponse}; +use askama::Template; + +use crate::args::{Args, ARGS}; + +#[derive(Template)] +#[template(path = "error.html")] +pub struct ErrorTemplate<'a> { + pub args: &'a Args, +} + +pub async fn not_found() -> Result { + Ok(HttpResponse::Found() + .content_type("text/html") + .body(ErrorTemplate { args: &ARGS }.render().unwrap())) +} diff --git a/src/endpoints/help.rs b/src/endpoints/help.rs new file mode 100644 index 0000000..f3aa6fd --- /dev/null +++ b/src/endpoints/help.rs @@ -0,0 +1,23 @@ +use crate::args::{Args, ARGS}; +use actix_web::{get, HttpResponse}; +use askama::Template; +use std::marker::PhantomData; + +#[derive(Template)] +#[template(path = "help.html")] +struct Help<'a> { + args: &'a Args, + _marker: PhantomData<&'a ()>, +} + +#[get("/help")] +pub async fn help() -> HttpResponse { + HttpResponse::Found().content_type("text/html").body( + Help { + args: &ARGS, + _marker: Default::default(), + } + .render() + .unwrap(), + ) +} diff --git a/src/endpoints/pasta.rs b/src/endpoints/pasta.rs new file mode 100644 index 0000000..8099e4c --- /dev/null +++ b/src/endpoints/pasta.rs @@ -0,0 +1,88 @@ +use actix_web::{get, web, HttpResponse}; +use askama::Template; + +use crate::args::{Args, ARGS}; +use crate::endpoints::errors::ErrorTemplate; +use crate::pasta::Pasta; +use crate::util::animalnumbers::to_u64; +use crate::util::misc::remove_expired; +use crate::AppState; + +#[derive(Template)] +#[template(path = "pasta.html", escape = "none")] +struct PastaTemplate<'a> { + pasta: &'a Pasta, + args: &'a Args, +} + +#[get("/pasta/{id}")] +pub async fn getpasta(data: web::Data, id: web::Path) -> HttpResponse { + let mut pastas = data.pastas.lock().unwrap(); + + let id = to_u64(&*id.into_inner()).unwrap_or(0); + + println!("{}", id); + + remove_expired(&mut pastas); + + for pasta in pastas.iter() { + if pasta.id == id { + return HttpResponse::Found().content_type("text/html").body( + PastaTemplate { + pasta: &pasta, + args: &ARGS, + } + .render() + .unwrap(), + ); + } + } + + HttpResponse::Found() + .content_type("text/html") + .body(ErrorTemplate { args: &ARGS }.render().unwrap()) +} + +#[get("/url/{id}")] +pub async fn redirecturl(data: web::Data, id: web::Path) -> HttpResponse { + let mut pastas = data.pastas.lock().unwrap(); + + let id = to_u64(&*id.into_inner()).unwrap_or(0); + + remove_expired(&mut pastas); + + for pasta in pastas.iter() { + if pasta.id == id { + if pasta.pasta_type == "url" { + return HttpResponse::Found() + .append_header(("Location", String::from(&pasta.content))) + .finish(); + } else { + return HttpResponse::Found() + .content_type("text/html") + .body(ErrorTemplate { args: &ARGS }.render().unwrap()); + } + } + } + + HttpResponse::Found() + .content_type("text/html") + .body(ErrorTemplate { args: &ARGS }.render().unwrap()) +} + +#[get("/raw/{id}")] +pub async fn getrawpasta(data: web::Data, id: web::Path) -> String { + let mut pastas = data.pastas.lock().unwrap(); + + let id = to_u64(&*id.into_inner()).unwrap_or(0); + + remove_expired(&mut pastas); + + for pasta in pastas.iter() { + if pasta.id == id { + return pasta.content.to_owned(); + } + } + + String::from("Pasta not found! :-(") +} diff --git a/src/endpoints/pastalist.rs b/src/endpoints/pastalist.rs new file mode 100644 index 0000000..bfe649c --- /dev/null +++ b/src/endpoints/pastalist.rs @@ -0,0 +1,38 @@ +use actix_web::{get, web, HttpResponse}; +use askama::Template; + +use crate::args::{Args, ARGS}; +use crate::pasta::Pasta; +use crate::util::misc::remove_expired; +use crate::AppState; + +#[derive(Template)] +#[template(path = "pastalist.html")] +struct PastaListTemplate<'a> { + pastas: &'a Vec, + args: &'a Args, +} + +#[get("/pastalist")] +pub async fn list(data: web::Data) -> HttpResponse { + if ARGS.no_listing { + return HttpResponse::Found() + .append_header(("Location", "/")) + .finish(); + } + + let mut pastas = data.pastas.lock().unwrap(); + + pastas.retain(|p| !p.private); + + remove_expired(&mut pastas); + + HttpResponse::Found().content_type("text/html").body( + PastaListTemplate { + pastas: &pastas, + args: &ARGS, + } + .render() + .unwrap(), + ) +} diff --git a/src/endpoints/remove.rs b/src/endpoints/remove.rs new file mode 100644 index 0000000..f04217d --- /dev/null +++ b/src/endpoints/remove.rs @@ -0,0 +1,36 @@ +use actix_web::{get, web, HttpResponse}; + +use crate::args::ARGS; +use crate::endpoints::errors::ErrorTemplate; +use crate::util::animalnumbers::to_u64; +use crate::util::misc::remove_expired; +use crate::AppState; +use askama::Template; + +#[get("/remove/{id}")] +pub async fn remove(data: web::Data, id: web::Path) -> HttpResponse { + if ARGS.readonly { + return HttpResponse::Found() + .append_header(("Location", "/")) + .finish(); + } + + let mut pastas = data.pastas.lock().unwrap(); + + let id = to_u64(&*id.into_inner()).unwrap_or(0); + + remove_expired(&mut pastas); + + for (i, pasta) in pastas.iter().enumerate() { + if pasta.id == id { + pastas.remove(i); + return HttpResponse::Found() + .append_header(("Location", "/pastalist")) + .finish(); + } + } + + HttpResponse::Found() + .content_type("text/html") + .body(ErrorTemplate { args: &ARGS }.render().unwrap()) +} diff --git a/src/endpoints/static_resources.rs b/src/endpoints/static_resources.rs new file mode 100644 index 0000000..b116852 --- /dev/null +++ b/src/endpoints/static_resources.rs @@ -0,0 +1,23 @@ +use actix_web::{get, web, HttpResponse}; +use askama::Template; +use std::marker::PhantomData; + +#[derive(Template)] +#[template(path = "water.css", escape = "none")] +struct WaterCSS<'a> { + _marker: PhantomData<&'a ()>, +} + +#[get("/static/{resource}")] +pub async fn static_resources(resource_id: web::Path) -> HttpResponse { + match resource_id.into_inner().as_str() { + "water.css" => HttpResponse::Found().content_type("text/html").body( + WaterCSS { + _marker: Default::default(), + } + .render() + .unwrap(), + ), + _ => HttpResponse::NotFound().content_type("text/html").finish(), + } +} diff --git a/src/main.rs b/src/main.rs index 6b2c8f4..9f12d4b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,331 +1,49 @@ extern crate core; +use crate::args::ARGS; +use crate::endpoints::{ + create, edit, errors, help, pasta as pasta_endpoint, pastalist, remove, static_resources, +}; +use crate::pasta::Pasta; +use crate::util::dbio; +use actix_web::middleware::Condition; +use actix_web::{middleware, web, App, HttpServer}; +use actix_web_httpauth::middleware::HttpAuthentication; +use chrono::Local; use env_logger::Builder; +use log::LevelFilter; +use std::fs; use std::io::Write; use std::sync::Mutex; -use std::time::{SystemTime, UNIX_EPOCH}; -use actix_files; -use actix_multipart::Multipart; -use actix_web::dev::ServiceRequest; -use actix_web::middleware::Condition; -use actix_web::{error, get, middleware, web, App, Error, HttpResponse, HttpServer, Responder}; -use actix_web_httpauth::extractors::basic::BasicAuth; -use actix_web_httpauth::middleware::HttpAuthentication; -use askama::Template; -use chrono::Local; -use clap::Parser; -use futures::TryStreamExt as _; -use lazy_static::lazy_static; -use linkify::{LinkFinder, LinkKind}; -use log::LevelFilter; -use rand::Rng; -use std::fs; +pub mod args; +pub mod pasta; -use crate::animalnumbers::{to_animal_names, to_u64}; -use crate::dbio::save_to_file; -use crate::pasta::Pasta; - -mod animalnumbers; -mod dbio; -mod pasta; - -lazy_static! { - static ref ARGS: Args = Args::parse(); +pub mod util { + pub mod animalnumbers; + pub mod auth; + pub mod dbio; + pub mod misc; + pub mod syntaxhighlighter; } -struct AppState { - pastas: Mutex>, +pub mod endpoints { + pub mod create; + pub mod edit; + pub mod errors; + pub mod help; + pub mod pasta; + pub mod pastalist; + pub mod remove; + pub mod static_resources; } -#[derive(Parser, Debug, Clone)] -#[clap(author, version, about, long_about = None)] -struct Args { - #[clap(short, long, default_value_t = 8080)] - port: u32, - - #[clap(short, long, default_value_t = 1)] - threads: u8, - - #[clap(long)] - hide_header: bool, - - #[clap(long)] - hide_footer: bool, - - #[clap(long)] - pure_html: bool, - - #[clap(long)] - no_listing: bool, - - #[clap(long)] - auth_username: Option, - - #[clap(long)] - auth_password: Option, -} - -async fn auth_validator( - req: ServiceRequest, - credentials: BasicAuth, -) -> Result { - // check if username matches - if credentials.user_id().as_ref() == ARGS.auth_username.as_ref().unwrap() { - return match ARGS.auth_password.as_ref() { - Some(cred_pass) => match credentials.password() { - None => Err(error::ErrorBadRequest("Invalid login details.")), - Some(arg_pass) => { - if arg_pass == cred_pass { - Ok(req) - } else { - Err(error::ErrorBadRequest("Invalid login details.")) - } - } - }, - None => Ok(req), - }; - } else { - Err(error::ErrorBadRequest("Invalid login details.")) - } -} - -#[derive(Template)] -#[template(path = "index.html")] -struct IndexTemplate<'a> { - args: &'a Args, -} - -#[derive(Template)] -#[template(path = "error.html")] -struct ErrorTemplate<'a> { - args: &'a Args, -} - -#[derive(Template)] -#[template(path = "pasta.html")] -struct PastaTemplate<'a> { - pasta: &'a Pasta, - args: &'a Args, -} - -#[derive(Template)] -#[template(path = "pastalist.html")] -struct PastaListTemplate<'a> { - pastas: &'a Vec, - args: &'a Args, -} - -#[get("/")] -async fn index() -> impl Responder { - HttpResponse::Found() - .content_type("text/html") - .body(IndexTemplate { args: &ARGS }.render().unwrap()) -} - -async fn not_found() -> Result { - Ok(HttpResponse::Found() - .content_type("text/html") - .body(ErrorTemplate { args: &ARGS }.render().unwrap())) -} - -async fn create(data: web::Data, mut payload: Multipart) -> Result { - let mut pastas = data.pastas.lock().unwrap(); - - let timenow: i64 = match SystemTime::now().duration_since(UNIX_EPOCH) { - Ok(n) => n.as_secs(), - Err(_) => panic!("SystemTime before UNIX EPOCH!"), - } as i64; - - let mut new_pasta = Pasta { - id: rand::thread_rng().gen::() as u64, - content: String::from("No Text Content"), - file: String::from("no-file"), - created: timenow, - pasta_type: String::from(""), - expiration: 0, - }; - - while let Some(mut field) = payload.try_next().await? { - match field.name() { - "expiration" => { - while let Some(chunk) = field.try_next().await? { - new_pasta.expiration = match std::str::from_utf8(&chunk).unwrap() { - "1min" => timenow + 60, - "10min" => timenow + 60 * 10, - "1hour" => timenow + 60 * 60, - "24hour" => timenow + 60 * 60 * 24, - "1week" => timenow + 60 * 60 * 24 * 7, - "never" => 0, - _ => panic!("Unexpected expiration time!"), - }; - } - - continue; - } - "content" => { - while let Some(chunk) = field.try_next().await? { - new_pasta.content = std::str::from_utf8(&chunk).unwrap().to_string(); - new_pasta.pasta_type = if is_valid_url(new_pasta.content.as_str()) { - String::from("url") - } else { - String::from("text") - }; - } - continue; - } - "file" => { - let content_disposition = field.content_disposition(); - - let filename = match content_disposition.get_filename() { - Some("") => continue, - Some(filename) => filename.replace(' ', "_").to_string(), - None => continue, - }; - - std::fs::create_dir_all(format!("./pasta_data/{}", &new_pasta.id_as_animals())) - .unwrap(); - - let filepath = format!("./pasta_data/{}/{}", &new_pasta.id_as_animals(), &filename); - - new_pasta.file = filename; - - let mut f = web::block(|| std::fs::File::create(filepath)).await??; - - while let Some(chunk) = field.try_next().await? { - f = web::block(move || f.write_all(&chunk).map(|_| f)).await??; - } - - new_pasta.pasta_type = String::from("text"); - } - _ => {} - } - } - - let id = new_pasta.id; - - pastas.push(new_pasta); - - save_to_file(&pastas); - - Ok(HttpResponse::Found() - .append_header(("Location", format!("/pasta/{}", to_animal_names(id)))) - .finish()) -} - -#[get("/pasta/{id}")] -async fn getpasta(data: web::Data, id: web::Path) -> HttpResponse { - let mut pastas = data.pastas.lock().unwrap(); - - let id = to_u64(&*id.into_inner()); - - remove_expired(&mut pastas); - - for pasta in pastas.iter() { - if pasta.id == id { - return HttpResponse::Found() - .content_type("text/html") - .body(PastaTemplate { pasta, args: &ARGS }.render().unwrap()); - } - } - - HttpResponse::Found() - .content_type("text/html") - .body(ErrorTemplate { args: &ARGS }.render().unwrap()) -} - -#[get("/url/{id}")] -async fn redirecturl(data: web::Data, id: web::Path) -> HttpResponse { - let mut pastas = data.pastas.lock().unwrap(); - - let id = to_u64(&*id.into_inner()); - - remove_expired(&mut pastas); - - for pasta in pastas.iter() { - if pasta.id == id { - if pasta.pasta_type == "url" { - return HttpResponse::Found() - .append_header(("Location", String::from(&pasta.content))) - .finish(); - } else { - return HttpResponse::Found() - .content_type("text/html") - .body(ErrorTemplate { args: &ARGS }.render().unwrap()); - } - } - } - - HttpResponse::Found() - .content_type("text/html") - .body(ErrorTemplate { args: &ARGS }.render().unwrap()) -} - -#[get("/raw/{id}")] -async fn getrawpasta(data: web::Data, id: web::Path) -> String { - let mut pastas = data.pastas.lock().unwrap(); - - let id = to_u64(&*id.into_inner()); - - remove_expired(&mut pastas); - - for pasta in pastas.iter() { - if pasta.id == id { - return pasta.content.to_owned(); - } - } - - String::from("Pasta not found! :-(") -} - -#[get("/remove/{id}")] -async fn remove(data: web::Data, id: web::Path) -> HttpResponse { - let mut pastas = data.pastas.lock().unwrap(); - - let id = to_u64(&*id.into_inner()); - - remove_expired(&mut pastas); - - for (i, pasta) in pastas.iter().enumerate() { - if pasta.id == id { - pastas.remove(i); - return HttpResponse::Found() - .append_header(("Location", "/pastalist")) - .finish(); - } - } - - HttpResponse::Found() - .content_type("text/html") - .body(ErrorTemplate { args: &ARGS }.render().unwrap()) -} - -#[get("/pastalist")] -async fn list(data: web::Data) -> HttpResponse { - if ARGS.no_listing { - return HttpResponse::Found() - .append_header(("Location", "/")) - .finish(); - } - - let mut pastas = data.pastas.lock().unwrap(); - - remove_expired(&mut pastas); - - HttpResponse::Found().content_type("text/html").body( - PastaListTemplate { - pastas: &pastas, - args: &ARGS, - } - .render() - .unwrap(), - ) +pub struct AppState { + pub pastas: Mutex>, } #[actix_web::main] async fn main() -> std::io::Result<()> { - let args: Args = Args::parse(); - Builder::new() .format(|buf, record| { writeln!( @@ -341,10 +59,10 @@ async fn main() -> std::io::Result<()> { log::info!( "MicroBin starting on http://127.0.0.1:{}", - args.port.to_string() + ARGS.port.to_string() ); - match std::fs::create_dir_all("./pasta_data") { + match fs::create_dir_all("./pasta_data") { Ok(dir) => dir, Err(error) => { log::error!("Couldn't create data directory ./pasta_data: {:?}", error); @@ -360,53 +78,27 @@ async fn main() -> std::io::Result<()> { App::new() .app_data(data.clone()) .wrap(middleware::NormalizePath::trim()) - .service(index) - .service(getpasta) - .service(redirecturl) - .service(getrawpasta) - .service(actix_files::Files::new("/static", "./static")) + .service(create::index) + .service(help::help) + .service(pasta_endpoint::getpasta) + .service(pasta_endpoint::getrawpasta) + .service(pasta_endpoint::redirecturl) + .service(edit::get_edit) + .service(edit::post_edit) + .service(static_resources::static_resources) .service(actix_files::Files::new("/file", "./pasta_data")) - .service(web::resource("/upload").route(web::post().to(create))) - .default_service(web::route().to(not_found)) + .service(web::resource("/upload").route(web::post().to(create::create))) + .default_service(web::route().to(errors::not_found)) .wrap(middleware::Logger::default()) - .service(remove) - .service(list) + .service(remove::remove) + .service(pastalist::list) .wrap(Condition::new( - args.auth_username.is_some(), - HttpAuthentication::basic(auth_validator), + ARGS.auth_username.is_some(), + HttpAuthentication::basic(util::auth::auth_validator), )) }) - .bind(format!("0.0.0.0:{}", args.port.to_string()))? - .workers(args.threads as usize) + .bind(format!("0.0.0.0:{}", ARGS.port.to_string()))? + .workers(ARGS.threads as usize) .run() .await } - -fn remove_expired(pastas: &mut Vec) { - // get current time - this will be needed to check which pastas have expired - let timenow: i64 = match SystemTime::now().duration_since(UNIX_EPOCH) { - Ok(n) => n.as_secs(), - Err(_) => panic!("SystemTime before UNIX EPOCH!"), - } as i64; - - pastas.retain(|p| { - // expiration is `never` or not reached - if p.expiration == 0 || p.expiration > timenow { - // keep - true - } else { - // remove the file itself - fs::remove_file(format!("./pasta_data/{}/{}", p.id_as_animals(), p.file)); - // and remove the containing directory - fs::remove_dir(format!("./pasta_data/{}/", p.id_as_animals())); - // remove - false - } - }); -} - -fn is_valid_url(url: &str) -> bool { - let finder = LinkFinder::new(); - let spans: Vec<_> = finder.spans(url).collect(); - spans[0].as_str() == url && Some(&LinkKind::Url) == spans[0].kind() -} diff --git a/src/pasta.rs b/src/pasta.rs index 4f67823..66cd342 100644 --- a/src/pasta.rs +++ b/src/pasta.rs @@ -3,13 +3,17 @@ use std::fmt; use chrono::{DateTime, Datelike, NaiveDateTime, Timelike, Utc}; use serde::{Deserialize, Serialize}; -use crate::to_animal_names; +use crate::util::animalnumbers::to_animal_names; +use crate::util::syntaxhighlighter::html_highlight; #[derive(Serialize, Deserialize)] pub struct Pasta { pub id: u64, pub content: String, pub file: String, + pub extension: String, + pub private: bool, + pub editable: bool, pub created: i64, pub expiration: i64, pub pasta_type: String, @@ -46,6 +50,14 @@ impl Pasta { ) } } + + pub fn content_syntax_highlighted(&self) -> String { + html_highlight(&self.content, &self.extension) + } + + pub fn content_not_highlighted(&self) -> String { + html_highlight(&self.content, "txt") + } } impl fmt::Display for Pasta { diff --git a/src/animalnumbers.rs b/src/util/animalnumbers.rs similarity index 77% rename from src/animalnumbers.rs rename to src/util/animalnumbers.rs index a94e702..29e5094 100644 --- a/src/animalnumbers.rs +++ b/src/util/animalnumbers.rs @@ -14,8 +14,8 @@ pub fn to_animal_names(mut number: u64) -> String { return ANIMAL_NAMES[0].parse().unwrap(); } - // max 4 animals so 6 * 6 = 64 bits let mut power = 6; + loop { let digit = number / ANIMAL_NAMES.len().pow(power) as u64; if !(result.is_empty() && digit == 0) { @@ -32,7 +32,7 @@ pub fn to_animal_names(mut number: u64) -> String { result.join("-") } -pub fn to_u64(animal_names: &str) -> u64 { +pub fn to_u64(animal_names: &str) -> Result { let mut result: u64 = 0; let animals: Vec<&str> = animal_names.split("-").collect(); @@ -40,9 +40,14 @@ pub fn to_u64(animal_names: &str) -> u64 { let mut pow = animals.len(); for i in 0..animals.len() { pow -= 1; - result += (ANIMAL_NAMES.iter().position(|&r| r == animals[i]).unwrap() - * ANIMAL_NAMES.len().pow(pow as u32)) as u64; + let animal_index = ANIMAL_NAMES.iter().position(|&r| r == animals[i]); + match animal_index { + None => return Err("Failed to convert animal name to u64!"), + Some(_) => { + result += (animal_index.unwrap() * ANIMAL_NAMES.len().pow(pow as u32)) as u64 + } + } } - result + Ok(result) } diff --git a/src/util/auth.rs b/src/util/auth.rs new file mode 100644 index 0000000..4d554d1 --- /dev/null +++ b/src/util/auth.rs @@ -0,0 +1,29 @@ +use actix_web::dev::ServiceRequest; +use actix_web::{error, Error}; +use actix_web_httpauth::extractors::basic::BasicAuth; + +use crate::args::ARGS; + +pub async fn auth_validator( + req: ServiceRequest, + credentials: BasicAuth, +) -> Result { + // check if username matches + if credentials.user_id().as_ref() == ARGS.auth_username.as_ref().unwrap() { + return match ARGS.auth_password.as_ref() { + Some(cred_pass) => match credentials.password() { + None => Err(error::ErrorBadRequest("Invalid login details.")), + Some(arg_pass) => { + if arg_pass == cred_pass { + Ok(req) + } else { + Err(error::ErrorBadRequest("Invalid login details.")) + } + } + }, + None => Ok(req), + }; + } else { + Err(error::ErrorBadRequest("Invalid login details.")) + } +} diff --git a/src/dbio.rs b/src/util/dbio.rs similarity index 91% rename from src/dbio.rs rename to src/util/dbio.rs index ef167cc..12dff06 100644 --- a/src/dbio.rs +++ b/src/util/dbio.rs @@ -39,7 +39,10 @@ pub fn load_from_file() -> io::Result> { match file { Ok(_) => { let reader = BufReader::new(file.unwrap()); - let data: Vec = serde_json::from_reader(reader).unwrap(); + let data: Vec = match serde_json::from_reader(reader) { + Ok(t) => t, + _ => Vec::new(), + }; Ok(data) } Err(_) => { diff --git a/src/util/misc.rs b/src/util/misc.rs new file mode 100644 index 0000000..233f048 --- /dev/null +++ b/src/util/misc.rs @@ -0,0 +1,42 @@ +use std::time::{SystemTime, UNIX_EPOCH}; + +use linkify::{LinkFinder, LinkKind}; +use std::fs; + +use crate::Pasta; + +pub fn remove_expired(pastas: &mut Vec) { + // get current time - this will be needed to check which pastas have expired + let timenow: i64 = match SystemTime::now().duration_since(UNIX_EPOCH) { + Ok(n) => n.as_secs(), + Err(_) => { + log::error!("SystemTime before UNIX EPOCH!"); + 0 + } + } as i64; + + pastas.retain(|p| { + // expiration is `never` or not reached + if p.expiration == 0 || p.expiration > timenow { + // keep + true + } else { + // remove the file itself + fs::remove_file(format!("./pasta_data/{}/{}", p.id_as_animals(), p.file)) + .expect(&*format!("Failed to delete file {}!", p.file)); + // and remove the containing directory + fs::remove_dir(format!("./pasta_data/{}/", p.id_as_animals())).expect(&*format!( + "Failed to delete directory {}!", + p.id_as_animals() + )); + // remove + false + } + }); +} + +pub fn is_valid_url(url: &str) -> bool { + let finder = LinkFinder::new(); + let spans: Vec<_> = finder.spans(url).collect(); + spans[0].as_str() == url && Some(&LinkKind::Url) == spans[0].kind() +} diff --git a/src/util/syntaxhighlighter.rs b/src/util/syntaxhighlighter.rs new file mode 100644 index 0000000..4b3f2a2 --- /dev/null +++ b/src/util/syntaxhighlighter.rs @@ -0,0 +1,37 @@ +use syntect::easy::HighlightLines; +use syntect::highlighting::{Style, ThemeSet}; +use syntect::html::append_highlighted_html_for_styled_line; +use syntect::html::IncludeBackground::No; +use syntect::parsing::SyntaxSet; +use syntect::util::LinesWithEndings; + +pub fn html_highlight(text: &str, extension: &str) -> String { + let ps = SyntaxSet::load_defaults_newlines(); + let ts = ThemeSet::load_defaults(); + + let syntax = ps + .find_syntax_by_extension(extension) + .or(Option::from(ps.find_syntax_plain_text())) + .unwrap(); + let mut h = HighlightLines::new(syntax, &ts.themes["InspiredGitHub"]); + + let mut highlighted_content: String = String::from(""); + + for line in LinesWithEndings::from(text) { + let ranges: Vec<(Style, &str)> = h.highlight_line(line, &ps).unwrap(); + append_highlighted_html_for_styled_line(&ranges[..], No, &mut highlighted_content) + .expect("Failed to append highlighted line!"); + } + + let mut highlighted_content2: String = String::from(""); + for line in highlighted_content.lines() { + highlighted_content2 += &*format!("{}\n", line); + } + + // Rewrite colours to ones that are compatible with water.css and both light/dark modes + highlighted_content2 = highlighted_content2.replace("style=\"color:#323232;\"", ""); + highlighted_content2 = + highlighted_content2.replace("style=\"color:#183691;\"", "style=\"color:blue;\""); + + return highlighted_content2; +} diff --git a/templates/edit.html b/templates/edit.html new file mode 100644 index 0000000..fe47b34 --- /dev/null +++ b/templates/edit.html @@ -0,0 +1,20 @@ +{% include "header.html" %} +
+

+ Editing pasta '{{ pasta.id_as_animals() }}' +

+ +
+ +
+ + {% if args.readonly %} + + {%- else %} + + {%- endif %} + + +
+
+{% include "footer.html" %} diff --git a/templates/footer.html b/templates/footer.html index 0b59f3d..d705401 100644 --- a/templates/footer.html +++ b/templates/footer.html @@ -3,8 +3,12 @@

- MicroBin by Daniel Szabo. Fork me on GitHub! - Let's keep the Web compact, accessible and humane! + {% if args.footer_text.as_ref().is_none() %} + MicroBin by Dániel Szabó. Fork me on GitHub! + Let's keep the Web compact, accessible and humane! + {%- else %} + {{ args.footer_text.as_ref().unwrap() }} + {%- endif %}

{%- endif %} diff --git a/templates/header.html b/templates/header.html index 7c0b7bc..885ad35 100644 --- a/templates/header.html +++ b/templates/header.html @@ -1,35 +1,59 @@ - MicroBin + {% if args.footer_text.as_ref().is_none() %} + MicroBin + {%- else %} + {{ args.title.as_ref().unwrap() }} + {%- endif %} + {% if !args.pure_html %} {%- endif %} +{% if args.wide %} - +{%- else %} + +{%- endif %}
{% if !args.hide_header %} - μ MicroBin + + {% if !args.hide_logo %} + μ + {%- endif %} + + {% if args.footer_text.as_ref().is_none() %} + MicroBin + {%- else %} + {{ args.title.as_ref().unwrap() }} + {%- endif %} New Pasta Pasta List -GitHub - +Help +
{%- endif %} diff --git a/templates/help.html b/templates/help.html new file mode 100644 index 0000000..bcc5d58 --- /dev/null +++ b/templates/help.html @@ -0,0 +1,153 @@ +{% include "header.html" %} + + +

Welcome to MicroBin!

+

This page contains help regarding the installation, configuration and use of MicroBin. If you have questions that are not answered here, head to our GitHub repository.

+

1 Usage

+

What is a "pasta" anyway?

+

In microbin, a pasta can be:

+
    +
  • A text that you want to paste from one machine to another, eg. some code
  • +
  • A file that you want to share, eg. a video that is too large for Discord, a zip with a code project in it or an image
  • +
  • A URL redirect
  • +
+

When is MicroBin useful?

+

You can use MicroBin

+
    +
  • As a URL shortener/redirect service,
  • +
  • To send long texts to other people,
  • +
  • To send large files to other people,
  • +
  • To serve content on the web, eg. configuration files for testing, images, or any other file content using the Raw functionality,
  • +
  • To move files between your desktop and a server you access from the console,
  • +
  • As a "postbox" service where people can upload their files or texts, but they cannot see or remove what others sent you - just disable the pastalist page
  • +
  • To take notes! Simply create an editable pasta.
  • +
+

...and many other things, why not get creative?

+

Creating a Pasta

+

Navigate to the root of your server, for example https://microbin.myserver.com/. This should show you a form where you will at the very least see an expiration selector, a file attachment input, a content text field and a green save button. Depending on your configuration there miight also be a syntax highlight selector, an editable checkbox and a private ceckbox.

+

Use the expiration dropdown to choose how long you want your pasta to exist. When the selected time has expired, it will be removed from the server. The content can be any text, including plain text, code, html, even a URL. A URL is a special case, because when you open the pasta again, it will redirect you to that URL instead of showing it as a text. Entering content is optional, and so is the file attachment. If you want, you can even submit a pasta completely empty.

+

You will be redirected to the URL of the pasta, which will end with a few animal names. If you remember those animals, you can simply type them in on another machine and open your pasta elsewhere.

+

If you have editable pastas enabled and you check the editable checkbox, then later on there will be an option to change the text content of your pasta. Selecting the private checkbox will simply prevent your pasta to show up on the pasta list page, if that is enabled.

+

If you have syntax higlighting enabled, then select your language from the dropdown, or leave it as none if you just want to upload plain with no highlighting.

+

Listing Pastas

+

If you have pasta listing enabled, then there is a pasta list option in the navigation bar, which will list all the pastas on the server in two groups: regular pastas and URL redirects (pastas containing nothing but a URL). If you have private pastas enabled, they will not show up here at all.

+

From the pasta list page, you will be able to view individual pastas by clicking on their animal identifiers on the lest, view their raw contrent by clicking on the Raw button, remove them, and if you have editable pastas enabled, then open them in edit view.

+

Use MicroBin from the console with cURL

+

Simple text Pasta: curl -d "expiration=10min&content=This is a test pasta" -X POST https://microbin.myserver.com/create

+

File contents: curl -d "expiration=10min&content=$( < mypastafile.txt )" -X POST https://microbin.myserver.com/create

+

Available expiration options: + 1min, 10min, 1hour, 24hour, 1week, never

+

Use cURL to read the pasta: curl https://microbin.myserver.com/rawpasta/fish-pony-crow,

+

or to download the pasta: curl https://microbin.myserver.com/rawpasta/fish-pony-crow > output.txt (use /file instead of /rawpasta to download attached file).

+

2 Installation

+

Building MicroBin

+

Simply clone the repository, build it with cargo build --release and run the microbin executable in the created target/release/ directory. It will start on port 8080. You can change the port with -p or --port CL arguments. For other arguments see the Wiki.

+
git clone https://github.com/szabodanika/microbin.git
+cd microbin
+cargo build --release
+./target/release/microbin -p 80
+

MicroBin as a service

+

To install it as a service on your Linux machine, create a file called /etc/systemd/system/microbin.service, paste this into it with the [username] and [path to installation directory] replaced with the actual values.

+
[Unit]
+Description=MicroBin
+After=network.target
+
+[Service]
+Type=simple
+Restart=always
+User=[username]
+RootDirectory=/
+WorkingDirectory=[path to installation directory]
+ExecStart=[path to installation directory]/target/release/microbin
+
+[Install]
+WantedBy=multi-user.target
+

Here is my microbin.service for example, with some optional arguments:

+
[Unit]
+Description=MicroBin
+After=network.target
+
+[Service]
+Type=simple
+Restart=always
+User=ubuntu
+RootDirectory=/
+
+# This is the directory where I want to run microbin. It will store all the pastas here.
+WorkingDirectory=/home/ubuntu/server/microbin
+
+# This is the location of my executable - I also have 2 optional features enabled
+ExecStart=/home/ubuntu/server/microbin/target/release/microbin --editable --linenumbers --highlightsyntax
+
+# I keep my installation in the home directory, so I need to add this
+ProtectHome=off
+
+[Install]
+WantedBy=multi-user.target
+

Then start the service with systemctl start microbin and enable it on boot with systemctl enable microbin. To update your MicroBin, simply update or clone the repository again, build it again, and then restart the service with systemctl restart microbin. An update will never affect your existing pastas, unless there is a breaking change in the data model (in which case MicroBin just won't be able to import your DB), which will always be mentioned explicitly.

+

NGINX configuration

+
server {
+    # I have HTTPS enabled using certbot - you can use HTTP of course if you want!
+  listen 443 ssl; # managed by Certbot
+
+    server_name    microbin.myserver.com;
+
+    location / {
+            # Make sure to change the port if you are not running MicroBin at 8080!
+        proxy_pass            http://127.0.0.1:8080$request_uri;
+        proxy_set_header    Host $host;
+        proxy_set_header    X-Forwarded-Proto $scheme;
+        proxy_set_header    X-Real-IP $remote_addr;
+        proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
+    }
+
+    # Limit content size - I have 1GB because my MicroBin server is private, no one else will use it.
+    client_max_body_size 1024M;
+
+  ssl_certificate /etc/letsencrypt/live/microbin.myserver.com/fullchain.pem; # managed by Certbot
+  ssl_certificate_key /etc/letsencrypt/live/microbin.myserver.com/privkey.pem; # managed by Certbot
+  include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
+  ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
+}
+

3 Command Line Arguments

+

There is an ever expanding list of customisations built into MicroBin so you can use it the way you want. Instead of a configuration file, we simply use arguments that you pass to the executable, making the workflow even simpler. Read the following options and if you cannot find what you need, you can always open an issue at our GitHub repository and request a new feature!

+

--auth-username [AUTH_USERNAME]

+

Require username for HTTP Basic Authentication when visiting the service. If --auth-username is set but --auth-password is not, just leave the password field empty when logging in. You can also just go to https://username:password@yourserver.net or https://username@yourserver.net if password is not set instead of typing into the password

+

--auth-password [AUTH_PASSWORD]

+

Require password for HTTP Basic Authentication when visiting the service. Will not have any affect unless --auth-username is also set. If --auth-username is set but --auth-password is not, just leave the password field empty when logging in. You can also just go to https://username:password@yourserver.net or https://username@yourserver.net if password is not set instead of typing into the password prompt.

+

--editable

+

Enables editable pastas. You will still be able to make finalised pastas but there will be an extra checkbox to make your new pasta editable from the pasta list or the pasta view page.

+ +

Replaces the default footer text with your own. If you want to hide the footer, use --hide-footer instead.

+

-h, --help

+

Show all commands in the terminal.

+ +

Hides the footer on every page.

+

--hide-header

+

Hides the navigation bar on every page.

+ +

Hides the MicroBin logo from the navigation bar on every page.

+

--no-listing

+

Disables the /pastalist endpoint, essentially making all pastas private.

+

--highlightsyntax

+

Enables syntax highlighting support. When creating a new pasta, a new dropdown selector will be added where you can select your pasta's syntax, or just leave it empty for no highlighting.

+

-p, --port [PORT]

+

Default value: 8080

+

Sets the port for the server will be listening on.

+

--private

+

Enables private pastas. Adds a new checkbox to make your pasta private, which then won't show up on the pastalist page. With the URL to your pasta, it will still be accessible.

+

--pure-html

+

Disables main CSS styling, just uses a few in-line stylings for the layout. With this option you will lose dark-mode support.

+

--readonly

+

Disables adding/editing/removing pastas entirely.

+

--title [TITLE]

+

Replaces "MicroBin" with your title of choice in the navigation bar.

+

-t, --threads [THREADS]

+

Default value: 1

+

Number of workers MicroBin is allowed to have. Increase this to the number of CPU cores you have if you want to go beast mode, but for personal use one worker is enough.

+

-V, --version

+

Displays your MicroBin's version information.

+

--wide

+

Changes the maximum width of the UI from 720 pixels to 1080 pixels.

+ +{% include "footer.html" %} diff --git a/templates/index.html b/templates/index.html index 848d274..e1c4ef7 100644 --- a/templates/index.html +++ b/templates/index.html @@ -1,27 +1,99 @@ {% include "header.html" %}

-
- -
+
+
+
+ +
+ {% if args.highlightsyntax %} +
+
+ +
+ {%- else %} + + {%- endif %} + +
+ +
+ +
+


- -
- -
- +
+ {% if args.editable %} +
+ + +
+ {%- endif %} + {% if args.private %} +
+ + +
+ {%- endif %} +
+ + {% if args.readonly %} + + {%- else %} + + {%- endif %} + +
{% include "footer.html" %} diff --git a/templates/pasta.html b/templates/pasta.html index 4701c2a..f868520 100644 --- a/templates/pasta.html +++ b/templates/pasta.html @@ -1,9 +1,44 @@ {% include "header.html" %} -Raw Text Content +Raw Text Content {% if pasta.file != "no-file" %} -Attached file '{{pasta.file}}' +Attached file + '{{pasta.file}}' +{%- endif %} +{% if pasta.editable %} +Edit {%- endif %} Remove -
{{pasta}}
+{% if args.highlightsyntax %} +
{{pasta.content_syntax_highlighted()}}
+{%- else %} +
{{pasta.content_not_highlighted()}}
+{%- endif %} + + {% include "footer.html" %} diff --git a/templates/pastalist.html b/templates/pastalist.html index f380763..3b1c525 100644 --- a/templates/pastalist.html +++ b/templates/pastalist.html @@ -4,97 +4,111 @@ {% if pastas.is_empty() %}

- No pastas yet. 😔 Create one here. + No pastas yet. 😔 Create one here.


{%- else %}
+{% if args.pure_html %} + +{% else %}
- + {% endif %} + - + - - - - + + + + - - + + {% for pasta in pastas %} {% if pasta.pasta_type == "text" %} - - - - + + + + {%- endif %} {% endfor %} - +
PastasPastas
- Key - - Created - - Expiration - + + Key + + Created + + Expiration + -
- {{pasta.id_as_animals()}} - - {{pasta.created_as_string()}} - - {{pasta.expiration_as_string()}} - - Raw - {% if pasta.file != "no-file" %} - File - {%- endif %} - Remove - + {{pasta.id_as_animals()}} + + {{pasta.created_as_string()}} + + {{pasta.expiration_as_string()}} + + Raw + {% if pasta.file != "no-file" %} + File + {%- endif %} + {% if pasta.editable %} + Edit + {%- endif %} + Remove +

- - +{% if args.pure_html %} +
+{% else %} +
+{% endif %} + - + - - - - - + + + + + - - {% for pasta in pastas %} - {% if pasta.pasta_type == "url" %} - - - - - - - {%- endif %} - {% endfor %} - + + {% for pasta in pastas %} + {% if pasta.pasta_type == "url" %} + + + + + + + {%- endif %} + {% endfor %} +
URL RedirectsURL Redirects
- Key - - Created - - Expiration - +
+ Key + + Created + + Expiration + -
- {{pasta.id_as_animals()}} - - {{pasta.created_as_string()}} - - {{pasta.expiration_as_string()}} - - Raw - Remove -
+ {{pasta.id_as_animals()}} + + {{pasta.created_as_string()}} + + {{pasta.expiration_as_string()}} + + Raw + {% if pasta.editable %} + Edit + {%- endif %} + Remove +

{%- endif %} diff --git a/static/water.css b/templates/water.css similarity index 100% rename from static/water.css rename to templates/water.css