/server/server.pl
#!/usr/bin/perl
use Mojolicious::Lite;
use AnyEvent;
use AnyEvent::XMPP;
use JSON;

use ChatNoir::Client;

use strict;
use v5.10;

my $json = JSON->new->utf8;
my %clients;

websocket '/ws/#jid' => sub {
    my $c = shift;
    my $jid = $c->stash('jid');

    $c->inactivity_timeout(300);
    $c->rendered(101);

    if (!$clients{$jid}) {
        $clients{$jid} = ChatNoir::Client->new({jid => $jid, app => $c->app});
        $c->app->log->debug((scalar keys %clients) . " clients active");
    }
    $clients{$jid}->attach(controller => $c);
    $c->on(finish => sub {
        if (!$clients{$jid}->xmpp || !$clients{$jid}->xmpp->is_connected) {
            # Destroy a disconnected client
            delete $clients{$jid};
            $c->app->log->debug((scalar keys %clients) . " clients active");
        }
    });
};

if (app->mode eq 'development') {
    push @{app->static->paths}, '../client/';

    get '/client/' => sub {
        my $c = shift;
        $c->reply->static('debug.html');
    };

    get '/client/*path' => sub {
        my $c = shift;
        $c->reply->static($c->stash('path'));
    };
}

app->start;