partey_workadventure/front/src/Components/ConsoleGlobalMessageManager/UploadAudioGlobalMessage.svelte

93 lines
3.3 KiB
Svelte
Raw Normal View History

<script lang="ts">
import {HtmlUtils} from "../../WebRtc/HtmlUtils";
import {Game} from "../../Phaser/Game/Game";
import {GameManager} from "../../Phaser/Game/GameManager";
import {ConsoleGlobalMessageManagerFocusStore, ConsoleGlobalMessageManagerVisibleStore} from "../../Stores/ConsoleGlobalMessageManagerStore";
import {AdminMessageEventTypes} from "../../Connexion/AdminMessagesService";
import type {PlayGlobalMessageInterface} from "../../Connexion/ConnexionModels";
import uploadFile from "../images/music-file.svg";
interface EventTargetFiles extends EventTarget {
files: Array<File>;
}
export let game: Game;
export let gameManager: GameManager;
let gameScene = game.scene.getScene(gameManager.currentGameSceneName);
let fileinput;
let filename: string;
let filesize: string;
const UPLOAD_CONSOLE_MESSAGE = 'input-upload-music';
const AUDIO_TYPE = AdminMessageEventTypes.audio;
async function SendAudioMessage() {
const inputAudio = HtmlUtils.getElementByIdOrFail<HTMLInputElement>(UPLOAD_CONSOLE_MESSAGE);
const selectedFile = inputAudio.files ? inputAudio.files[0] : null;
if (!selectedFile) {
throw 'no file selected';
}
const fd = new FormData();
fd.append('file', selectedFile);
const res = await gameScene.connection.uploadAudio(fd);
const GlobalMessage: PlayGlobalMessageInterface = {
id: (res as { id: string }).id,
message: (res as { path: string }).path,
type: AUDIO_TYPE
}
inputAudio.value = '';
gameScene.connection.emitGlobalMessage(GlobalMessage);
disableConsole();
}
function inputAudioFile(event: Event) {
console.log('Input');
const eventTarget : EventTargetFiles = (event.target as EventTargetFiles);
if(!eventTarget || !eventTarget.files || eventTarget.files.length === 0){
return;
}
const file = eventTarget.files[0];
if(!file) {
return;
}
filename = file.name;
filesize = getFileSize(file.size);
}
function getFileSize(number: number) {
if (number < 1024) {
return number + 'bytes';
} else if (number >= 1024 && number < 1048576) {
return (number / 1024).toFixed(1) + 'KB';
} else if (number >= 1048576) {
return (number / 1048576).toFixed(1) + 'MB';
} else {
return '';
}
}
function disableConsole() {
ConsoleGlobalMessageManagerVisibleStore.set(false);
ConsoleGlobalMessageManagerFocusStore.set(false);
}
</script>
<section class="section-input-send-audio">
<div class="input-send-audio">
<img src="{uploadFile}" alt="Upload a file" on:click|preventDefault={ () => {fileinput.click();}}>
{#if filename != undefined}
<label for="input-send-audio">{filename} : {filesize}</label>
{/if}
<input type="file" id="input-send-audio" bind:this={fileinput} on:change={(e) => {inputAudioFile(e)}}>
</div>
<div class="btn-action">
<button class="nes-btn is-primary" on:click|preventDefault={SendAudioMessage}>Send</button>
</div>
</section>