Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Utils from './Utils';
- import logger from './logger';
- import * as musicMetadata from 'music-metadata-browser';
- import videoMetadata from './VideoMetadata';
- import AudioVisualizer from './AudioVisualizer';
- import { store } from '../store';
- export default new class {
- parseFiletype(blob) {
- try {
- return `.${blob.type.split('/')[1]}`;
- } catch (err) {
- return '';
- }
- }
- async downloadingFile(url, progress = () => { }) {
- const response = await fetch(url);
- const contentLength = response.headers.get('content-length');
- const total = parseInt(contentLength, 10);
- let loaded = 0;
- const res = new Response(new ReadableStream({
- async start(controller) {
- const reader = response.body.getReader();
- for (; ;) {
- const { done, value } = await reader.read();
- if (done) break;
- loaded += value.byteLength;
- progress({ loaded, total })
- controller.enqueue(value);
- }
- controller.close();
- },
- }));
- const blob = await res.blob();
- return blob.slice(0, blob.size, response.headers.get('content-type'));
- }
- async generateFileData(data, opts = {}) {
- if (!data) return false;
- let file = false;
- let fileName = '';
- if (typeof data == 'string') {
- const name = opts.name || `Untitle_${Date.now()}`;
- let sw = store.state.swal({
- title: 'Downloading <b>0</b>%',
- allowEscapeKey: false,
- allowOutsideClick: false,
- showConfirmButton: false,
- didOpen: () => store.state.swal.showLoading()
- });
- const blob = await this.downloadingFile(data, ({ loaded, total }) => {
- store.state.swal.getTitle().querySelector('b').innerHTML = Math.round(loaded / total * 100);
- });
- const fileType = this.parseFiletype(blob);
- store.state.swal.close();
- fileName = `${name}${fileType}`;
- file = Utils.blobToFile(blob, fileName);
- } else {
- file = data;
- fileName.data.name;
- }
- return {
- type: file.type, size: file.size,
- name: fileName, lastModified: Date.now(),
- file, ...(await this.generatePayload(file, opts))
- };
- }
- async getProcessedFile(data = false, opts = {}) {
- const result = await this.generateFileData(data, opts);
- if (!result) return false;
- return this.processFileByType(result);
- }
- async processFileByType(data) {
- if (data && data.type) {
- if (/^(audio)/g.test(data.type))
- return audio.process(data);
- if (/^(video)/g.test(data.type))
- return video.process(data);
- if (/^(image)/g.test(data.type))
- return image.process(data);
- }
- console.log("step 1.2");
- return false;
- }
- async generatePayload(file, opts = {}) {
- let payload = {};
- if (opts.api_id) payload.api_id = opts.api_id;
- if (file.type.includes('image')) {
- const blobURL = URL.createObjectURL(file);
- const arrayBuffer = await fetch(blobURL).then(res => res.arrayBuffer());
- URL.revokeObjectURL(blobURL);
- payload = { ...payload, arrayBuffer };
- } else {
- }
- return payload;
- }
- }
- class Basic {
- clear(data) {
- //delete data.file;
- data.blob = data.file; //await fetch(data.src).then(res => res.blob());
- delete data.src;
- return data;
- }
- }
- const image = new class extends Basic {
- constructor() { super(); }
- async process(data) {
- try {
- let meta;
- try {
- meta = await window.ExifReader.load(data.arrayBuffer || data.file);
- } catch(err) {
- //console.error(err);
- meta = {};
- }
- let parsedMeta = Object.entries(meta).reduce((result, [key, value]) => {
- if (typeof value.value != 'undefined')
- result[key] = value.value;
- return result;
- }, {});
- data = this.clear(data);
- const item = {
- thumb: await Utils.generateImageThumb(data.blob, 200, 200),
- meta: { ...parsedMeta, metadataOriginal: meta },
- ...data, title: data.name, id: Utils.uuidv4(),
- time: Date.now()
- };
- return item;
- } catch (err) {
- logger.handleError(err);
- return false;
- }
- }
- }
- const video = new class extends Basic {
- constructor() { super(); }
- async process(data) {
- try {
- const metadata = (await videoMetadata.processed(data.file)).media;
- console.log("step 2.2: ", metadata);
- const meta = {
- video: metadata.track.find(tr => tr['@type'] == 'Video'),
- general: metadata.track.find(tr => tr['@type'] == 'General'),
- audio: metadata.track.find(tr => tr['@type'] == 'Audio'),
- metadataOriginal: metadata
- };
- console.log("step 2.3");
- if(!meta.video.Duration) {
- meta.video.Duration = await videoMetadata.measureDuration([data.file]);
- meta.general.Duration = meta.video.Duration;
- }
- console.log("step 2.4: ", meta.video.Duration);
- const preview = await fetch(await videoMetadata.createVideoThumbnail(data.file)).then(res => res.blob());
- data = this.clear(data);
- const item = { meta, ...data, time: Date.now(), title: data.name, id: Utils.uuidv4(), preview };
- console.log("final item is ", item);
- return item;
- } catch (err) {
- console.log("meta catch 1", err);
- logger.handleError(err);
- return false;
- }
- }
- }
- const audio = new class extends Basic {
- constructor() { super(); }
- async process(data) {
- try {
- const url = URL.createObjectURL(data.file);
- const metadata = await new Promise(resolve => musicMetadata.fetchFromUrl(url).then(resolve));
- //URL.revokeObjectURL(url);
- const payload = {
- metadataOriginal: metadata,
- description: metadata.common.comment,
- moods: ["Bright", "Calm", "Fragile", "Fun", "Happy", "Love", "Mellow", "Playful"],
- genres: metadata.common.genre || [],
- instruments: ["Drums", "Electric guitar", "Female oohs aahs"],
- bitrate: metadata.format.bitrate,
- artist: metadata.common.artist,
- histogramData: await AudioVisualizer.visualizeAudio(url, { samples: 40 })
- };
- //delete data.file;
- data.blob = data.file; //await fetch(data.src).then(res => res.blob());
- //delete data.src;
- const item = {
- ...data, name: metadata.common.title || data.name,
- meta: payload, id: Utils.uuidv4(), time: Date.now()
- };
- return item;
- } catch (err) {
- logger.handleError(err);
- return false;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement