Advertisement
KoctrX

Untitled

Oct 26th, 2021
244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.58 KB | None | 0 0
  1. import Utils from './Utils';
  2. import logger from './logger';
  3. import * as musicMetadata from 'music-metadata-browser';
  4. import videoMetadata from './VideoMetadata';
  5. import AudioVisualizer from './AudioVisualizer';
  6. import { store } from '../store';
  7.  
  8. export default new class {
  9. parseFiletype(blob) {
  10. try {
  11. return `.${blob.type.split('/')[1]}`;
  12. } catch (err) {
  13. return '';
  14. }
  15. }
  16.  
  17. async downloadingFile(url, progress = () => { }) {
  18. const response = await fetch(url);
  19.  
  20. const contentLength = response.headers.get('content-length');
  21. const total = parseInt(contentLength, 10);
  22. let loaded = 0;
  23.  
  24. const res = new Response(new ReadableStream({
  25. async start(controller) {
  26. const reader = response.body.getReader();
  27. for (; ;) {
  28. const { done, value } = await reader.read();
  29. if (done) break;
  30. loaded += value.byteLength;
  31. progress({ loaded, total })
  32. controller.enqueue(value);
  33. }
  34.  
  35. controller.close();
  36. },
  37. }));
  38.  
  39. const blob = await res.blob();
  40. return blob.slice(0, blob.size, response.headers.get('content-type'));
  41. }
  42.  
  43. async generateFileData(data, opts = {}) {
  44. if (!data) return false;
  45. let file = false;
  46. let fileName = '';
  47.  
  48. if (typeof data == 'string') {
  49. const name = opts.name || `Untitle_${Date.now()}`;
  50.  
  51. let sw = store.state.swal({
  52. title: 'Downloading <b>0</b>%',
  53. allowEscapeKey: false,
  54. allowOutsideClick: false,
  55. showConfirmButton: false,
  56. didOpen: () => store.state.swal.showLoading()
  57. });
  58.  
  59. const blob = await this.downloadingFile(data, ({ loaded, total }) => {
  60. store.state.swal.getTitle().querySelector('b').innerHTML = Math.round(loaded / total * 100);
  61. });
  62.  
  63. const fileType = this.parseFiletype(blob);
  64. store.state.swal.close();
  65.  
  66. fileName = `${name}${fileType}`;
  67. file = Utils.blobToFile(blob, fileName);
  68. } else {
  69. file = data;
  70. fileName.data.name;
  71. }
  72.  
  73. return {
  74. type: file.type, size: file.size,
  75. name: fileName, lastModified: Date.now(),
  76. file, ...(await this.generatePayload(file, opts))
  77. };
  78. }
  79.  
  80. async getProcessedFile(data = false, opts = {}) {
  81. const result = await this.generateFileData(data, opts);
  82. if (!result) return false;
  83.  
  84. return this.processFileByType(result);
  85. }
  86.  
  87. async processFileByType(data) {
  88. if (data && data.type) {
  89. if (/^(audio)/g.test(data.type))
  90. return audio.process(data);
  91.  
  92. if (/^(video)/g.test(data.type))
  93. return video.process(data);
  94.  
  95. if (/^(image)/g.test(data.type))
  96. return image.process(data);
  97. }
  98. console.log("step 1.2");
  99. return false;
  100. }
  101.  
  102. async generatePayload(file, opts = {}) {
  103. let payload = {};
  104. if (opts.api_id) payload.api_id = opts.api_id;
  105.  
  106. if (file.type.includes('image')) {
  107. const blobURL = URL.createObjectURL(file);
  108. const arrayBuffer = await fetch(blobURL).then(res => res.arrayBuffer());
  109. URL.revokeObjectURL(blobURL);
  110.  
  111. payload = { ...payload, arrayBuffer };
  112. } else {
  113.  
  114. }
  115.  
  116. return payload;
  117. }
  118. }
  119.  
  120. class Basic {
  121. clear(data) {
  122. //delete data.file;
  123. data.blob = data.file; //await fetch(data.src).then(res => res.blob());
  124. delete data.src;
  125.  
  126. return data;
  127. }
  128. }
  129.  
  130. const image = new class extends Basic {
  131. constructor() { super(); }
  132.  
  133. async process(data) {
  134. try {
  135. let meta;
  136. try {
  137. meta = await window.ExifReader.load(data.arrayBuffer || data.file);
  138. } catch(err) {
  139. //console.error(err);
  140. meta = {};
  141. }
  142.  
  143. let parsedMeta = Object.entries(meta).reduce((result, [key, value]) => {
  144. if (typeof value.value != 'undefined')
  145. result[key] = value.value;
  146.  
  147. return result;
  148. }, {});
  149.  
  150. data = this.clear(data);
  151. const item = {
  152. thumb: await Utils.generateImageThumb(data.blob, 200, 200),
  153. meta: { ...parsedMeta, metadataOriginal: meta },
  154. ...data, title: data.name, id: Utils.uuidv4(),
  155. time: Date.now()
  156. };
  157.  
  158. return item;
  159. } catch (err) {
  160. logger.handleError(err);
  161. return false;
  162. }
  163. }
  164. }
  165.  
  166. const video = new class extends Basic {
  167. constructor() { super(); }
  168.  
  169. async process(data) {
  170. try {
  171.  
  172. const metadata = (await videoMetadata.processed(data.file)).media;
  173. console.log("step 2.2: ", metadata);
  174.  
  175. const meta = {
  176. video: metadata.track.find(tr => tr['@type'] == 'Video'),
  177. general: metadata.track.find(tr => tr['@type'] == 'General'),
  178. audio: metadata.track.find(tr => tr['@type'] == 'Audio'),
  179. metadataOriginal: metadata
  180. };
  181.  
  182. console.log("step 2.3");
  183.  
  184. if(!meta.video.Duration) {
  185. meta.video.Duration = await videoMetadata.measureDuration([data.file]);
  186. meta.general.Duration = meta.video.Duration;
  187. }
  188.  
  189. console.log("step 2.4: ", meta.video.Duration);
  190.  
  191. const preview = await fetch(await videoMetadata.createVideoThumbnail(data.file)).then(res => res.blob());
  192. data = this.clear(data);
  193. const item = { meta, ...data, time: Date.now(), title: data.name, id: Utils.uuidv4(), preview };
  194.  
  195. console.log("final item is ", item);
  196.  
  197. return item;
  198. } catch (err) {
  199. console.log("meta catch 1", err);
  200. logger.handleError(err);
  201. return false;
  202. }
  203. }
  204. }
  205.  
  206. const audio = new class extends Basic {
  207. constructor() { super(); }
  208.  
  209. async process(data) {
  210. try {
  211. const url = URL.createObjectURL(data.file);
  212. const metadata = await new Promise(resolve => musicMetadata.fetchFromUrl(url).then(resolve));
  213. //URL.revokeObjectURL(url);
  214.  
  215. const payload = {
  216. metadataOriginal: metadata,
  217. description: metadata.common.comment,
  218. moods: ["Bright", "Calm", "Fragile", "Fun", "Happy", "Love", "Mellow", "Playful"],
  219. genres: metadata.common.genre || [],
  220. instruments: ["Drums", "Electric guitar", "Female oohs aahs"],
  221. bitrate: metadata.format.bitrate,
  222. artist: metadata.common.artist,
  223. histogramData: await AudioVisualizer.visualizeAudio(url, { samples: 40 })
  224. };
  225.  
  226. //delete data.file;
  227. data.blob = data.file; //await fetch(data.src).then(res => res.blob());
  228. //delete data.src;
  229.  
  230. const item = {
  231. ...data, name: metadata.common.title || data.name,
  232. meta: payload, id: Utils.uuidv4(), time: Date.now()
  233. };
  234.  
  235. return item;
  236. } catch (err) {
  237. logger.handleError(err);
  238. return false;
  239. }
  240. }
  241. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement