API bug fixes. Clean up. New util functions. Highlight times for newer files.
This commit is contained in:
72
src/lib/ae_utils/ae_utils__files.ts
Normal file
72
src/lib/ae_utils/ae_utils__files.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
// These are all file related functions.
|
||||
|
||||
export let format_bytes = function format_bytes(
|
||||
bytes: number,
|
||||
decimals: number = 2
|
||||
) {
|
||||
if (bytes === 0) return '0 Bytes';
|
||||
|
||||
const k = 1024;
|
||||
const dm = decimals < 0 ? 0 : decimals;
|
||||
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
|
||||
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
|
||||
}
|
||||
|
||||
// Updated 2024-08-12
|
||||
export let guess_file_name = function guess_file_name(filename_string: string) {
|
||||
// console.log('*** guess_file_name() ***');
|
||||
if (!filename_string) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if (filename_string.includes('.')) {
|
||||
let file_name = filename_string.substring(0, filename_string.lastIndexOf('.'));
|
||||
// console.log(file_name);
|
||||
return file_name;
|
||||
} else {
|
||||
return filename_string;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Updated 2024-08-12
|
||||
export let guess_file_extension = function guess_file_extension(filename_string: string) {
|
||||
// console.log('*** guess_file_extension() ***');
|
||||
if (!filename_string) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if (!filename_string.includes('.')) {
|
||||
return '';
|
||||
}
|
||||
|
||||
let file_extension = filename_string.substring(filename_string.lastIndexOf('.') + 1, filename_string.length) || filename_string;
|
||||
// console.log(file_extension);
|
||||
return file_extension;
|
||||
}
|
||||
|
||||
|
||||
// Updated 2024-08-12
|
||||
export let get_file_hash = async function get_file_hash(file) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let file_reader = new FileReader();
|
||||
|
||||
file_reader.onload = async function() {
|
||||
if (file_reader.result.byteLength !== file.size) {
|
||||
console.log('File was not read completely');
|
||||
reject("Error reading the file");
|
||||
}
|
||||
|
||||
const hash_buffer = await crypto.subtle.digest('SHA-256', file_reader.result);
|
||||
const hash_array = Array.from(new Uint8Array(hash_buffer));
|
||||
const hash_hex = hash_array.map(b => b.toString(16).padStart(2, '0')).join('');
|
||||
|
||||
resolve(hash_hex);
|
||||
};
|
||||
|
||||
file_reader.readAsArrayBuffer(file);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user