import { Utils } from '../Utils'; import requestPromise = require('request-promise'); import { Upload } from '../server/SharedMediaTypes'; /** * Networking is repsonsible for connecting the client to the server. Networking * mainly provides methods that the client can use to begin the process of * interacting with the server, such as fetching or uploading files. */ export namespace Networking { export async function FetchFromServer(relativeRoute: string) { return (await fetch(relativeRoute)).text(); } export async function PostToServer(relativeRoute: string, body?: any) { const options = { uri: Utils.prepend(relativeRoute), method: 'POST', body, json: true, }; return requestPromise.post(options); } /** * FileGuidPair attaches a guid to a file that is being uploaded, * allowing the client to track the upload progress. * * When files are dragged to the canvas, the overWriteDoc's ID is * used as the guid. Otherwise, a new guid is generated. */ export interface FileGuidPair { file: File; guid?: string; } /** * Handles uploading basic file types to server and makes the API call to "/uploadFormData" endpoint * with the mapping of guid to files as parameters. * * @param fileguidpairs the files and corresponding guids to be uploaded to the server * @returns the response as a json from the server */ export async function UploadFilesToServer(fileguidpairs: FileGuidPair | FileGuidPair[], browndash?: boolean): Promise[]> { const formData = new FormData(); if (Array.isArray(fileguidpairs)) { if (!fileguidpairs.length) { return []; } const maxFileSize = 50000000; if (fileguidpairs.some(f => f.file.size > maxFileSize)) { return new Promise(res => res([ { source: { name: '', type: '', size: 0, toJson: () => ({ name: '', type: '' }) }, result: { name: '', message: `max file size (${maxFileSize / 1000000}MB) exceeded` }, }, ]) ); } // If the fileguidpair has a guid to use (From the overwriteDoc) use that guid. Otherwise, generate a new guid. fileguidpairs.forEach(fileguidpair => formData.append(fileguidpair.guid ?? Utils.GenerateGuid(), fileguidpair.file)); } else { // Handle the case where fileguidpairs is a single file. formData.append(fileguidpairs.guid ?? Utils.GenerateGuid(), fileguidpairs.file); } const parameters = { method: 'POST', body: formData, }; const endpoint = browndash ? 'http://10.38.71.246:1050/uploadFormData' : '/uploadFormData'; const response = await fetch(endpoint, parameters); return response.json(); } export async function UploadYoutubeToServer(videoId: string): Promise[]> { const parameters = { method: 'POST', body: JSON.stringify({ videoId }), json: true, }; const response = await fetch('/uploadYoutubeVideo', parameters); return response.json(); } export async function QueryYoutubeProgress(videoId: string): Promise<{ progress: string }> { const parameters = { method: 'POST', body: JSON.stringify({ videoId }), json: true, }; const response = await fetch('/queryYoutubeProgress', parameters); return response.json(); } }