qair 0.7.0

Send/receive files with builtin HTTP server and terminal QR code.
Documentation
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

//! HTTP server to send a file or to allow receiving file uploads.

extern crate hyper;
extern crate iron;
extern crate mount;
extern crate percent_encoding;
extern crate router;

mod not_shared;
mod receive;
mod serve_file;
mod serve_html;

use iron::error::HttpError;
use iron::method::Method;
use iron::Iron;
use router::Router;
use serve_html::ServeHtml;
use std::net::SocketAddr;
use std::path::PathBuf;

/// Starts a webserver.
///
/// When the return value is not an error, dropping the return value blocks and
/// keeps the webserver running.
///
/// # Parameters
/// * `port` - TCP port to listen to
/// * `receive` - Whether to serve an HTML upload form and accept the
///    client to upload files
/// * `send_file` - The file to send to clients. This is the file that is
///    served over HTTP.
pub fn start(
    port: u16,
    receive: bool,
    send_file: &Option<PathBuf>,
) -> Result<iron::Listening, HttpError> {
    let mut router = Router::new();

    // "defaults": can be overridden.
    router.route(
        Method::Get,
        "*",
        not_shared::not_shared_handler,
        "not_shared_files",
    );

    if receive {
        router.route(
            Method::Put,
            "/*",
            receive::upload_receive_handler,
            "upload_put",
        );
    }

    if let Some(path) = &send_file {
        let serve_file = serve_file::ServeFile::new(path.to_path_buf());
        router.route(Method::Get, "*", serve_file, "file");
    }

    let serve_html = ServeHtml::new(&send_file, receive);
    router.route(Method::Get, "/", serve_html, "index");

    let addr = SocketAddr::from(([0, 0, 0, 0], port));
    Iron::new(router).http(addr)
}