Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Switch to fast_qr lib #848

Merged
merged 20 commits into from
Sep 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 17 additions & 7 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ clap = { version = "3.2", features = ["derive", "cargo", "wrap_help"] }
clap_complete = "3.2.3"
clap_mangen = "0.1"
cyqsimon marked this conversation as resolved.
Show resolved Hide resolved
comrak = "0.14.0"
fast_qr = "0.3.1"
futures = "0.3"
get_if_addrs = "0.5"
hex = "0.4"
Expand All @@ -44,7 +45,6 @@ mime = "0.3"
nanoid = "0.4"
percent-encoding = "2"
port_check = "0.1"
qrcodegen = "1"
rustls = { version = "0.20", optional = true }
rustls-pemfile = { version = "1.0", optional = true }
serde = { version = "1", features = ["derive"] }
Expand Down Expand Up @@ -77,5 +77,9 @@ rstest = "0.15"
select = "0.5"
url = "2"

[target.'cfg(not(windows))'.dev-dependencies]
# fake_tty does not support Windows for now
fake-tty = "0.2.0"

[build-dependencies]
grass = "0.11"
4 changes: 1 addition & 3 deletions data/style.scss
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@ $themes: squirrel, archlinux, monokai, zenburn;
@return $s;
}



html {
font-smoothing: antialiased;
text-rendering: optimizeLegibility;
Expand Down Expand Up @@ -180,7 +178,7 @@ nav .qrcode {
background: var(--switch_theme_background);
}

nav .qrcode img {
nav .qrcode svg {
display: block;
}

Expand Down
7 changes: 7 additions & 0 deletions src/consts.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
use fast_qr::ECL;

/// The error correction level to use for all QR code generation.
pub const QR_EC_LEVEL: ECL = ECL::L;

/// The margin size for the SVG QR code on the webpage.
pub const SVG_QR_MARGIN: usize = 1;
56 changes: 8 additions & 48 deletions src/listing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ use actix_web::{HttpMessage, HttpRequest, HttpResponse};
use bytesize::ByteSize;
use comrak::{markdown_to_html, ComrakOptions};
use percent_encoding::{percent_decode_str, utf8_percent_encode};
use qrcodegen::{QrCode, QrCodeEcc};
use serde::Deserialize;
use strum_macros::{Display, EnumString};

Expand Down Expand Up @@ -38,7 +37,6 @@ pub struct QueryParameters {
pub order: Option<SortingOrder>,
pub raw: Option<bool>,
pub mkdir_name: Option<String>,
qrcode: Option<String>,
download: Option<ArchiveMethod>,
}

Expand Down Expand Up @@ -166,6 +164,12 @@ pub fn directory_listing(

let base = Path::new(serve_path);
let random_route_abs = format!("/{}", conf.route_prefix);
let abs_url = format!(
"{}://{}{}",
req.connection_info().scheme(),
req.connection_info().host(),
req.uri()
);
let is_root = base.parent().is_none() || Path::new(&req.path()) == Path::new(&random_route_abs);

let encoded_dir = match base.strip_prefix(random_route_abs) {
Expand Down Expand Up @@ -218,20 +222,6 @@ pub fn directory_listing(

let query_params = extract_query_parameters(req);

// If the `qrcode` parameter is included in the url, then should respond to the QR code
if let Some(url) = query_params.qrcode {
let res = match QrCode::encode_text(&url, QrCodeEcc::Medium) {
Ok(qr) => HttpResponse::Ok()
.append_header(("Content-Type", "image/svg+xml"))
.body(qr_to_svg_string(&qr, 2)),
Err(err) => {
log::error!("URL is invalid (too long?): {:?}", err);
HttpResponse::UriTooLong().finish()
}
};
return Ok(ServiceResponse::new(req.clone(), res));
}

let mut entries: Vec<Entry> = Vec::new();
let mut readme: Option<(String, String)> = None;

Expand Down Expand Up @@ -384,9 +374,10 @@ pub fn directory_listing(
renderer::page(
entries,
readme,
abs_url,
is_root,
query_params,
breadcrumbs,
&breadcrumbs,
&encoded_dir,
conf,
current_user,
Expand All @@ -407,34 +398,3 @@ pub fn extract_query_parameters(req: &HttpRequest) -> QueryParameters {
}
}
}

// Returns a string of SVG code for an image depicting
// the given QR Code, with the given number of border modules.
// The string always uses Unix newlines (\n), regardless of the platform.
fn qr_to_svg_string(qr: &QrCode, border: i32) -> String {
assert!(border >= 0, "Border must be non-negative");
let mut result = String::new();
result += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
result += "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n";
let dimension = qr
.size()
.checked_add(border.checked_mul(2).unwrap())
.unwrap();
result += &format!(
"<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" viewBox=\"0 0 {0} {0}\" stroke=\"none\">\n", dimension);
result += "\t<rect width=\"100%\" height=\"100%\" fill=\"#FFFFFF\"/>\n";
result += "\t<path d=\"";
for y in 0..qr.size() {
for x in 0..qr.size() {
if qr.get_module(x, y) {
if x != 0 || y != 0 {
result += " ";
}
result += &format!("M{},{}h1v1h-1z", x + border, y + border);
}
}
}
result += "\" fill=\"#000000\"/>\n";
result += "</svg>\n";
result
}
37 changes: 5 additions & 32 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,15 @@ use actix_web::{middleware, App, HttpRequest, HttpResponse};
use actix_web_httpauth::middleware::HttpAuthentication;
use anyhow::Result;
use clap::{crate_version, IntoApp, Parser};
use fast_qr::QRBuilder;
use log::{error, warn};
use qrcodegen::{QrCode, QrCodeEcc};
use yansi::{Color, Paint};

mod archive;
mod args;
mod auth;
mod config;
mod consts;
mod errors;
mod file_upload;
mod listing;
Expand Down Expand Up @@ -238,13 +239,13 @@ async fn run(miniserve_config: MiniserveConfig) -> Result<(), ContextualError> {
.iter()
.filter(|url| !url.contains("//127.0.0.1:") && !url.contains("//[::1]:"))
{
match QrCode::encode_text(url, QrCodeEcc::Low) {
match QRBuilder::new(url.clone()).ecl(consts::QR_EC_LEVEL).build() {
Ok(qr) => {
println!("QR code for {}:", Color::Green.paint(url).bold());
print_qr(&qr);
qr.print();
}
Err(e) => {
error!("Failed to render QR to terminal: {}", e);
error!("Failed to render QR to terminal: {:?}", e);
}
};
}
Expand Down Expand Up @@ -350,31 +351,3 @@ async fn css() -> impl Responder {
.insert_header(ContentType(mime::TEXT_CSS))
.body(css)
}

// Prints to the console two inverted QrCodes side by side.
fn print_qr(qr: &QrCode) {
let border = 4;
let size = qr.size() + 2 * border;

for y in (0..size).step_by(2) {
for x in 0..2 * size {
let inverted = x >= size;
let (x, y) = (x % size - border, y - border);

//each char represents two vertical modules
let (mod1, mod2) = match inverted {
false => (qr.get_module(x, y), qr.get_module(x, y + 1)),
true => (!qr.get_module(x, y), !qr.get_module(x, y + 1)),
};
let c = match (mod1, mod2) {
(false, false) => ' ',
(true, false) => '▀',
(false, true) => '▄',
(true, true) => '█',
};
print!("{0}", c);
}
println!();
}
println!();
}
Loading