From 9279e6388af1ecf12eda626f41b6d4c44cb45769 Mon Sep 17 00:00:00 2001 From: Sergiotarxz Date: Sat, 13 Jan 2024 01:17:57 +0100 Subject: [PATCH] Adding initial team support. --- Build.PL | 1 + js-src/conquer/index.ts | 111 ++++++++++-------- js-src/conquer/interface/node-view.ts | 14 ++- js-src/conquer/map-node.ts | 33 ++++++ js-src/conquer/team.ts | 71 +++++++++++ js-src/conquer/user.ts | 60 ++++++---- lib/BurguillosInfo.pm | 4 + lib/BurguillosInfo/Controller/ConquerNode.pm | 25 +++- lib/BurguillosInfo/Controller/ConquerTeam.pm | 57 +++++++++ lib/BurguillosInfo/DB/Migrations.pm | 15 ++- .../Schema/Result/ConquerNode.pm | 31 ++++- .../Schema/Result/ConquerTeam.pm | 53 +++++++++ .../Schema/Result/ConquerUser.pm | 23 ++-- public/js/bundle.js | 19 ++- 14 files changed, 426 insertions(+), 91 deletions(-) create mode 100644 js-src/conquer/team.ts create mode 100644 lib/BurguillosInfo/Controller/ConquerTeam.pm create mode 100644 lib/BurguillosInfo/Schema/Result/ConquerTeam.pm diff --git a/Build.PL b/Build.PL index bf88ecf..4066522 100755 --- a/Build.PL +++ b/Build.PL @@ -33,6 +33,7 @@ my $build = Module::Build->new( 'Crypt::Bcrypt' => 0, 'DBIx::Class::TimeStamp' => 0, 'DateTime::Format::HTTP' => 0, + 'GIS::Distance' => 0, }, ); $build->create_build_script; diff --git a/js-src/conquer/index.ts b/js-src/conquer/index.ts index 5978037..085a231 100644 --- a/js-src/conquer/index.ts +++ b/js-src/conquer/index.ts @@ -238,37 +238,46 @@ export default class Conquer { } } - private getNearbyNodes(): void { + private async getNearbyNodes(): Promise { const urlNodes = new URL('/conquer/node/near', window.location.protocol + '//' + window.location.hostname + ':' + window.location.port) - fetch(urlNodes).then(async (response) => { - let responseBody; - try { - responseBody = await response.json(); - } catch (error) { - console.error('Error parseando json: ' + responseBody); - console.error(error); - return; + let response; + try { + response = await fetch(urlNodes); + } catch (error) { + console.error(error); + return; + } + let responseBody; + try { + responseBody = await response.json(); + } catch (error) { + console.error('Error parseando json: ' + responseBody); + console.error(error); + return; + } + if (response.status !== 200) { + console.error(responseBody.error); + return; + } + const serverNodes: Record = {}; + const nodes = JsonSerializer.deserialize(responseBody, MapNode); + if (!(nodes instanceof Array)) { + console.error('Received null instead of node list.'); + return; + } + for (const node of nodes) { + if (!(node instanceof MapNode)) { + console.error('Received node is not a MapNode.'); + continue; } - if (response.status !== 200) { - console.error(responseBody.error); - return; - } - const serverNodes: Record = {}; - const nodes = JsonSerializer.deserialize(responseBody, MapNode); - if (!(nodes instanceof Array)) { - console.error('Received null instead of node list.'); - return; - } - for (const node of nodes) { - if (!(node instanceof MapNode)) { - console.error('Received node is not a MapNode.'); - continue; - } - serverNodes[node.getId()] = node; - } - this.serverNodes = serverNodes; - this.refreshLayers(); - }); + node.on('update-nodes', async () => { + await this.sendCoordinatesToServer(); + this.getNearbyNodes(); + }); + serverNodes[node.getId()] = node; + } + this.serverNodes = serverNodes; + this.refreshLayers(); } private createIntervalPollNearbyNodes(): void { @@ -284,29 +293,31 @@ export default class Conquer { }, 40000); } - private sendCoordinatesToServer(): void { + private async sendCoordinatesToServer(): Promise { const urlLog = new URL('/conquer/user/coordinates', window.location.protocol + '//' + window.location.hostname + ':' + window.location.port) - fetch(urlLog, { - method: 'POST', - body: JSON.stringify([ - this.coordinate_1, - this.coordinate_2, - ]), - }).then(async (res) => { - let responseBody; - try { - responseBody = await res.json(); - } catch(error) { - console.error('Error parseando json: ' + responseBody); - console.error(error); - return; - } - if (res.status !== 200) { - console.error(responseBody.error); - } - }).catch((error) => { + let res; + try { + res = await fetch(urlLog, { + method: 'POST', + body: JSON.stringify([ + this.coordinate_1, + this.coordinate_2, + ])}); + } catch (error) { console.error(error) - }); + return; + } + let responseBody; + try { + responseBody = await res.json(); + } catch(error) { + console.error('Error parseando json: ' + responseBody); + console.error(error); + return; + } + if (res.status !== 200) { + console.error(responseBody.error); + } } private runPreStartState(): void { diff --git a/js-src/conquer/interface/node-view.ts b/js-src/conquer/interface/node-view.ts index 7594d90..1405ee1 100644 --- a/js-src/conquer/interface/node-view.ts +++ b/js-src/conquer/interface/node-view.ts @@ -24,12 +24,22 @@ export default class NodeView extends AbstractTopBarInterface { super() this.node = node; } - public run() { + public async run() { const mainNode = this.getMainNode() + this.runCallbacks('update-nodes'); + try { + this.node = await this.node.fetch(); + } catch (error) { + this.runCallbacks('close'); + } const view = this.getNodeFromTemplateId('conquer-view-node-template') mainNode.append(view) this.getNodeNameH2().innerText = this.node.getName(); - this.getNodeDescriptionParagraph().innerText = this.node.getDescription(); + this.getNodeDescriptionParagraph().innerText = this.node.getDescription() + + "\n" + + (this.node.isNear() + ? 'Estas cerca y puedes interactuar con este sitio.' + : 'Estás demasiado lejos para hacer nada aquí.'); view.classList.remove('conquer-display-none') mainNode.classList.remove('conquer-display-none') } diff --git a/js-src/conquer/map-node.ts b/js-src/conquer/map-node.ts index 672d5de..1e25638 100644 --- a/js-src/conquer/map-node.ts +++ b/js-src/conquer/map-node.ts @@ -7,6 +7,7 @@ import Fill from 'ol/style/Fill' import Stroke from 'ol/style/Stroke' import InterfaceManager from '@burguillosinfo/conquer/interface-manager' import NodeView from '@burguillosinfo/conquer/interface/node-view' +import JsonSerializer from '@burguillosinfo/conquer/serializer'; @JsonObject() export default class MapNode { @@ -21,14 +22,42 @@ export default class MapNode { @JsonProperty() private name: string, @JsonProperty() private description: string, @JsonProperty() private kind: string, + @JsonProperty() private is_near: boolean, ) { } + public async fetch(): Promise { + const urlNode = new URL('/conquer/node/' + this.uuid, window.location.protocol + '//' + window.location.hostname + ':' + window.location.port) + const response = await fetch(urlNode); + let responseBody; + const errorThrow = new Error('Unable to fetch node updated.'); + try { + responseBody = await response.json(); + } catch (error) { + console.error('Error parseando json: ' + responseBody); + console.error(error); + throw errorThrow; + } + if (response.status !== 200) { + console.error(responseBody.error); + throw errorThrow; + } + const node = JsonSerializer.deserialize(responseBody, MapNode); + if (!(node instanceof MapNode)) { + console.error('Unexpected JSON value for MapNode.'); + throw errorThrow; + } + return node; + } + public click(interfaceManager: InterfaceManager): void { const viewNodeInterface = new NodeView(this); viewNodeInterface.on('close', () => { interfaceManager.remove(viewNodeInterface); }); + viewNodeInterface.on('update-nodes', () => { + this.runCallbacks('update-nodes'); + }); interfaceManager.push(viewNodeInterface); this.runCallbacks('click'); } @@ -53,6 +82,10 @@ export default class MapNode { public getType(): string { return this.type; } + + public isNear(): boolean { + return this.is_near; + } public getName(): string { return this.name; diff --git a/js-src/conquer/team.ts b/js-src/conquer/team.ts new file mode 100644 index 0000000..51ae027 --- /dev/null +++ b/js-src/conquer/team.ts @@ -0,0 +1,71 @@ +import JsonSerializer from '@burguillosinfo/conquer/serializer'; +import { JsonObject, JsonProperty } from 'typescript-json-serializer'; + +@JsonObject() +export default class ConquerTeam { + @JsonProperty() + private kind: string; + @JsonProperty() + private uuid: string; + @JsonProperty() + private name: string; + @JsonProperty() + private description: string; + @JsonProperty() + private points: number; + @JsonProperty() + private color: string; + + constructor(uuid: string, name: string, description: string, points: number, color: string) { + this.kind = 'ConquerTeam'; + this.uuid = uuid; + this.name = name; + this.description = description; + this.points = points; + this.color = color; + } + + public static async getTeam(uuid: string): Promise { + const urlTeam = new URL('/conquer/team/' + uuid, window.location.protocol + '//' + window.location.hostname + ':' + window.location.port) + try { + const response = await fetch(urlTeam) + if (response.status !== 200) { + throw new Error('Invalid response fetching team.') + } + const teamData = await response.json() + let team = JsonSerializer.deserialize(teamData, ConquerTeam); + if (team === undefined) { + team = null; + } + if (!(team instanceof ConquerTeam)) { + throw new Error('Unable to parse team.'); + } + return team; + } catch (error) { + console.error(error) + throw new Error('Unable to fetch Team.'); + } + } + + public static async getSelfTeam(): Promise { + const urlTeam = new URL('/conquer/user/team', window.location.protocol + '//' + window.location.hostname + ':' + window.location.port) + try { + const response = await fetch(urlTeam) + if (response.status !== 200) { + throw new Error('Invalid response fetching team.') + } + const teamData = await response.json() + let team = JsonSerializer.deserialize(teamData, ConquerTeam); + if (team === undefined) { + team = null; + } + if (team !== null && !(team instanceof ConquerTeam)) { + throw new Error('Unable to parse team.'); + } + return team; + } catch (error) { + console.error(error) + throw new Error('Unable to fetch Team.'); + } + } +} diff --git a/js-src/conquer/user.ts b/js-src/conquer/user.ts index 9c214b7..08ace3d 100644 --- a/js-src/conquer/user.ts +++ b/js-src/conquer/user.ts @@ -1,3 +1,7 @@ +import JsonSerializer from '@burguillosinfo/conquer/serializer'; +import { JsonObject, JsonProperty } from 'typescript-json-serializer'; +import ConquerTeam from '@burguillosinfo/conquer/team'; + export interface UserData { is_admin: number kind: string @@ -7,29 +11,37 @@ export interface UserData { uuid: string } +@JsonObject() export default class ConquerUser { - private _isAdmin = false - private kind = "ConquerUser" - private lastActivity: string | null = null - private registrationDate: string | null = null - private username: string | null = null - private uuid: string | null = null + @JsonProperty() + private is_admin: boolean; + @JsonProperty() + private kind: string; + @JsonProperty() + private last_activity: string | null; + @JsonProperty() + private registration_date: string | null; + @JsonProperty() + private username: string; + @JsonProperty() + private uuid: string; + @JsonProperty({name: 'team'}) + private team_uuid: string | null; - constructor(data: UserData) { - this.lastActivity = data.last_activity ?? null; - this.registrationDate = data.registration_date ?? null; - if (this.kind !== data.kind) { - throw new Error(`We cannot instance a user from a kind different to ${this.kind}.`) - } - this._isAdmin = !!data.is_admin || false - this.uuid = data.uuid - this.username = data.username - if (this.username === null || this.username === undefined) { - throw new Error('No username in user instance') - } - if (this.uuid === null || this.username === undefined) { - throw new Error('No uuid in user instance') + constructor(kind: string, uuid: string, username: string, is_admin = false, registration_date: string | null = null, last_activity: string | null = null) { + this.kind = kind; + this.uuid = uuid; + this.username = username; + this.is_admin = is_admin; + this.registration_date = registration_date; + this.last_activity = last_activity; + } + + public async getTeam(): Promise { + if (this.team_uuid === null) { + return null; } + return ConquerTeam.getTeam(this.team_uuid); } public static async getSelfUser(): Promise { @@ -40,7 +52,11 @@ export default class ConquerUser { throw new Error('Invalid response fetching user.') } const userData = await response.json() - return new ConquerUser(userData) + const user = JsonSerializer.deserialize(userData, ConquerUser); + if (!(user instanceof ConquerUser)) { + throw new Error('Unable to parse user.'); + } + return user; } catch (error) { console.error(error) return null @@ -53,6 +69,6 @@ export default class ConquerUser { return this.username } public isAdmin(): boolean { - return this._isAdmin + return this.is_admin } } diff --git a/lib/BurguillosInfo.pm b/lib/BurguillosInfo.pm index dfd8fd2..e75842d 100644 --- a/lib/BurguillosInfo.pm +++ b/lib/BurguillosInfo.pm @@ -7,6 +7,7 @@ use Mojo::Base 'Mojolicious', -signatures; # This method will run once at server start sub startup ($self) { my $metrics = BurguillosInfo::Controller::Metrics->new; + $self->sessions->default_expiration(0); $self->hook( around_dispatch => sub { my $next = shift; @@ -91,9 +92,12 @@ sub startup ($self) { $r->get('/stats')->to('Metrics#stats'); $r->get('/conquer')->to('Conquer#index'); $r->put('/conquer/user')->to('UserConquer#create'); + $r->get('/conquer/user/team')->to('UserConquer#getSelfTeam'); $r->post('/conquer/user/coordinates')->to('UserConquer#setCoordinates'); + $r->get('/conquer/team/')->to('ConquerTeam#get'); $r->put('/conquer/node')->to('ConquerNode#create'); $r->get('/conquer/node/near')->to('ConquerNode#nearbyNodes'); + $r->get('/conquer/node/')->to('ConquerNode#get'); $r->get('/conquer/user')->to('UserConquer#get_self'); $r->post('/conquer/user/login')->to('UserConquer#login'); $r->get('/conquer/tile///.png')->to('ConquerTile#tile'); diff --git a/lib/BurguillosInfo/Controller/ConquerNode.pm b/lib/BurguillosInfo/Controller/ConquerNode.pm index 7bee3c2..cb7395c 100644 --- a/lib/BurguillosInfo/Controller/ConquerNode.pm +++ b/lib/BurguillosInfo/Controller/ConquerNode.pm @@ -9,7 +9,30 @@ use utf8; use Mojo::Base 'Mojolicious::Controller', '-signatures'; use UUID::URandom qw/create_uuid_string/; +use BurguillosInfo::Schema; +sub get($self) { + my $uuid = $self->param('uuid'); + my $user = $self->current_user; + if (!defined $uuid || !$uuid) { + return $self->render(status => 400, json => { + error => 'UUID de nodo invalido.', + }); + } + my $schema = BurguillosInfo::Schema->Schema->resultset('ConquerNode'); + my @nodes = $schema->search({uuid => $uuid}); + if (!scalar @nodes) { + return $self->render(status => 404, json => { + error => 'Nodo no encontrado', + }); + } + my $node = $nodes[0]; + if (defined $user) { + return $self->render(json => $node->serialize($user)); + } + return $self->render(json => $node->serialize()); +} + sub create ($self) { my $user = $self->current_user; if ( !defined $user ) { @@ -118,7 +141,7 @@ sub nearbyNodes($self) { }); } my @nodes = BurguillosInfo::Schema->Schema->resultset('ConquerNode')->search({}); - @nodes = map { $_->serialize } @nodes; + @nodes = map { $_->serialize($user) } @nodes; return $self->render(json => \@nodes); } diff --git a/lib/BurguillosInfo/Controller/ConquerTeam.pm b/lib/BurguillosInfo/Controller/ConquerTeam.pm new file mode 100644 index 0000000..bc07aa2 --- /dev/null +++ b/lib/BurguillosInfo/Controller/ConquerTeam.pm @@ -0,0 +1,57 @@ +package BurguillosInfo::Controller::ConquerTeam; + +use v5.34.1; + +use strict; +use warnings; + +use utf8; + +use Mojo::Base 'Mojolicious::Controller', '-signatures'; + +use UUID::URandom qw/create_uuid_string/; +use JSON; + +use BurguillosInfo::Schema; + +sub get($self) { + my $user = $self->current_user; + if (!defined $user) { + return $self->render(status => 401, json => { + error => 'You must be logged to fetch a team.', + }); + } + my $uuid = $self->param('uuid'); + my $resultset = BurguillosInfo::Schema->Schema->resultset('ConquerTeam'); + my @teams = $resultset->search({ + 'uuid' => $uuid, + }); + if (scalar @teams <= 0) { + return $self->render( status => 404, json => { + error => 'This team does not exist.', + }); + } + my $team = $teams[0]; + return $self->render(json => $team); +} + +sub getSelfTeam($self) { + my $user = $self->current_user; + if (!defined $user) { + return $self->render(status => 401, json => { + error => 'You must be logged to fetch your Team.', + }); + } + my $resultset = BurguillosInfo::Schema->Schema->resultset('ConquerTeam'); + my @teams = $resultset->search({ + 'players.uuid' => $user->uuid + }, { + join => 'players', + }); + if (scalar @teams <= 0) { + return $self->render(json => undef); + } + my $team = $teams[0]; + return $self->render(json => $team); +} +1; diff --git a/lib/BurguillosInfo/DB/Migrations.pm b/lib/BurguillosInfo/DB/Migrations.pm index ff5677e..8326c57 100644 --- a/lib/BurguillosInfo/DB/Migrations.pm +++ b/lib/BurguillosInfo/DB/Migrations.pm @@ -28,11 +28,11 @@ sub MIGRATIONS { path TEXT, FOREIGN KEY (path) REFERENCES paths(path) )', - 'ALTER TABLE paths ADD column last_seen TIMESTAMP;', + 'ALTER TABLE paths ADD COLUMN last_seen TIMESTAMP;', 'ALTER TABLE paths ALTER COLUMN last_seen SET DEFAULT NOW();', 'ALTER TABLE requests ADD PRIMARY KEY (uuid)', 'CREATE INDEX request_extra_index on requests (date, path);', - 'ALTER TABLE requests ADD column referer text;', + 'ALTER TABLE requests ADD COLUMN referer text;', 'CREATE INDEX request_referer_index on requests (referer);', 'ALTER TABLE requests ADD COLUMN country TEXT;', 'CREATE INDEX request_country_index on requests (country);', @@ -71,6 +71,17 @@ sub MIGRATIONS { 'ALTER TABLE conquer_user ALTER COLUMN last_coordinate_1 DROP DEFAULT;', 'ALTER TABLE conquer_user ADD COLUMN last_coordinate_2 REAL NOT NULL DEFAULT 0;', 'ALTER TABLE conquer_user ALTER COLUMN last_coordinate_2 DROP DEFAULT;', + 'CREATE TABLE conquer_teams ( + uuid UUID NOT NULL PRIMARY KEY, + name TEXT NOT NULL, + description TEXT NOT NULL DEFAULT \'\', + points INTEGER NOT NULL DEFAULT 0 + );', + 'ALTER TABLE conquer_user ADD COLUMN team UUID REFERENCES conquer_teams (uuid);', + 'ALTER TABLE conquer_node ADD COLUMN team UUID REFERENCES conquer_teams (uuid);', + 'ALTER TABLE conquer_teams ADD COLUMN color TEXT NOT NULL DEFAULT \'#000\';', + 'ALTER TABLE conquer_teams ALTER COLUMN color SET DEFAULT \'#555\';', + 'ALTER TABLE conquer_teams ALTER COLUMN color SET DEFAULT \'#aaa\';', ); } diff --git a/lib/BurguillosInfo/Schema/Result/ConquerNode.pm b/lib/BurguillosInfo/Schema/Result/ConquerNode.pm index 6b05b16..3748eba 100644 --- a/lib/BurguillosInfo/Schema/Result/ConquerNode.pm +++ b/lib/BurguillosInfo/Schema/Result/ConquerNode.pm @@ -9,6 +9,9 @@ use parent 'DBIx::Class::Core'; use feature 'signatures'; +use JSON; +use GIS::Distance; + __PACKAGE__->table('conquer_node'); __PACKAGE__->load_components("TimeStamp"); @@ -40,9 +43,9 @@ __PACKAGE__->add_columns( } ); -sub serialize ($self) { +sub serialize ( $self, $player = undef ) { $self = $self->get_from_storage(); - return { + my $return = { kind => 'ConquerNode', uuid => $self->uuid, name => $self->name, @@ -50,7 +53,31 @@ sub serialize ($self) { type => $self->type, coordinate_1 => $self->coordinate_1, coordinate_2 => $self->coordinate_2, + is_near => $self->is_near($player), }; + return $return; } + +sub is_near ( $self, $player ) { + if ( !defined $player ) { + return $JSON::false; + } + # Meters + if ($self->get_distance_to_player($player) < 100) { + return $JSON::true; + } + return $JSON::false; +} + +sub get_distance_to_player ($self, $player) { + my $longitude_player = $player->last_coordinate_1; + my $latitude_player = $player->last_coordinate_2; + my $longitude_node = $self->coordinate_1; + my $latitude_node = $self->coordinate_2; + my $gis = GIS::Distance->new; + # Setting distance to meters. + my $distance = $gis->distance_metal( $latitude_node, $longitude_node, $latitude_player, $longitude_player) * 1000; +} + __PACKAGE__->set_primary_key('uuid'); 1; diff --git a/lib/BurguillosInfo/Schema/Result/ConquerTeam.pm b/lib/BurguillosInfo/Schema/Result/ConquerTeam.pm new file mode 100644 index 0000000..0ccf447 --- /dev/null +++ b/lib/BurguillosInfo/Schema/Result/ConquerTeam.pm @@ -0,0 +1,53 @@ +package BurguillosInfo::Schema::Result::ConquerTeam; + +use v5.36.0; + +use strict; +use warnings; + +use parent 'DBIx::Class::Core'; + +use feature 'signatures'; + +use JSON; + +__PACKAGE__->table('conquer_teams'); +__PACKAGE__->load_components("TimeStamp"); + +__PACKAGE__->add_columns( + uuid => { + data_type => 'uuid', + is_nullable => 0, + }, + name => { + data_type => 'text', + is_nullable => 0, + }, + description => { + data_type => 'text', + is_nullable => 0, + }, + points => { + data_type => 'integer', + is_nullable => 0, + }, + color => { + data_type => 'text', + is_nullable => 0, + }, +); + +sub serialize ($self) { + $self = $self->get_from_storage(); + return { + kind => 'ConquerTeam', + uuid => $self->uuid, + name => $self->name, + description => $self->description, + points => $self->points, + color => $self->color, + }; +} +__PACKAGE__->has_many( players => 'BurguillosInfo::Schema::Result::ConquerUser', 'team'); +__PACKAGE__->set_primary_key('uuid'); +1; diff --git a/lib/BurguillosInfo/Schema/Result/ConquerUser.pm b/lib/BurguillosInfo/Schema/Result/ConquerUser.pm index 0d74832..bea3831 100644 --- a/lib/BurguillosInfo/Schema/Result/ConquerUser.pm +++ b/lib/BurguillosInfo/Schema/Result/ConquerUser.pm @@ -9,6 +9,8 @@ use parent 'DBIx::Class::Core'; use feature 'signatures'; +use JSON; + __PACKAGE__->table('conquer_user'); __PACKAGE__->load_components("TimeStamp"); @@ -17,6 +19,10 @@ __PACKAGE__->add_columns( data_type => 'uuid', is_nullable => 0, }, + team => { + data_type => 'uuid', + is_nullable => 1, + }, username => { data_type => 'text', is_nullable => 0, @@ -52,16 +58,16 @@ __PACKAGE__->add_columns( }, ); -sub coordinates($self, $coordinates = undef) { - if (defined $coordinates) { - if (ref $coordinates ne 'ARRAY' || scalar $coordinates->@* != 2) { +sub coordinates ( $self, $coordinates = undef ) { + if ( defined $coordinates ) { + if ( ref $coordinates ne 'ARRAY' || scalar $coordinates->@* != 2 ) { die 'The second parameter of this subroutine ' - . 'must be an ARRAYREF of exactly two elements.'; + . 'must be an ARRAYREF of exactly two elements.'; } - $self->last_coordinate_1($coordinates->[0]); - $self->last_coordinate_2($coordinates->[1]); + $self->last_coordinate_1( $coordinates->[0] ); + $self->last_coordinate_2( $coordinates->[1] ); } - return [$self->last_coordinate_1, $self->last_coordinate_2]; + return [ $self->last_coordinate_1, $self->last_coordinate_2 ]; } sub serialize_to_owner ($self) { @@ -69,8 +75,9 @@ sub serialize_to_owner ($self) { return { kind => 'ConquerUser', uuid => $self->uuid, + team => $self->team, username => $self->username, - is_admin => $self->is_admin, + is_admin => $self->is_admin ? $JSON::true : $JSON::false, last_activity => $self->last_activity, registration_date => $self->registration_date, }; diff --git a/public/js/bundle.js b/public/js/bundle.js index 62dbe82..4e53ad6 100644 --- a/public/js/bundle.js +++ b/public/js/bundle.js @@ -89,7 +89,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (/* binding */ Conquer)\n/* harmony export */ });\n/* harmony import */ var ol_Map__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ol/Map */ \"./node_modules/ol/Map.js\");\n/* harmony import */ var ol_MapBrowserEvent__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ol/MapBrowserEvent */ \"./node_modules/ol/MapBrowserEvent.js\");\n/* harmony import */ var ol_View__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ol/View */ \"./node_modules/ol/View.js\");\n/* harmony import */ var ol_proj_Projection_js__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ol/proj/Projection.js */ \"./node_modules/ol/proj/Projection.js\");\n/* harmony import */ var ol_layer_Tile__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ol/layer/Tile */ \"./node_modules/ol/layer/Tile.js\");\n/* harmony import */ var ol_source_OSM__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ol/source/OSM */ \"./node_modules/ol/source/OSM.js\");\n/* harmony import */ var ol_proj__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ol/proj */ \"./node_modules/ol/proj.js\");\n/* harmony import */ var ol_Feature__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ol/Feature */ \"./node_modules/ol/Feature.js\");\n/* harmony import */ var ol_geom_Point__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ol/geom/Point */ \"./node_modules/ol/geom/Point.js\");\n/* harmony import */ var ol_layer_Vector__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ol/layer/Vector */ \"./node_modules/ol/layer/Vector.js\");\n/* harmony import */ var ol_source_Vector__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ol/source/Vector */ \"./node_modules/ol/source/Vector.js\");\n/* harmony import */ var ol_style_Stroke__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ol/style/Stroke */ \"./node_modules/ol/style/Stroke.js\");\n/* harmony import */ var ol_style_Fill__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ol/style/Fill */ \"./node_modules/ol/style/Fill.js\");\n/* harmony import */ var ol_style_Circle__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ol/style/Circle */ \"./node_modules/ol/style/Circle.js\");\n/* harmony import */ var ol_style_Style__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ol/style/Style */ \"./node_modules/ol/style/Style.js\");\n/* harmony import */ var _burguillosinfo_conquer_login__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @burguillosinfo/conquer/login */ \"./js-src/conquer/login.ts\");\n/* harmony import */ var _burguillosinfo_conquer_interface_manager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @burguillosinfo/conquer/interface-manager */ \"./js-src/conquer/interface-manager.ts\");\n/* harmony import */ var _burguillosinfo_conquer_interface_self_player__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @burguillosinfo/conquer/interface/self-player */ \"./js-src/conquer/interface/self-player.ts\");\n/* harmony import */ var _burguillosinfo_conquer_create_node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @burguillosinfo/conquer/create-node */ \"./js-src/conquer/create-node.ts\");\n/* harmony import */ var _burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @burguillosinfo/conquer/map-state */ \"./js-src/conquer/map-state.ts\");\n/* harmony import */ var _burguillosinfo_conquer_map_node__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @burguillosinfo/conquer/map-node */ \"./js-src/conquer/map-node.ts\");\n/* harmony import */ var _burguillosinfo_conquer_interface_new_node__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @burguillosinfo/conquer/interface/new-node */ \"./js-src/conquer/interface/new-node.ts\");\n/* harmony import */ var _burguillosinfo_conquer_serializer__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @burguillosinfo/conquer/serializer */ \"./js-src/conquer/serializer.ts\");\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nclass Conquer {\n getServerNodes() {\n return this.serverNodes;\n }\n getState() {\n return this.state;\n }\n setState(state) {\n this.state = state;\n this.refreshState();\n }\n removeState(state) {\n this.state &= ~state;\n this.refreshState();\n }\n addState(state) {\n this.state |= state;\n this.refreshState();\n }\n refreshState() {\n this.createNodeObject.refreshState();\n return;\n }\n static start() {\n const conquerContainer = document.querySelector(\".conquer-container\");\n if (conquerContainer === null || !(conquerContainer instanceof HTMLDivElement)) {\n Conquer.fail('.conquer-container is not a div.');\n }\n const conquer = new Conquer(conquerContainer);\n conquer.run();\n }\n setCenterDisplaced(lat, lon) {\n if (this.firstSetCenter || !(this.state & _burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].FREE_MOVE)) {\n this.coordinate_1 = lon;\n this.coordinate_2 = lat;\n const olCoordinates = this.realCoordinatesToOl(lat, lon);\n const size = this.map.getSize();\n if (size === undefined) {\n return;\n }\n this.map.getView().centerOn(olCoordinates, size, [size[0] / 2, size[1] - 60]);\n this.firstSetCenter = false;\n }\n }\n static fail(error) {\n alert('Error de interfaz');\n throw new Error(error);\n }\n isStateCreatingNode() {\n return !!(this.getState() & _burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].CREATE_NODE);\n }\n isStateSelectWhereToCreateNode() {\n return !!(this.getState() & _burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].SELECT_WHERE_TO_CREATE_NODE);\n }\n async onClickWhereToCreateNode(event) {\n if (!(event instanceof ol_MapBrowserEvent__WEBPACK_IMPORTED_MODULE_9__[\"default\"])) {\n return;\n }\n const pixel = event.pixel;\n const coordinates = this.map.getCoordinateFromPixel(pixel);\n const newNodeUI = new _burguillosinfo_conquer_interface_new_node__WEBPACK_IMPORTED_MODULE_7__[\"default\"](coordinates);\n const oldState = this.getState();\n newNodeUI.on('close', () => {\n this.interfaceManager.remove(newNodeUI);\n this.setState(oldState);\n });\n this.interfaceManager.push(newNodeUI);\n this.removeState(_burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].SELECT_WHERE_TO_CREATE_NODE);\n // const style = new Style({\n // image: new CircleStyle({\n // radius: 14,\n // fill: new Fill({color: 'white'}),\n // stroke: new Stroke({\n // color: 'gray',\n // width: 2,\n // })\n // })\n // })\n // const mapNode = new MapNode(style, feature, `server-node-${++this.createNodeCounter}`)\n // this.getServerNodes()[mapNode.getId()] = mapNode\n // this.refreshLayers()\n }\n isStateFillingFormCreateNode() {\n return !!(this.getState() & _burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].FILLING_FORM_CREATE_NODE);\n }\n async onClickMap(event) {\n if (this.isStateCreatingNode() && this.isStateSelectWhereToCreateNode()) {\n this.onClickWhereToCreateNode(event);\n }\n if (!(this.getState() & _burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].NORMAL)) {\n return;\n }\n if (this.vectorLayer === null) {\n return;\n }\n if (!(event instanceof ol_MapBrowserEvent__WEBPACK_IMPORTED_MODULE_9__[\"default\"])) {\n return;\n }\n if (event.dragging) {\n return;\n }\n const pixel = event.pixel;\n const features = this.map.getFeaturesAtPixel(pixel);\n const feature = features.length ? features[0] : undefined;\n if (feature === undefined) {\n return;\n }\n if (!(feature instanceof ol_Feature__WEBPACK_IMPORTED_MODULE_10__[\"default\"])) {\n return;\n }\n this.onClickFeature(feature);\n }\n async onClickSelf() {\n if (!(this.state & _burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].NORMAL)) {\n return;\n }\n const selfPlayerUI = new _burguillosinfo_conquer_interface_self_player__WEBPACK_IMPORTED_MODULE_3__[\"default\"](!!(this.getState() & (_burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].FREE_MOVE | _burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].FREE_ROTATION)));\n selfPlayerUI.on('close', () => {\n this.interfaceManager.remove(selfPlayerUI);\n });\n selfPlayerUI.on('enable-explorer-mode', () => {\n console.log('hola');\n this.addState(_burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].FREE_MOVE);\n this.addState(_burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].FREE_ROTATION);\n });\n selfPlayerUI.on('disable-explorer-mode', () => {\n this.removeState(_burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].FREE_MOVE);\n this.removeState(_burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].FREE_ROTATION);\n });\n selfPlayerUI.on('createNodeStart', () => {\n this.addState(_burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].CREATE_NODE);\n this.removeState(_burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].NORMAL);\n });\n this.interfaceManager.push(selfPlayerUI);\n this.selfPlayerUI = selfPlayerUI;\n }\n async onClickFeature(feature) {\n if (this.isFeatureEnabledMap[feature.getProperties().type] === undefined) {\n this.isFeatureEnabledMap[feature.getProperties().type] = true;\n }\n if (!this.isFeatureEnabledMap[feature.getProperties().type]) {\n return;\n }\n this.isFeatureEnabledMap[feature.getProperties().type] = false;\n window.setTimeout(() => {\n this.isFeatureEnabledMap[feature.getProperties().type] = true;\n }, 100);\n const candidateNode = this.getServerNodes()[feature.getProperties().type];\n if (candidateNode !== undefined) {\n candidateNode.click(this.interfaceManager);\n return;\n }\n if (feature === this.currentPositionFeature) {\n this.onClickSelf();\n return;\n }\n }\n async onLoginSuccess() {\n this.clearIntervalSendCoordinates();\n this.createIntervalSendCoordinates();\n this.clearIntervalPollNearbyNodes();\n this.createIntervalPollNearbyNodes();\n }\n clearIntervalPollNearbyNodes() {\n if (this.intervalPollNearbyNodes !== null) {\n window.clearInterval(this.intervalPollNearbyNodes);\n this.intervalPollNearbyNodes = null;\n }\n }\n getNearbyNodes() {\n const urlNodes = new URL('/conquer/node/near', window.location.protocol + '//' + window.location.hostname + ':' + window.location.port);\n fetch(urlNodes).then(async (response) => {\n let responseBody;\n try {\n responseBody = await response.json();\n }\n catch (error) {\n console.error('Error parseando json: ' + responseBody);\n console.error(error);\n return;\n }\n if (response.status !== 200) {\n console.error(responseBody.error);\n return;\n }\n const serverNodes = {};\n const nodes = _burguillosinfo_conquer_serializer__WEBPACK_IMPORTED_MODULE_8__[\"default\"].deserialize(responseBody, _burguillosinfo_conquer_map_node__WEBPACK_IMPORTED_MODULE_6__[\"default\"]);\n if (!(nodes instanceof Array)) {\n console.error('Received null instead of node list.');\n return;\n }\n for (const node of nodes) {\n if (!(node instanceof _burguillosinfo_conquer_map_node__WEBPACK_IMPORTED_MODULE_6__[\"default\"])) {\n console.error('Received node is not a MapNode.');\n continue;\n }\n serverNodes[node.getId()] = node;\n }\n this.serverNodes = serverNodes;\n this.refreshLayers();\n });\n }\n createIntervalPollNearbyNodes() {\n this.getNearbyNodes();\n this.intervalPollNearbyNodes = window.setInterval(() => {\n this.getNearbyNodes();\n }, 40000);\n }\n createIntervalSendCoordinates() {\n this.intervalSendCoordinates = window.setInterval(() => {\n this.sendCoordinatesToServer();\n }, 40000);\n }\n sendCoordinatesToServer() {\n const urlLog = new URL('/conquer/user/coordinates', window.location.protocol + '//' + window.location.hostname + ':' + window.location.port);\n fetch(urlLog, {\n method: 'POST',\n body: JSON.stringify([\n this.coordinate_1,\n this.coordinate_2,\n ]),\n }).then(async (res) => {\n let responseBody;\n try {\n responseBody = await res.json();\n }\n catch (error) {\n console.error('Error parseando json: ' + responseBody);\n console.error(error);\n return;\n }\n if (res.status !== 200) {\n console.error(responseBody.error);\n }\n }).catch((error) => {\n console.error(error);\n });\n }\n runPreStartState() {\n const createNodeObject = new _burguillosinfo_conquer_create_node__WEBPACK_IMPORTED_MODULE_4__[\"default\"](this);\n this.createNodeObject = createNodeObject;\n const interfaceManager = new _burguillosinfo_conquer_interface_manager__WEBPACK_IMPORTED_MODULE_2__[\"default\"]();\n this.interfaceManager = interfaceManager;\n const conquerLogin = new _burguillosinfo_conquer_login__WEBPACK_IMPORTED_MODULE_1__[\"default\"](interfaceManager);\n conquerLogin.on('login', () => {\n this.onLoginSuccess();\n });\n conquerLogin.on('logout', () => {\n this.onLogout();\n });\n conquerLogin.start();\n this.conquerLogin = conquerLogin;\n }\n onLogout() {\n this.clearIntervalSendCoordinates();\n this.clearIntervalPollNearbyNodes();\n }\n clearIntervalSendCoordinates() {\n if (this.intervalSendCoordinates !== null) {\n window.clearInterval(this.intervalSendCoordinates);\n this.intervalSendCoordinates = null;\n }\n }\n async run() {\n this.runPreStartState();\n this.setState(_burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].NORMAL);\n const conquerContainer = this.conquerContainer;\n //layer.on('prerender', (evt) => {\n // // return\n // if (evt.context) {\n // const context = evt.context as CanvasRenderingContext2D\n // context.filter = 'grayscale(80%) invert(100%) '\n // context.globalCompositeOperation = 'source-over'\n // }\n //})\n //layer.on('postrender', (evt) => {\n // if (evt.context) {\n // const context = evt.context as CanvasRenderingContext2D\n // context.filter = 'none'\n // }\n //})\n ol_proj__WEBPACK_IMPORTED_MODULE_0__.useGeographic();\n const osm = new ol_source_OSM__WEBPACK_IMPORTED_MODULE_11__[\"default\"]();\n osm.setUrls([`${window.location.protocol}//${window.location.hostname}:${window.location.port}/conquer/tile/{z}/{x}/{y}.png`]);\n this.map = new ol_Map__WEBPACK_IMPORTED_MODULE_12__[\"default\"]({\n target: conquerContainer,\n layers: [\n new ol_layer_Tile__WEBPACK_IMPORTED_MODULE_13__[\"default\"]({\n source: osm\n })\n ],\n view: new ol_View__WEBPACK_IMPORTED_MODULE_14__[\"default\"]({\n zoom: 19,\n maxZoom: 22,\n }),\n });\n this.setLocationChangeTriggers();\n this.setRotationChangeTriggers();\n }\n setRotationChangeTriggers() {\n if (window.DeviceOrientationEvent) {\n window.addEventListener(\"deviceorientation\", (event) => {\n if (event.alpha !== null && event.beta !== null && event.gamma !== null) {\n this.onRotate(event.alpha, event.beta, event.gamma);\n }\n }, true);\n }\n }\n addCurrentLocationMarkerToMap(currentLatitude, currentLongitude) {\n const currentPositionFeature = new ol_Feature__WEBPACK_IMPORTED_MODULE_10__[\"default\"]({\n type: 'currentPositionFeature',\n geometry: new ol_geom_Point__WEBPACK_IMPORTED_MODULE_15__[\"default\"](this.realCoordinatesToOl(currentLatitude, currentLongitude))\n });\n this.currentPositionFeature = currentPositionFeature;\n }\n processLocation(location) {\n this.currentLatitude = location.coords.latitude;\n this.currentLongitude = location.coords.longitude;\n if (location.coords.heading !== null && (this.alpha != 0 || this.beta != 0 || this.gamma != 0) && !this.disableSetRotationOffset) {\n this.disableSetRotationOffset = true;\n this.heading = location.coords.heading;\n this.rotationOffset = this.compassHeading(this.alpha, this.beta, this.gamma) + (location.coords.heading * Math.PI * 2) / 360;\n }\n this.setCenterDisplaced(this.currentLatitude, this.currentLongitude);\n this.addCurrentLocationMarkerToMap(this.currentLatitude, this.currentLongitude);\n this.refreshLayers();\n }\n async refreshLayers() {\n if (this.currentPositionFeature === null) {\n return;\n }\n const styles = {\n currentPositionFeature: new ol_style_Style__WEBPACK_IMPORTED_MODULE_16__[\"default\"]({\n image: new ol_style_Circle__WEBPACK_IMPORTED_MODULE_17__[\"default\"]({\n radius: 14,\n fill: new ol_style_Fill__WEBPACK_IMPORTED_MODULE_18__[\"default\"]({ color: 'white' }),\n stroke: new ol_style_Stroke__WEBPACK_IMPORTED_MODULE_19__[\"default\"]({\n color: 'blue',\n width: 2,\n })\n })\n })\n };\n const features = [this.currentPositionFeature];\n for (const key in this.getServerNodes()) {\n styles[key] = this.getServerNodes()[key].getStyle();\n features.push(this.getServerNodes()[key].getFeature());\n }\n const vectorLayer = new ol_layer_Vector__WEBPACK_IMPORTED_MODULE_20__[\"default\"]({\n source: new ol_source_Vector__WEBPACK_IMPORTED_MODULE_21__[\"default\"]({\n features: features\n }),\n });\n if (this.vectorLayer !== null) {\n this.map.removeLayer(this.vectorLayer);\n this.vectorLayer = null;\n }\n vectorLayer.setStyle((feature) => {\n return styles[feature.getProperties().type];\n });\n this.map.addLayer(vectorLayer);\n this.vectorLayer = vectorLayer;\n this.map.on('click', (event) => {\n this.onClickMap(event);\n });\n }\n setLocationChangeTriggers() {\n window.setInterval(() => {\n this.disableSetRotationOffset = false;\n }, 10000);\n this.currentPositionFeature = null;\n window.setTimeout(() => {\n window.setInterval(() => {\n navigator.geolocation.getCurrentPosition((location) => {\n this.processLocation(location);\n }, () => {\n return;\n }, {\n enableHighAccuracy: true,\n });\n }, 3000);\n }, 1000);\n // const initialLatitude = 37.58237\n //const initialLongitude = -5.96766\n const initialLongitude = 2.500845037550267;\n const initialLatitude = 48.81050698635832;\n this.setCenterDisplaced(initialLatitude, initialLongitude);\n this.addCurrentLocationMarkerToMap(initialLatitude, initialLongitude);\n this.refreshLayers();\n navigator.geolocation.watchPosition((location) => {\n this.processLocation(location);\n }, (err) => {\n return;\n }, {\n enableHighAccuracy: true,\n });\n }\n realCoordinatesToOl(lat, lon) {\n return ol_proj__WEBPACK_IMPORTED_MODULE_0__.transform([lon, lat], new ol_proj_Projection_js__WEBPACK_IMPORTED_MODULE_22__[\"default\"]({ code: \"WGS84\" }), new ol_proj_Projection_js__WEBPACK_IMPORTED_MODULE_22__[\"default\"]({ code: \"EPSG:900913\" }));\n }\n compassHeading(alpha, beta, gamma) {\n const alphaRad = alpha * (Math.PI / 180);\n return alphaRad;\n }\n logToServer(logValue) {\n const urlLog = new URL('/conquer/log', window.location.protocol + '//' + window.location.hostname + ':' + window.location.port);\n urlLog.searchParams.append('log', logValue);\n fetch(urlLog).then(() => {\n return;\n }).catch((error) => {\n console.error(error);\n });\n }\n onRotate(alpha, beta, gamma) {\n if (this.enabledOnRotate) {\n this.alpha = alpha;\n this.beta = beta;\n this.gamma = gamma;\n this.enabledOnRotate = false;\n if (this.firstSetRotation || !(this.state & _burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].FREE_ROTATION)) {\n this.map.getView().setRotation((this.compassHeading(alpha, beta, gamma) - this.rotationOffset));\n this.firstSetRotation = false;\n }\n window.setTimeout(() => {\n this.enabledOnRotate = true;\n }, 10);\n }\n this.setCenterDisplaced(this.currentLatitude, this.currentLongitude);\n }\n constructor(conquerContainer) {\n this.intervalSendCoordinates = null;\n this.rotationOffset = 0;\n this.heading = 0;\n this.disableSetRotationOffset = false;\n this.vectorLayer = null;\n this.alpha = 0;\n this.beta = 0;\n this.gamma = 0;\n this.selfPlayerUI = null;\n this.firstSetCenter = true;\n this.firstSetRotation = true;\n this.state = _burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].NOTHING;\n this.serverNodes = {};\n this.coordinate_1 = 0;\n this.coordinate_2 = 0;\n this.createNodeCounter = 0;\n this.isFeatureEnabledMap = {};\n this.intervalPollNearbyNodes = null;\n this.enabledOnRotate = true;\n this.conquerContainer = conquerContainer;\n }\n}\n\n\n//# sourceURL=webpack://BurguillosInfo/./js-src/conquer/index.ts?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (/* binding */ Conquer)\n/* harmony export */ });\n/* harmony import */ var ol_Map__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ol/Map */ \"./node_modules/ol/Map.js\");\n/* harmony import */ var ol_MapBrowserEvent__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ol/MapBrowserEvent */ \"./node_modules/ol/MapBrowserEvent.js\");\n/* harmony import */ var ol_View__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ol/View */ \"./node_modules/ol/View.js\");\n/* harmony import */ var ol_proj_Projection_js__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ol/proj/Projection.js */ \"./node_modules/ol/proj/Projection.js\");\n/* harmony import */ var ol_layer_Tile__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ol/layer/Tile */ \"./node_modules/ol/layer/Tile.js\");\n/* harmony import */ var ol_source_OSM__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ol/source/OSM */ \"./node_modules/ol/source/OSM.js\");\n/* harmony import */ var ol_proj__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ol/proj */ \"./node_modules/ol/proj.js\");\n/* harmony import */ var ol_Feature__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ol/Feature */ \"./node_modules/ol/Feature.js\");\n/* harmony import */ var ol_geom_Point__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ol/geom/Point */ \"./node_modules/ol/geom/Point.js\");\n/* harmony import */ var ol_layer_Vector__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ol/layer/Vector */ \"./node_modules/ol/layer/Vector.js\");\n/* harmony import */ var ol_source_Vector__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ol/source/Vector */ \"./node_modules/ol/source/Vector.js\");\n/* harmony import */ var ol_style_Stroke__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ol/style/Stroke */ \"./node_modules/ol/style/Stroke.js\");\n/* harmony import */ var ol_style_Fill__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ol/style/Fill */ \"./node_modules/ol/style/Fill.js\");\n/* harmony import */ var ol_style_Circle__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ol/style/Circle */ \"./node_modules/ol/style/Circle.js\");\n/* harmony import */ var ol_style_Style__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ol/style/Style */ \"./node_modules/ol/style/Style.js\");\n/* harmony import */ var _burguillosinfo_conquer_login__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @burguillosinfo/conquer/login */ \"./js-src/conquer/login.ts\");\n/* harmony import */ var _burguillosinfo_conquer_interface_manager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @burguillosinfo/conquer/interface-manager */ \"./js-src/conquer/interface-manager.ts\");\n/* harmony import */ var _burguillosinfo_conquer_interface_self_player__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @burguillosinfo/conquer/interface/self-player */ \"./js-src/conquer/interface/self-player.ts\");\n/* harmony import */ var _burguillosinfo_conquer_create_node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @burguillosinfo/conquer/create-node */ \"./js-src/conquer/create-node.ts\");\n/* harmony import */ var _burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @burguillosinfo/conquer/map-state */ \"./js-src/conquer/map-state.ts\");\n/* harmony import */ var _burguillosinfo_conquer_map_node__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @burguillosinfo/conquer/map-node */ \"./js-src/conquer/map-node.ts\");\n/* harmony import */ var _burguillosinfo_conquer_interface_new_node__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @burguillosinfo/conquer/interface/new-node */ \"./js-src/conquer/interface/new-node.ts\");\n/* harmony import */ var _burguillosinfo_conquer_serializer__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @burguillosinfo/conquer/serializer */ \"./js-src/conquer/serializer.ts\");\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nclass Conquer {\n getServerNodes() {\n return this.serverNodes;\n }\n getState() {\n return this.state;\n }\n setState(state) {\n this.state = state;\n this.refreshState();\n }\n removeState(state) {\n this.state &= ~state;\n this.refreshState();\n }\n addState(state) {\n this.state |= state;\n this.refreshState();\n }\n refreshState() {\n this.createNodeObject.refreshState();\n return;\n }\n static start() {\n const conquerContainer = document.querySelector(\".conquer-container\");\n if (conquerContainer === null || !(conquerContainer instanceof HTMLDivElement)) {\n Conquer.fail('.conquer-container is not a div.');\n }\n const conquer = new Conquer(conquerContainer);\n conquer.run();\n }\n setCenterDisplaced(lat, lon) {\n if (this.firstSetCenter || !(this.state & _burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].FREE_MOVE)) {\n this.coordinate_1 = lon;\n this.coordinate_2 = lat;\n const olCoordinates = this.realCoordinatesToOl(lat, lon);\n const size = this.map.getSize();\n if (size === undefined) {\n return;\n }\n this.map.getView().centerOn(olCoordinates, size, [size[0] / 2, size[1] - 60]);\n this.firstSetCenter = false;\n }\n }\n static fail(error) {\n alert('Error de interfaz');\n throw new Error(error);\n }\n isStateCreatingNode() {\n return !!(this.getState() & _burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].CREATE_NODE);\n }\n isStateSelectWhereToCreateNode() {\n return !!(this.getState() & _burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].SELECT_WHERE_TO_CREATE_NODE);\n }\n async onClickWhereToCreateNode(event) {\n if (!(event instanceof ol_MapBrowserEvent__WEBPACK_IMPORTED_MODULE_9__[\"default\"])) {\n return;\n }\n const pixel = event.pixel;\n const coordinates = this.map.getCoordinateFromPixel(pixel);\n const newNodeUI = new _burguillosinfo_conquer_interface_new_node__WEBPACK_IMPORTED_MODULE_7__[\"default\"](coordinates);\n const oldState = this.getState();\n newNodeUI.on('close', () => {\n this.interfaceManager.remove(newNodeUI);\n this.setState(oldState);\n });\n this.interfaceManager.push(newNodeUI);\n this.removeState(_burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].SELECT_WHERE_TO_CREATE_NODE);\n // const style = new Style({\n // image: new CircleStyle({\n // radius: 14,\n // fill: new Fill({color: 'white'}),\n // stroke: new Stroke({\n // color: 'gray',\n // width: 2,\n // })\n // })\n // })\n // const mapNode = new MapNode(style, feature, `server-node-${++this.createNodeCounter}`)\n // this.getServerNodes()[mapNode.getId()] = mapNode\n // this.refreshLayers()\n }\n isStateFillingFormCreateNode() {\n return !!(this.getState() & _burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].FILLING_FORM_CREATE_NODE);\n }\n async onClickMap(event) {\n if (this.isStateCreatingNode() && this.isStateSelectWhereToCreateNode()) {\n this.onClickWhereToCreateNode(event);\n }\n if (!(this.getState() & _burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].NORMAL)) {\n return;\n }\n if (this.vectorLayer === null) {\n return;\n }\n if (!(event instanceof ol_MapBrowserEvent__WEBPACK_IMPORTED_MODULE_9__[\"default\"])) {\n return;\n }\n if (event.dragging) {\n return;\n }\n const pixel = event.pixel;\n const features = this.map.getFeaturesAtPixel(pixel);\n const feature = features.length ? features[0] : undefined;\n if (feature === undefined) {\n return;\n }\n if (!(feature instanceof ol_Feature__WEBPACK_IMPORTED_MODULE_10__[\"default\"])) {\n return;\n }\n this.onClickFeature(feature);\n }\n async onClickSelf() {\n if (!(this.state & _burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].NORMAL)) {\n return;\n }\n const selfPlayerUI = new _burguillosinfo_conquer_interface_self_player__WEBPACK_IMPORTED_MODULE_3__[\"default\"](!!(this.getState() & (_burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].FREE_MOVE | _burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].FREE_ROTATION)));\n selfPlayerUI.on('close', () => {\n this.interfaceManager.remove(selfPlayerUI);\n });\n selfPlayerUI.on('enable-explorer-mode', () => {\n console.log('hola');\n this.addState(_burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].FREE_MOVE);\n this.addState(_burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].FREE_ROTATION);\n });\n selfPlayerUI.on('disable-explorer-mode', () => {\n this.removeState(_burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].FREE_MOVE);\n this.removeState(_burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].FREE_ROTATION);\n });\n selfPlayerUI.on('createNodeStart', () => {\n this.addState(_burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].CREATE_NODE);\n this.removeState(_burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].NORMAL);\n });\n this.interfaceManager.push(selfPlayerUI);\n this.selfPlayerUI = selfPlayerUI;\n }\n async onClickFeature(feature) {\n if (this.isFeatureEnabledMap[feature.getProperties().type] === undefined) {\n this.isFeatureEnabledMap[feature.getProperties().type] = true;\n }\n if (!this.isFeatureEnabledMap[feature.getProperties().type]) {\n return;\n }\n this.isFeatureEnabledMap[feature.getProperties().type] = false;\n window.setTimeout(() => {\n this.isFeatureEnabledMap[feature.getProperties().type] = true;\n }, 100);\n const candidateNode = this.getServerNodes()[feature.getProperties().type];\n if (candidateNode !== undefined) {\n candidateNode.click(this.interfaceManager);\n return;\n }\n if (feature === this.currentPositionFeature) {\n this.onClickSelf();\n return;\n }\n }\n async onLoginSuccess() {\n this.clearIntervalSendCoordinates();\n this.createIntervalSendCoordinates();\n this.clearIntervalPollNearbyNodes();\n this.createIntervalPollNearbyNodes();\n }\n clearIntervalPollNearbyNodes() {\n if (this.intervalPollNearbyNodes !== null) {\n window.clearInterval(this.intervalPollNearbyNodes);\n this.intervalPollNearbyNodes = null;\n }\n }\n async getNearbyNodes() {\n const urlNodes = new URL('/conquer/node/near', window.location.protocol + '//' + window.location.hostname + ':' + window.location.port);\n let response;\n try {\n response = await fetch(urlNodes);\n }\n catch (error) {\n console.error(error);\n return;\n }\n let responseBody;\n try {\n responseBody = await response.json();\n }\n catch (error) {\n console.error('Error parseando json: ' + responseBody);\n console.error(error);\n return;\n }\n if (response.status !== 200) {\n console.error(responseBody.error);\n return;\n }\n const serverNodes = {};\n const nodes = _burguillosinfo_conquer_serializer__WEBPACK_IMPORTED_MODULE_8__[\"default\"].deserialize(responseBody, _burguillosinfo_conquer_map_node__WEBPACK_IMPORTED_MODULE_6__[\"default\"]);\n if (!(nodes instanceof Array)) {\n console.error('Received null instead of node list.');\n return;\n }\n for (const node of nodes) {\n if (!(node instanceof _burguillosinfo_conquer_map_node__WEBPACK_IMPORTED_MODULE_6__[\"default\"])) {\n console.error('Received node is not a MapNode.');\n continue;\n }\n node.on('update-nodes', async () => {\n await this.sendCoordinatesToServer();\n this.getNearbyNodes();\n });\n serverNodes[node.getId()] = node;\n }\n this.serverNodes = serverNodes;\n this.refreshLayers();\n }\n createIntervalPollNearbyNodes() {\n this.getNearbyNodes();\n this.intervalPollNearbyNodes = window.setInterval(() => {\n this.getNearbyNodes();\n }, 40000);\n }\n createIntervalSendCoordinates() {\n this.intervalSendCoordinates = window.setInterval(() => {\n this.sendCoordinatesToServer();\n }, 40000);\n }\n async sendCoordinatesToServer() {\n const urlLog = new URL('/conquer/user/coordinates', window.location.protocol + '//' + window.location.hostname + ':' + window.location.port);\n let res;\n try {\n res = await fetch(urlLog, {\n method: 'POST',\n body: JSON.stringify([\n this.coordinate_1,\n this.coordinate_2,\n ])\n });\n }\n catch (error) {\n console.error(error);\n return;\n }\n let responseBody;\n try {\n responseBody = await res.json();\n }\n catch (error) {\n console.error('Error parseando json: ' + responseBody);\n console.error(error);\n return;\n }\n if (res.status !== 200) {\n console.error(responseBody.error);\n }\n }\n runPreStartState() {\n const createNodeObject = new _burguillosinfo_conquer_create_node__WEBPACK_IMPORTED_MODULE_4__[\"default\"](this);\n this.createNodeObject = createNodeObject;\n const interfaceManager = new _burguillosinfo_conquer_interface_manager__WEBPACK_IMPORTED_MODULE_2__[\"default\"]();\n this.interfaceManager = interfaceManager;\n const conquerLogin = new _burguillosinfo_conquer_login__WEBPACK_IMPORTED_MODULE_1__[\"default\"](interfaceManager);\n conquerLogin.on('login', () => {\n this.onLoginSuccess();\n });\n conquerLogin.on('logout', () => {\n this.onLogout();\n });\n conquerLogin.start();\n this.conquerLogin = conquerLogin;\n }\n onLogout() {\n this.clearIntervalSendCoordinates();\n this.clearIntervalPollNearbyNodes();\n }\n clearIntervalSendCoordinates() {\n if (this.intervalSendCoordinates !== null) {\n window.clearInterval(this.intervalSendCoordinates);\n this.intervalSendCoordinates = null;\n }\n }\n async run() {\n this.runPreStartState();\n this.setState(_burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].NORMAL);\n const conquerContainer = this.conquerContainer;\n //layer.on('prerender', (evt) => {\n // // return\n // if (evt.context) {\n // const context = evt.context as CanvasRenderingContext2D\n // context.filter = 'grayscale(80%) invert(100%) '\n // context.globalCompositeOperation = 'source-over'\n // }\n //})\n //layer.on('postrender', (evt) => {\n // if (evt.context) {\n // const context = evt.context as CanvasRenderingContext2D\n // context.filter = 'none'\n // }\n //})\n ol_proj__WEBPACK_IMPORTED_MODULE_0__.useGeographic();\n const osm = new ol_source_OSM__WEBPACK_IMPORTED_MODULE_11__[\"default\"]();\n osm.setUrls([`${window.location.protocol}//${window.location.hostname}:${window.location.port}/conquer/tile/{z}/{x}/{y}.png`]);\n this.map = new ol_Map__WEBPACK_IMPORTED_MODULE_12__[\"default\"]({\n target: conquerContainer,\n layers: [\n new ol_layer_Tile__WEBPACK_IMPORTED_MODULE_13__[\"default\"]({\n source: osm\n })\n ],\n view: new ol_View__WEBPACK_IMPORTED_MODULE_14__[\"default\"]({\n zoom: 19,\n maxZoom: 22,\n }),\n });\n this.setLocationChangeTriggers();\n this.setRotationChangeTriggers();\n }\n setRotationChangeTriggers() {\n if (window.DeviceOrientationEvent) {\n window.addEventListener(\"deviceorientation\", (event) => {\n if (event.alpha !== null && event.beta !== null && event.gamma !== null) {\n this.onRotate(event.alpha, event.beta, event.gamma);\n }\n }, true);\n }\n }\n addCurrentLocationMarkerToMap(currentLatitude, currentLongitude) {\n const currentPositionFeature = new ol_Feature__WEBPACK_IMPORTED_MODULE_10__[\"default\"]({\n type: 'currentPositionFeature',\n geometry: new ol_geom_Point__WEBPACK_IMPORTED_MODULE_15__[\"default\"](this.realCoordinatesToOl(currentLatitude, currentLongitude))\n });\n this.currentPositionFeature = currentPositionFeature;\n }\n processLocation(location) {\n this.currentLatitude = location.coords.latitude;\n this.currentLongitude = location.coords.longitude;\n if (location.coords.heading !== null && (this.alpha != 0 || this.beta != 0 || this.gamma != 0) && !this.disableSetRotationOffset) {\n this.disableSetRotationOffset = true;\n this.heading = location.coords.heading;\n this.rotationOffset = this.compassHeading(this.alpha, this.beta, this.gamma) + (location.coords.heading * Math.PI * 2) / 360;\n }\n this.setCenterDisplaced(this.currentLatitude, this.currentLongitude);\n this.addCurrentLocationMarkerToMap(this.currentLatitude, this.currentLongitude);\n this.refreshLayers();\n }\n async refreshLayers() {\n if (this.currentPositionFeature === null) {\n return;\n }\n const styles = {\n currentPositionFeature: new ol_style_Style__WEBPACK_IMPORTED_MODULE_16__[\"default\"]({\n image: new ol_style_Circle__WEBPACK_IMPORTED_MODULE_17__[\"default\"]({\n radius: 14,\n fill: new ol_style_Fill__WEBPACK_IMPORTED_MODULE_18__[\"default\"]({ color: 'white' }),\n stroke: new ol_style_Stroke__WEBPACK_IMPORTED_MODULE_19__[\"default\"]({\n color: 'blue',\n width: 2,\n })\n })\n })\n };\n const features = [this.currentPositionFeature];\n for (const key in this.getServerNodes()) {\n styles[key] = this.getServerNodes()[key].getStyle();\n features.push(this.getServerNodes()[key].getFeature());\n }\n const vectorLayer = new ol_layer_Vector__WEBPACK_IMPORTED_MODULE_20__[\"default\"]({\n source: new ol_source_Vector__WEBPACK_IMPORTED_MODULE_21__[\"default\"]({\n features: features\n }),\n });\n if (this.vectorLayer !== null) {\n this.map.removeLayer(this.vectorLayer);\n this.vectorLayer = null;\n }\n vectorLayer.setStyle((feature) => {\n return styles[feature.getProperties().type];\n });\n this.map.addLayer(vectorLayer);\n this.vectorLayer = vectorLayer;\n this.map.on('click', (event) => {\n this.onClickMap(event);\n });\n }\n setLocationChangeTriggers() {\n window.setInterval(() => {\n this.disableSetRotationOffset = false;\n }, 10000);\n this.currentPositionFeature = null;\n window.setTimeout(() => {\n window.setInterval(() => {\n navigator.geolocation.getCurrentPosition((location) => {\n this.processLocation(location);\n }, () => {\n return;\n }, {\n enableHighAccuracy: true,\n });\n }, 3000);\n }, 1000);\n // const initialLatitude = 37.58237\n //const initialLongitude = -5.96766\n const initialLongitude = 2.500845037550267;\n const initialLatitude = 48.81050698635832;\n this.setCenterDisplaced(initialLatitude, initialLongitude);\n this.addCurrentLocationMarkerToMap(initialLatitude, initialLongitude);\n this.refreshLayers();\n navigator.geolocation.watchPosition((location) => {\n this.processLocation(location);\n }, (err) => {\n return;\n }, {\n enableHighAccuracy: true,\n });\n }\n realCoordinatesToOl(lat, lon) {\n return ol_proj__WEBPACK_IMPORTED_MODULE_0__.transform([lon, lat], new ol_proj_Projection_js__WEBPACK_IMPORTED_MODULE_22__[\"default\"]({ code: \"WGS84\" }), new ol_proj_Projection_js__WEBPACK_IMPORTED_MODULE_22__[\"default\"]({ code: \"EPSG:900913\" }));\n }\n compassHeading(alpha, beta, gamma) {\n const alphaRad = alpha * (Math.PI / 180);\n return alphaRad;\n }\n logToServer(logValue) {\n const urlLog = new URL('/conquer/log', window.location.protocol + '//' + window.location.hostname + ':' + window.location.port);\n urlLog.searchParams.append('log', logValue);\n fetch(urlLog).then(() => {\n return;\n }).catch((error) => {\n console.error(error);\n });\n }\n onRotate(alpha, beta, gamma) {\n if (this.enabledOnRotate) {\n this.alpha = alpha;\n this.beta = beta;\n this.gamma = gamma;\n this.enabledOnRotate = false;\n if (this.firstSetRotation || !(this.state & _burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].FREE_ROTATION)) {\n this.map.getView().setRotation((this.compassHeading(alpha, beta, gamma) - this.rotationOffset));\n this.firstSetRotation = false;\n }\n window.setTimeout(() => {\n this.enabledOnRotate = true;\n }, 10);\n }\n this.setCenterDisplaced(this.currentLatitude, this.currentLongitude);\n }\n constructor(conquerContainer) {\n this.intervalSendCoordinates = null;\n this.rotationOffset = 0;\n this.heading = 0;\n this.disableSetRotationOffset = false;\n this.vectorLayer = null;\n this.alpha = 0;\n this.beta = 0;\n this.gamma = 0;\n this.selfPlayerUI = null;\n this.firstSetCenter = true;\n this.firstSetRotation = true;\n this.state = _burguillosinfo_conquer_map_state__WEBPACK_IMPORTED_MODULE_5__[\"default\"].NOTHING;\n this.serverNodes = {};\n this.coordinate_1 = 0;\n this.coordinate_2 = 0;\n this.createNodeCounter = 0;\n this.isFeatureEnabledMap = {};\n this.intervalPollNearbyNodes = null;\n this.enabledOnRotate = true;\n this.conquerContainer = conquerContainer;\n }\n}\n\n\n//# sourceURL=webpack://BurguillosInfo/./js-src/conquer/index.ts?"); /***/ }), @@ -155,7 +155,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (/* binding */ NodeView)\n/* harmony export */ });\n/* harmony import */ var _burguillosinfo_conquer_interface_abstract_top_bar_interface__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @burguillosinfo/conquer/interface/abstract-top-bar-interface */ \"./js-src/conquer/interface/abstract-top-bar-interface.ts\");\n/* harmony import */ var _burguillosinfo_conquer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @burguillosinfo/conquer */ \"./js-src/conquer/index.ts\");\n\n\nclass NodeView extends _burguillosinfo_conquer_interface_abstract_top_bar_interface__WEBPACK_IMPORTED_MODULE_0__[\"default\"] {\n getNodeNameH2() {\n const element = this.getMainNode().querySelector('h2.node-name');\n if (!(element instanceof HTMLElement)) {\n _burguillosinfo_conquer__WEBPACK_IMPORTED_MODULE_1__[\"default\"].fail('h2.node-name is not a H2 or does not exist.');\n }\n return element;\n }\n getNodeDescriptionParagraph() {\n const element = this.getMainNode().querySelector('p.node-description');\n if (!(element instanceof HTMLElement)) {\n _burguillosinfo_conquer__WEBPACK_IMPORTED_MODULE_1__[\"default\"].fail('p.node-description is not a P or does not exist.');\n }\n return element;\n }\n constructor(node) {\n super();\n this.node = node;\n }\n run() {\n const mainNode = this.getMainNode();\n const view = this.getNodeFromTemplateId('conquer-view-node-template');\n mainNode.append(view);\n this.getNodeNameH2().innerText = this.node.getName();\n this.getNodeDescriptionParagraph().innerText = this.node.getDescription();\n view.classList.remove('conquer-display-none');\n mainNode.classList.remove('conquer-display-none');\n }\n}\n\n\n//# sourceURL=webpack://BurguillosInfo/./js-src/conquer/interface/node-view.ts?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (/* binding */ NodeView)\n/* harmony export */ });\n/* harmony import */ var _burguillosinfo_conquer_interface_abstract_top_bar_interface__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @burguillosinfo/conquer/interface/abstract-top-bar-interface */ \"./js-src/conquer/interface/abstract-top-bar-interface.ts\");\n/* harmony import */ var _burguillosinfo_conquer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @burguillosinfo/conquer */ \"./js-src/conquer/index.ts\");\n\n\nclass NodeView extends _burguillosinfo_conquer_interface_abstract_top_bar_interface__WEBPACK_IMPORTED_MODULE_0__[\"default\"] {\n getNodeNameH2() {\n const element = this.getMainNode().querySelector('h2.node-name');\n if (!(element instanceof HTMLElement)) {\n _burguillosinfo_conquer__WEBPACK_IMPORTED_MODULE_1__[\"default\"].fail('h2.node-name is not a H2 or does not exist.');\n }\n return element;\n }\n getNodeDescriptionParagraph() {\n const element = this.getMainNode().querySelector('p.node-description');\n if (!(element instanceof HTMLElement)) {\n _burguillosinfo_conquer__WEBPACK_IMPORTED_MODULE_1__[\"default\"].fail('p.node-description is not a P or does not exist.');\n }\n return element;\n }\n constructor(node) {\n super();\n this.node = node;\n }\n async run() {\n const mainNode = this.getMainNode();\n this.runCallbacks('update-nodes');\n try {\n this.node = await this.node.fetch();\n }\n catch (error) {\n this.runCallbacks('close');\n }\n const view = this.getNodeFromTemplateId('conquer-view-node-template');\n mainNode.append(view);\n this.getNodeNameH2().innerText = this.node.getName();\n this.getNodeDescriptionParagraph().innerText = this.node.getDescription()\n + \"\\n\"\n + (this.node.isNear()\n ? 'Estas cerca y puedes interactuar con este sitio.'\n : 'Estás demasiado lejos para hacer nada aquí.');\n view.classList.remove('conquer-display-none');\n mainNode.classList.remove('conquer-display-none');\n }\n}\n\n\n//# sourceURL=webpack://BurguillosInfo/./js-src/conquer/interface/node-view.ts?"); /***/ }), @@ -188,7 +188,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* harmony import */ var typescript_json_serializer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! typescript-json-serializer */ \"./node_modules/typescript-json-serializer/dist/index.esm.js\");\n/* harmony import */ var ol_style_Style__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ol/style/Style */ \"./node_modules/ol/style/Style.js\");\n/* harmony import */ var ol_Feature__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ol/Feature */ \"./node_modules/ol/Feature.js\");\n/* harmony import */ var ol_style_Circle__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ol/style/Circle */ \"./node_modules/ol/style/Circle.js\");\n/* harmony import */ var ol_geom_Point__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ol/geom/Point */ \"./node_modules/ol/geom/Point.js\");\n/* harmony import */ var ol_style_Fill__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ol/style/Fill */ \"./node_modules/ol/style/Fill.js\");\n/* harmony import */ var ol_style_Stroke__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ol/style/Stroke */ \"./node_modules/ol/style/Stroke.js\");\n/* harmony import */ var _burguillosinfo_conquer_interface_node_view__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @burguillosinfo/conquer/interface/node-view */ \"./js-src/conquer/interface/node-view.ts\");\nvar __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nvar __metadata = (undefined && undefined.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};\nvar __param = (undefined && undefined.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n};\n\n\n\n\n\n\n\n\nlet MapNode = class MapNode {\n constructor(uuid, coordinate_1, coordinate_2, type, name, description, kind) {\n this.uuid = uuid;\n this.coordinate_1 = coordinate_1;\n this.coordinate_2 = coordinate_2;\n this.type = type;\n this.name = name;\n this.description = description;\n this.kind = kind;\n this.feature = null;\n this.callbacks = {};\n }\n click(interfaceManager) {\n const viewNodeInterface = new _burguillosinfo_conquer_interface_node_view__WEBPACK_IMPORTED_MODULE_1__[\"default\"](this);\n viewNodeInterface.on('close', () => {\n interfaceManager.remove(viewNodeInterface);\n });\n interfaceManager.push(viewNodeInterface);\n this.runCallbacks('click');\n }\n on(eventName, callback) {\n if (this.callbacks[eventName] === undefined) {\n this.callbacks[eventName] = [];\n }\n this.callbacks[eventName].push(callback);\n }\n runCallbacks(eventName) {\n const callbacks = this.callbacks[eventName];\n if (callbacks === undefined) {\n return;\n }\n for (const callback of callbacks) {\n callback();\n }\n }\n getType() {\n return this.type;\n }\n getName() {\n return this.name;\n }\n getDescription() {\n return this.description;\n }\n getId() {\n return 'node-' + this.uuid;\n }\n getFeature() {\n if (this.feature === null) {\n console.log(this.coordinate_1);\n console.log(this.coordinate_2);\n this.feature = new ol_Feature__WEBPACK_IMPORTED_MODULE_2__[\"default\"]({\n geometry: new ol_geom_Point__WEBPACK_IMPORTED_MODULE_3__[\"default\"]([this.coordinate_1, this.coordinate_2]),\n type: 'node-' + this.uuid,\n });\n }\n return this.feature;\n }\n getStyle() {\n return new ol_style_Style__WEBPACK_IMPORTED_MODULE_4__[\"default\"]({\n image: new ol_style_Circle__WEBPACK_IMPORTED_MODULE_5__[\"default\"]({\n radius: 14,\n fill: new ol_style_Fill__WEBPACK_IMPORTED_MODULE_6__[\"default\"]({ color: 'white' }),\n stroke: new ol_style_Stroke__WEBPACK_IMPORTED_MODULE_7__[\"default\"]({\n color: 'gray',\n width: 2,\n })\n })\n });\n }\n};\nMapNode = __decorate([\n (0,typescript_json_serializer__WEBPACK_IMPORTED_MODULE_0__.JsonObject)(),\n __param(0, (0,typescript_json_serializer__WEBPACK_IMPORTED_MODULE_0__.JsonProperty)()),\n __param(1, (0,typescript_json_serializer__WEBPACK_IMPORTED_MODULE_0__.JsonProperty)()),\n __param(2, (0,typescript_json_serializer__WEBPACK_IMPORTED_MODULE_0__.JsonProperty)()),\n __param(3, (0,typescript_json_serializer__WEBPACK_IMPORTED_MODULE_0__.JsonProperty)()),\n __param(4, (0,typescript_json_serializer__WEBPACK_IMPORTED_MODULE_0__.JsonProperty)()),\n __param(5, (0,typescript_json_serializer__WEBPACK_IMPORTED_MODULE_0__.JsonProperty)()),\n __param(6, (0,typescript_json_serializer__WEBPACK_IMPORTED_MODULE_0__.JsonProperty)()),\n __metadata(\"design:paramtypes\", [String, Number, Number, String, String, String, String])\n], MapNode);\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (MapNode);\n\n\n//# sourceURL=webpack://BurguillosInfo/./js-src/conquer/map-node.ts?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* harmony import */ var typescript_json_serializer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! typescript-json-serializer */ \"./node_modules/typescript-json-serializer/dist/index.esm.js\");\n/* harmony import */ var ol_style_Style__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ol/style/Style */ \"./node_modules/ol/style/Style.js\");\n/* harmony import */ var ol_Feature__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ol/Feature */ \"./node_modules/ol/Feature.js\");\n/* harmony import */ var ol_style_Circle__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ol/style/Circle */ \"./node_modules/ol/style/Circle.js\");\n/* harmony import */ var ol_geom_Point__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ol/geom/Point */ \"./node_modules/ol/geom/Point.js\");\n/* harmony import */ var ol_style_Fill__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ol/style/Fill */ \"./node_modules/ol/style/Fill.js\");\n/* harmony import */ var ol_style_Stroke__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ol/style/Stroke */ \"./node_modules/ol/style/Stroke.js\");\n/* harmony import */ var _burguillosinfo_conquer_interface_node_view__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @burguillosinfo/conquer/interface/node-view */ \"./js-src/conquer/interface/node-view.ts\");\n/* harmony import */ var _burguillosinfo_conquer_serializer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @burguillosinfo/conquer/serializer */ \"./js-src/conquer/serializer.ts\");\nvar __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nvar __metadata = (undefined && undefined.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};\nvar __param = (undefined && undefined.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n};\nvar MapNode_1;\n\n\n\n\n\n\n\n\n\nlet MapNode = MapNode_1 = class MapNode {\n constructor(uuid, coordinate_1, coordinate_2, type, name, description, kind, is_near) {\n this.uuid = uuid;\n this.coordinate_1 = coordinate_1;\n this.coordinate_2 = coordinate_2;\n this.type = type;\n this.name = name;\n this.description = description;\n this.kind = kind;\n this.is_near = is_near;\n this.feature = null;\n this.callbacks = {};\n }\n async fetch() {\n const urlNode = new URL('/conquer/node/' + this.uuid, window.location.protocol + '//' + window.location.hostname + ':' + window.location.port);\n const response = await fetch(urlNode);\n let responseBody;\n const errorThrow = new Error('Unable to fetch node updated.');\n try {\n responseBody = await response.json();\n }\n catch (error) {\n console.error('Error parseando json: ' + responseBody);\n console.error(error);\n throw errorThrow;\n }\n if (response.status !== 200) {\n console.error(responseBody.error);\n throw errorThrow;\n }\n const node = _burguillosinfo_conquer_serializer__WEBPACK_IMPORTED_MODULE_2__[\"default\"].deserialize(responseBody, MapNode_1);\n if (!(node instanceof MapNode_1)) {\n console.error('Unexpected JSON value for MapNode.');\n throw errorThrow;\n }\n return node;\n }\n click(interfaceManager) {\n const viewNodeInterface = new _burguillosinfo_conquer_interface_node_view__WEBPACK_IMPORTED_MODULE_1__[\"default\"](this);\n viewNodeInterface.on('close', () => {\n interfaceManager.remove(viewNodeInterface);\n });\n viewNodeInterface.on('update-nodes', () => {\n this.runCallbacks('update-nodes');\n });\n interfaceManager.push(viewNodeInterface);\n this.runCallbacks('click');\n }\n on(eventName, callback) {\n if (this.callbacks[eventName] === undefined) {\n this.callbacks[eventName] = [];\n }\n this.callbacks[eventName].push(callback);\n }\n runCallbacks(eventName) {\n const callbacks = this.callbacks[eventName];\n if (callbacks === undefined) {\n return;\n }\n for (const callback of callbacks) {\n callback();\n }\n }\n getType() {\n return this.type;\n }\n isNear() {\n return this.is_near;\n }\n getName() {\n return this.name;\n }\n getDescription() {\n return this.description;\n }\n getId() {\n return 'node-' + this.uuid;\n }\n getFeature() {\n if (this.feature === null) {\n console.log(this.coordinate_1);\n console.log(this.coordinate_2);\n this.feature = new ol_Feature__WEBPACK_IMPORTED_MODULE_3__[\"default\"]({\n geometry: new ol_geom_Point__WEBPACK_IMPORTED_MODULE_4__[\"default\"]([this.coordinate_1, this.coordinate_2]),\n type: 'node-' + this.uuid,\n });\n }\n return this.feature;\n }\n getStyle() {\n return new ol_style_Style__WEBPACK_IMPORTED_MODULE_5__[\"default\"]({\n image: new ol_style_Circle__WEBPACK_IMPORTED_MODULE_6__[\"default\"]({\n radius: 14,\n fill: new ol_style_Fill__WEBPACK_IMPORTED_MODULE_7__[\"default\"]({ color: 'white' }),\n stroke: new ol_style_Stroke__WEBPACK_IMPORTED_MODULE_8__[\"default\"]({\n color: 'gray',\n width: 2,\n })\n })\n });\n }\n};\nMapNode = MapNode_1 = __decorate([\n (0,typescript_json_serializer__WEBPACK_IMPORTED_MODULE_0__.JsonObject)(),\n __param(0, (0,typescript_json_serializer__WEBPACK_IMPORTED_MODULE_0__.JsonProperty)()),\n __param(1, (0,typescript_json_serializer__WEBPACK_IMPORTED_MODULE_0__.JsonProperty)()),\n __param(2, (0,typescript_json_serializer__WEBPACK_IMPORTED_MODULE_0__.JsonProperty)()),\n __param(3, (0,typescript_json_serializer__WEBPACK_IMPORTED_MODULE_0__.JsonProperty)()),\n __param(4, (0,typescript_json_serializer__WEBPACK_IMPORTED_MODULE_0__.JsonProperty)()),\n __param(5, (0,typescript_json_serializer__WEBPACK_IMPORTED_MODULE_0__.JsonProperty)()),\n __param(6, (0,typescript_json_serializer__WEBPACK_IMPORTED_MODULE_0__.JsonProperty)()),\n __param(7, (0,typescript_json_serializer__WEBPACK_IMPORTED_MODULE_0__.JsonProperty)()),\n __metadata(\"design:paramtypes\", [String, Number, Number, String, String, String, String, Boolean])\n], MapNode);\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (MapNode);\n\n\n//# sourceURL=webpack://BurguillosInfo/./js-src/conquer/map-node.ts?"); /***/ }), @@ -214,6 +214,17 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ }), +/***/ "./js-src/conquer/team.ts": +/*!********************************!*\ + !*** ./js-src/conquer/team.ts ***! + \********************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* harmony import */ var _burguillosinfo_conquer_serializer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @burguillosinfo/conquer/serializer */ \"./js-src/conquer/serializer.ts\");\n/* harmony import */ var typescript_json_serializer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! typescript-json-serializer */ \"./node_modules/typescript-json-serializer/dist/index.esm.js\");\nvar __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nvar __metadata = (undefined && undefined.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};\nvar ConquerTeam_1;\n\n\nlet ConquerTeam = ConquerTeam_1 = class ConquerTeam {\n constructor(uuid, name, description, points, color) {\n this.kind = 'ConquerTeam';\n this.uuid = uuid;\n this.name = name;\n this.description = description;\n this.points = points;\n this.color = color;\n }\n static async getTeam(uuid) {\n const urlTeam = new URL('/conquer/team/' + uuid, window.location.protocol + '//' + window.location.hostname + ':' + window.location.port);\n try {\n const response = await fetch(urlTeam);\n if (response.status !== 200) {\n throw new Error('Invalid response fetching team.');\n }\n const teamData = await response.json();\n let team = _burguillosinfo_conquer_serializer__WEBPACK_IMPORTED_MODULE_0__[\"default\"].deserialize(teamData, ConquerTeam_1);\n if (team === undefined) {\n team = null;\n }\n if (!(team instanceof ConquerTeam_1)) {\n throw new Error('Unable to parse team.');\n }\n return team;\n }\n catch (error) {\n console.error(error);\n throw new Error('Unable to fetch Team.');\n }\n }\n static async getSelfTeam() {\n const urlTeam = new URL('/conquer/user/team', window.location.protocol + '//' + window.location.hostname + ':' + window.location.port);\n try {\n const response = await fetch(urlTeam);\n if (response.status !== 200) {\n throw new Error('Invalid response fetching team.');\n }\n const teamData = await response.json();\n let team = _burguillosinfo_conquer_serializer__WEBPACK_IMPORTED_MODULE_0__[\"default\"].deserialize(teamData, ConquerTeam_1);\n if (team === undefined) {\n team = null;\n }\n if (team !== null && !(team instanceof ConquerTeam_1)) {\n throw new Error('Unable to parse team.');\n }\n return team;\n }\n catch (error) {\n console.error(error);\n throw new Error('Unable to fetch Team.');\n }\n }\n};\n__decorate([\n (0,typescript_json_serializer__WEBPACK_IMPORTED_MODULE_1__.JsonProperty)(),\n __metadata(\"design:type\", String)\n], ConquerTeam.prototype, \"kind\", void 0);\n__decorate([\n (0,typescript_json_serializer__WEBPACK_IMPORTED_MODULE_1__.JsonProperty)(),\n __metadata(\"design:type\", String)\n], ConquerTeam.prototype, \"uuid\", void 0);\n__decorate([\n (0,typescript_json_serializer__WEBPACK_IMPORTED_MODULE_1__.JsonProperty)(),\n __metadata(\"design:type\", String)\n], ConquerTeam.prototype, \"name\", void 0);\n__decorate([\n (0,typescript_json_serializer__WEBPACK_IMPORTED_MODULE_1__.JsonProperty)(),\n __metadata(\"design:type\", String)\n], ConquerTeam.prototype, \"description\", void 0);\n__decorate([\n (0,typescript_json_serializer__WEBPACK_IMPORTED_MODULE_1__.JsonProperty)(),\n __metadata(\"design:type\", Number)\n], ConquerTeam.prototype, \"points\", void 0);\n__decorate([\n (0,typescript_json_serializer__WEBPACK_IMPORTED_MODULE_1__.JsonProperty)(),\n __metadata(\"design:type\", String)\n], ConquerTeam.prototype, \"color\", void 0);\nConquerTeam = ConquerTeam_1 = __decorate([\n (0,typescript_json_serializer__WEBPACK_IMPORTED_MODULE_1__.JsonObject)(),\n __metadata(\"design:paramtypes\", [String, String, String, Number, String])\n], ConquerTeam);\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (ConquerTeam);\n\n\n//# sourceURL=webpack://BurguillosInfo/./js-src/conquer/team.ts?"); + +/***/ }), + /***/ "./js-src/conquer/user.ts": /*!********************************!*\ !*** ./js-src/conquer/user.ts ***! @@ -221,7 +232,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (/* binding */ ConquerUser)\n/* harmony export */ });\nclass ConquerUser {\n constructor(data) {\n this._isAdmin = false;\n this.kind = \"ConquerUser\";\n this.lastActivity = null;\n this.registrationDate = null;\n this.username = null;\n this.uuid = null;\n this.lastActivity = data.last_activity ?? null;\n this.registrationDate = data.registration_date ?? null;\n if (this.kind !== data.kind) {\n throw new Error(`We cannot instance a user from a kind different to ${this.kind}.`);\n }\n this._isAdmin = !!data.is_admin || false;\n this.uuid = data.uuid;\n this.username = data.username;\n if (this.username === null || this.username === undefined) {\n throw new Error('No username in user instance');\n }\n if (this.uuid === null || this.username === undefined) {\n throw new Error('No uuid in user instance');\n }\n }\n static async getSelfUser() {\n const urlUser = new URL('/conquer/user', window.location.protocol + '//' + window.location.hostname + ':' + window.location.port);\n try {\n const response = await fetch(urlUser);\n if (response.status !== 200) {\n throw new Error('Invalid response fetching user.');\n }\n const userData = await response.json();\n return new ConquerUser(userData);\n }\n catch (error) {\n console.error(error);\n return null;\n }\n }\n getUsername() {\n if (this.username === null) {\n throw new Error('User username cannot be null.');\n }\n return this.username;\n }\n isAdmin() {\n return this._isAdmin;\n }\n}\n\n\n//# sourceURL=webpack://BurguillosInfo/./js-src/conquer/user.ts?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* harmony import */ var _burguillosinfo_conquer_serializer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @burguillosinfo/conquer/serializer */ \"./js-src/conquer/serializer.ts\");\n/* harmony import */ var typescript_json_serializer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! typescript-json-serializer */ \"./node_modules/typescript-json-serializer/dist/index.esm.js\");\n/* harmony import */ var _burguillosinfo_conquer_team__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @burguillosinfo/conquer/team */ \"./js-src/conquer/team.ts\");\nvar __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nvar __metadata = (undefined && undefined.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};\nvar ConquerUser_1;\n\n\n\nlet ConquerUser = ConquerUser_1 = class ConquerUser {\n constructor(kind, uuid, username, is_admin = false, registration_date = null, last_activity = null) {\n this.kind = kind;\n this.uuid = uuid;\n this.username = username;\n this.is_admin = is_admin;\n this.registration_date = registration_date;\n this.last_activity = last_activity;\n }\n async getTeam() {\n if (this.team_uuid === null) {\n return null;\n }\n return _burguillosinfo_conquer_team__WEBPACK_IMPORTED_MODULE_2__[\"default\"].getTeam(this.team_uuid);\n }\n static async getSelfUser() {\n const urlUser = new URL('/conquer/user', window.location.protocol + '//' + window.location.hostname + ':' + window.location.port);\n try {\n const response = await fetch(urlUser);\n if (response.status !== 200) {\n throw new Error('Invalid response fetching user.');\n }\n const userData = await response.json();\n const user = _burguillosinfo_conquer_serializer__WEBPACK_IMPORTED_MODULE_0__[\"default\"].deserialize(userData, ConquerUser_1);\n if (!(user instanceof ConquerUser_1)) {\n throw new Error('Unable to parse user.');\n }\n return user;\n }\n catch (error) {\n console.error(error);\n return null;\n }\n }\n getUsername() {\n if (this.username === null) {\n throw new Error('User username cannot be null.');\n }\n return this.username;\n }\n isAdmin() {\n return this.is_admin;\n }\n};\n__decorate([\n (0,typescript_json_serializer__WEBPACK_IMPORTED_MODULE_1__.JsonProperty)(),\n __metadata(\"design:type\", Boolean)\n], ConquerUser.prototype, \"is_admin\", void 0);\n__decorate([\n (0,typescript_json_serializer__WEBPACK_IMPORTED_MODULE_1__.JsonProperty)(),\n __metadata(\"design:type\", String)\n], ConquerUser.prototype, \"kind\", void 0);\n__decorate([\n (0,typescript_json_serializer__WEBPACK_IMPORTED_MODULE_1__.JsonProperty)(),\n __metadata(\"design:type\", Object)\n], ConquerUser.prototype, \"last_activity\", void 0);\n__decorate([\n (0,typescript_json_serializer__WEBPACK_IMPORTED_MODULE_1__.JsonProperty)(),\n __metadata(\"design:type\", Object)\n], ConquerUser.prototype, \"registration_date\", void 0);\n__decorate([\n (0,typescript_json_serializer__WEBPACK_IMPORTED_MODULE_1__.JsonProperty)(),\n __metadata(\"design:type\", String)\n], ConquerUser.prototype, \"username\", void 0);\n__decorate([\n (0,typescript_json_serializer__WEBPACK_IMPORTED_MODULE_1__.JsonProperty)(),\n __metadata(\"design:type\", String)\n], ConquerUser.prototype, \"uuid\", void 0);\n__decorate([\n (0,typescript_json_serializer__WEBPACK_IMPORTED_MODULE_1__.JsonProperty)({ name: 'team' }),\n __metadata(\"design:type\", Object)\n], ConquerUser.prototype, \"team_uuid\", void 0);\nConquerUser = ConquerUser_1 = __decorate([\n (0,typescript_json_serializer__WEBPACK_IMPORTED_MODULE_1__.JsonObject)(),\n __metadata(\"design:paramtypes\", [String, String, String, Object, Object, Object])\n], ConquerUser);\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (ConquerUser);\n\n\n//# sourceURL=webpack://BurguillosInfo/./js-src/conquer/user.ts?"); /***/ }),