Commit 00014224 authored by Sebastian Dröge's avatar Sebastian Dröge
Browse files

Hook up Rooms actor, and Subscriber/Publisher actors via WebSocket handshake

parent 71e64df3
Loading
Loading
Loading
Loading
+29 −3
Original line number Diff line number Diff line
@@ -3,9 +3,14 @@
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>

use crate::config::Config;
use crate::publisher::Publisher;
use crate::rooms::Rooms;
use crate::subscriber::Subscriber;

use actix::{Actor, Addr};
use actix_files::NamedFile;
use actix_web::{web, App, HttpRequest, HttpResponse, HttpServer, Responder};
use actix_web_actors::ws;

async fn index(cfg: web::Data<Config>) -> Result<NamedFile, actix_web::Error> {
    let full_path = cfg.static_files.join("index.html");
@@ -15,8 +20,26 @@ async fn index(cfg: web::Data<Config>) -> Result<NamedFile, actix_web::Error> {
    Ok(file.use_last_modified(true))
}

async fn ws(_cfg: web::Data<Config>) -> impl Responder {
    HttpResponse::Ok().body("Hello world!")
async fn ws(
    cfg: web::Data<Config>,
    rooms: web::Data<Addr<Rooms>>,
    path: web::Path<String>,
    req: HttpRequest,
    stream: web::Payload,
) -> impl Responder {
    match path.as_str() {
        "publish" => ws::start(
            Publisher::new(cfg.into_inner(), rooms.as_ref().clone()),
            &req,
            stream,
        ),
        "subscribe" => ws::start(
            Subscriber::new(cfg.into_inner(), rooms.as_ref().clone()),
            &req,
            stream,
        ),
        _ => Ok(HttpResponse::NotFound().finish()),
    }
}

async fn static_file(
@@ -32,14 +55,17 @@ async fn static_file(
}

pub async fn run(cfg: Config) -> Result<(), anyhow::Error> {
    let rooms = Rooms::new().start();

    let cfg = web::Data::new(cfg);
    let cfg_clone = cfg.clone();

    let server = HttpServer::new(move || {
        App::new()
            .app_data(cfg_clone.clone())
            .data(rooms.clone())
            .route("/", web::get().to(index))
            .route("/ws", web::get().to(ws))
            .route("/ws/{mode:(publish|subscribe)}", web::get().to(ws))
            .route("/static/{filename:.*}", web::get().to(static_file))
    });