LasTres/lib/LasTres/Controller/Websocket.pm

78 lines
2.0 KiB
Perl
Raw Normal View History

2023-06-01 08:45:43 +02:00
package LasTres::Controller::Websocket;
use v5.36.0;
use strict;
use warnings;
2023-06-08 09:02:32 +02:00
use JSON qw/encode_json/;
use UUID::URandom qw/create_uuid_string/;
2023-06-01 08:45:43 +02:00
use Mojo::Base 'Mojolicious::Controller', -signatures;
2023-06-08 09:02:32 +02:00
use Data::Dumper;
use LasTres::Redis;
use LasTres::Controller::Websocket::InputPackets;
my %sessions;
use LasTres::DAO::PJs;
2023-06-08 09:02:32 +02:00
my $result_set_pjs = LasTres::DAO::PJs->ResultSet;
2023-06-01 08:45:43 +02:00
my $redis = LasTres::Redis->new;
2023-06-08 09:02:32 +02:00
my $input_packets = LasTres::Controller::Websocket::InputPackets->new;
sub ws ($self) {
2023-06-01 08:45:43 +02:00
my $user = $self->user;
2023-06-08 09:02:32 +02:00
if ( !defined $user ) {
2023-06-01 08:45:43 +02:00
return $self->render(
status => 401,
2023-06-08 09:02:32 +02:00
json => {
2023-06-01 08:45:43 +02:00
error => 'You are not logged in.',
}
);
}
2023-06-08 09:02:32 +02:00
my $session_uuid = create_uuid_string;
$sessions{$session_uuid} = {
user => $user,
controller => $self,
uuid => $session_uuid,
};
my $session = $sessions{$session_uuid};
$self->on(
json => sub ( $self, $hash ) {
$self->_handle_packet( $session, $hash );
}
);
$self->on(
finish => sub ( $self, $code, $reason ) {
delete $sessions{$session_uuid};
$reason ||= "No reason";
2023-06-08 09:02:32 +02:00
say STDERR
"Websocket for user @{[$user->username]} closed with status $code and reason $reason.";
}
);
}
{
2023-06-08 09:02:32 +02:00
sub _handle_packet ( $self, $session, $hash ) {
my $command = $hash->{command};
if ( !defined $command ) {
say STDERR "No command.";
$self->send( encode_json( { error => "No command" } ) );
return;
}
my $input_packet = $input_packets->hash->{$command};
2023-06-08 09:02:32 +02:00
if ( !defined $input_packet ) {
say STDERR "Unknown command $command.";
$self->send(
encode_json( { error => "Unknown command $command" } ) );
return;
}
my $data = $hash->{data};
return $input_packet->handle( $self, $session, $data );
2023-06-01 08:45:43 +02:00
}
}
1;