Now with a better download file container thing. Can change open with OS.

This commit is contained in:
Scott Idem
2024-10-07 18:30:09 -04:00
parent 03e6117024
commit c3f4832f48
5 changed files with 318 additions and 63 deletions

View File

@@ -106,6 +106,7 @@ export let get_object = async function get_object(
}
}
// Handle the case where there is no Blob expected to be returned. Mainly JSON and text data.
if (!return_blob) {
let response_data_promise = await axios_api.get(
endpoint,
@@ -214,6 +215,26 @@ export let get_object = async function get_object(
if (log_lvl > 2) {
console.log(error);
}
// Post file download message
try {
if (typeof window !== 'undefined') {
window.postMessage({
type: 'api_download_data',
status: 'complete',
task_id: task_id,
endpoint: endpoint,
filename: filename,
size_total: 0,
size_loaded: 0,
percent_completed: 0,
},
'*'
);
}
} catch (error) {
console.log('Error posting message to window:', error);
}
return null; // Returning null since there were no results
}
@@ -265,7 +286,7 @@ export let get_object = async function get_object(
} else if (response_data_promise === null) {
// Less common, but expected response if no results were returned.
if (log_lvl) {
console.log('Returning null. This is expected if no results were found.');
console.log('Returning null. This is expected if no results were found. (404)');
}
return response_data_promise;
} else if (response_data_promise === false) {
@@ -274,10 +295,13 @@ export let get_object = async function get_object(
return response_data_promise;
} else {
// This generally should not happen. It likely means the query was bad or an API issue.
console.log('Returning unknown. This should not happen in most cases.');
console.log('Returning (JSON/text) unknown. This should not happen in most cases.');
Promise.reject(new Error('fail')).then(resolved, rejected);
}
// Handle the case where a Blob is expected to be returned.
} else {
// console.log('Expecting a Blob to be returned...');
let response_data_promise = await axios_api.get(
@@ -367,6 +391,73 @@ export let get_object = async function get_object(
} else {
return response;
}
})
.catch(function (error) {
// Handle the common and expected 404 "error" first
if (error.response && error.response.status === 404) {
if (log_lvl) {
console.log('The response was a 404 not found "error". Returning null.');
}
if (log_lvl > 1) {
console.log(error.response);
}
if (log_lvl > 2) {
console.log(error);
}
// Post file download message
try {
if (typeof window !== 'undefined') {
window.postMessage({
type: 'api_download_blob',
status: 'complete',
task_id: task_id,
endpoint: endpoint,
filename: filename,
size_total: 0,
size_loaded: 0,
percent_completed: 0,
},
'*'
);
}
} catch (error) {
console.log('Error posting message to window:', error);
}
return null; // Returning null since there were no results
}
if (log_lvl) {
console.log(`Base URL: ${api_cfg['base_url']} | Endpoint: ${endpoint}`);
console.log('Error Message:', error.message); // Is this needed here or below in the in the else portion???
if (error.response) {
// The request was made and the server responded with a status code that falls out of the range of 2xx
console.log('Error Response Data', error.response.data);
console.log('Error Response Status', error.response.status);
console.log('Error Response Headers', error.response.headers);
} else if (error.request) {
// The request was made but no response was received `error.request` is an instance of XMLHttpRequest in the browser and an instance of http.ClientRequest in node.js
if (log_lvl > 1) {
console.log('Error Request', error.request);
}
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error Message', error.message);
}
}
if (error.code === 'ECONNABORTED') {
// Timeout Error (You can implement retry here where suitable)
console.log('Timeout Error: ', error.message);
}
if (log_lvl) {
console.log('The response was an error. Returning false.');
}
return false; // Returning false since something may have gone wrong. This includes timeouts. Also more in line with what the API returns.
// return error;
});
if (response_data_promise) {
@@ -377,6 +468,16 @@ export let get_object = async function get_object(
// return test_blob;
// console.log(response_data_promise.blob());
return response_data_promise;
} else if (response_data_promise === null) {
// Less common, but expected response if no results were returned.
if (log_lvl) {
console.log('Returning null. This is expected if no results were found. (404)');
}
return response_data_promise;
} else if (response_data_promise === false) {
// Not common, but expected response if the request to the API had an issue.
console.log('Returning false. There may have been an issue with this request.');
return response_data_promise;
} else {
// This generally should not happen. It likely means the query was bad or an API issue.
console.log('Returning (blob) unknown. This should not happen in most cases.');

View File

@@ -649,11 +649,11 @@ export let download_hosted_file = async function download_hosted_file(
{
api_cfg,
hosted_file_id,
return_file=true,
return_file = true,
filename,
auto_download=false,
params={},
log_lvl=0
auto_download = false,
params = {},
log_lvl = 0
} : {
api_cfg: any,
hosted_file_id: string,
@@ -678,7 +678,7 @@ export let download_hosted_file = async function download_hosted_file(
api_cfg: api_cfg,
endpoint: endpoint,
params: params,
return_blob: true,
return_blob: return_file,
filename: filename,
auto_download: auto_download,
task_id: task_id,

View File

@@ -445,6 +445,7 @@ export let close_event_file_as_modal = function close_event_file_as_modal({}) {
items-center
basis-4/5
max-w-full
overflow-y-auto
"
>

View File

@@ -1,11 +1,18 @@
<script lang="ts">
export let log_lvl: number = 0;
// *** Import Svelte core
import { onMount, tick } from 'svelte';
import { fade, scale, fly } from 'svelte/transition';
import type { key_val } from '$lib/ae_stores';
import { ae_util } from '$lib/ae_utils/ae_utils';
import { api } from '$lib/api';
import { ae_snip, ae_loc, ae_sess, ae_api, ae_trig, slct, slct_trigger } from '$lib/ae_stores';
import { events_loc, events_sess, events_slct, events_trigger } from '$lib/ae_events_stores';
import { events_func } from '$lib/ae_events_functions';
import Element_ae_crud from '$lib/element_ae_crud.svelte';
// *** Import Aether core variables and functions
// import { ae } from 'aether_npm_lib';
@@ -40,8 +47,10 @@ export let open_method: null|string = 'download'; // modal, download, native ope
export let modal_title: string = '';
// *** Set initial variables
let ae_promises: key_val = {};
let ae_downloads: key_val = {};
let ae_promises: key_val = {};
let ae_tmp: key_val = {};
let ae_triggers: key_val = {};
let open_file_clicked: null|boolean = null;
let open_file_status: null|string = null; // null, 'checking_cache', 'checking_cache_failed', 'downloading_file', 'downloading_file_failed', 'opening_file', 'opening_file_failed', 'opening_file_success'
@@ -228,9 +237,7 @@ async function handle_open_file() {
</script>
<div class="event_launcher_file_cont">
<span class="event_file_action">
<div class="event_launcher_file_cont flex flex-col md:flex-row gap-1 wrap items-center justify-between w-full max-w-full">
{#if open_file_clicked}
<div class="open_file_clicked alert" in:fade="{{ duration: 250 }}" out:fade="{{ duration: 2000 }}">
@@ -264,7 +271,9 @@ async function handle_open_file() {
{/if}
<!-- First - Handle opening using a modal. This applies to all Launcher app modes (default, onsite, native) -->
<span class="event_file_action">
<!-- First [WORKING!] - Handle opening using a modal. This applies to all Launcher app modes (default, onsite, native) -->
{#if (session_type == 'poster' || open_method == 'modal')}
<!-- <a
href="/event/file/{event_file_obj.event_file_id_random}/download"
@@ -278,7 +287,6 @@ async function handle_open_file() {
<span class="fas fa-paper-plane" class:hidden="{hide_launch_icon}"></span> {ae_util.shorten_filename({filename: event_file_obj.filename, max_length: max_filename_length})}
</a> -->
<button
class="btn btn-lg variant-ghost-primary"
on:click={() => {
$events_sess.launcher.modal__open = event_file_obj.event_file_id_random;
if (!modal_title) {
@@ -311,7 +319,12 @@ async function handle_open_file() {
// tick();
}
}}
title={`${event_file_obj.filename} [BTN] -- SHA256 hash: ${event_file_obj.hash_sha256.slice(0, 10)}...`}
class="
btn btn-sm md:btn-md lg:btn-lg
variant-ghost-primary
min-w-96
"
title={`Open this file in a modal window:\n${event_file_obj.filename}\n[API] SHA256: ${event_file_obj.hash_sha256.slice(0, 10)}...\nHosted ID: ${event_file_obj.hosted_file_id_random} Event File ID: ${event_file_obj.event_file_id_random}`}
>
{#if (screen_saver_exts.includes(event_file_obj.extension))}
<span class="fas fa-chart-bar m-1" class:hidden="{hide_launch_icon}"></span>
@@ -324,7 +337,7 @@ async function handle_open_file() {
<!-- {#if ($events_loc.launcher.app_mode == 'native')} -->
<!-- Second - Handle opening a file. This applies to all Launcher app modes (default, onsite, native) -->
<!-- Second [NOT WORKING!!!] - Handle opening a file. This applies to all Launcher app modes (default, onsite, native) -->
{:else if ($events_loc.launcher.app_mode == 'native')}
<a
href="/event/file/{event_file_obj.event_file_id_random}/download?use_os=true"
@@ -339,7 +352,8 @@ async function handle_open_file() {
</a>
{:else if ($events_loc.launcher.app_mode == 'onsite' && (event_file_obj.extension == 'ppt' || event_file_obj.extension == 'pptx') && event_file_obj.open_in_os == 'win')}
<!-- Third [NOT WORKING!!!] - Handle opening a file. This applies to all Launcher app modes (default, onsite, native) -->
<!-- {:else if ($events_loc.launcher.app_mode == 'onsite' && (event_file_obj.extension == 'ppt' || event_file_obj.extension == 'pptx') && event_file_obj.open_in_os == 'win')}
<a
href="/event/file/{event_file_obj.event_file_id_random}/download?use_os=true" download
class="ae_btn btn_info {btn_size}"
@@ -349,47 +363,79 @@ async function handle_open_file() {
title={`${event_file_obj.filename} [A] -- SHA256 hash: ${event_file_obj.hash_sha256.slice(0, 10)}...`}
>
<span class="fas fa-paper-plane" class:hidden="{hide_launch_icon}"></span> {ae_util.shorten_filename({filename: event_file_obj.filename, max_length: max_filename_length})}
</a>
</a> -->
<!-- Last [WORKING!] - Handle opening a file. This applies to all Launcher app modes (default, onsite, native) -->
{:else}
<button
class="ae_btn btn_info {btn_size}"
on:click={() => {
ae_promises[event_file_obj.event_file_id_random]
ae_promises[event_file_obj.event_file_id_random] = download_event_file({ 'event_file_id': event_file_obj.event_file_id_random, 'return_file': true, filename: event_file_obj.filename, auto_download: true, log_lvl: 1 })
.then((result) => {
console.log('Downloaded file:');
console.log(result);
let new_filename = event_file_obj.filename;
if (result === null) {
ae_promises[event_file_obj.event_file_id_random] = null;
}
})
if ($events_loc.launcher.app_mode == 'onsite' && (event_file_obj.extension == 'ppt' || event_file_obj.extension == 'pptx') && event_file_obj.open_in_os == 'win') {
// Example: the_new_filename.pptxwin
new_filename = event_file_obj.filename + 'win';
}
// ae_promises[event_file_obj.event_file_id_random]
ae_promises[event_file_obj.event_file_id_random] = api.download_hosted_file({
api_cfg: $ae_api,
hosted_file_id: event_file_obj.hosted_file_id_random, // +'x'
return_file: true,
filename: new_filename,
auto_download: true,
log_lvl: 1
});
// window.postMessage({ type: 'download_event_file', event_file_id: event_file_obj.event_file_id_random, filename: event_file_obj.filename, auto_download: true }, '*');
}}
title={`${event_file_obj.filename} [API] -- SHA256 hash: ${event_file_obj.hash_sha256.slice(0, 10)}...`}
class="
btn btn-sm md:btn-md lg:btn-lg
variant-ghost-primary
min-w-72 lg:min-w-96
"
title={`Download this file:\n${event_file_obj.filename}\n[API] SHA256: ${event_file_obj.hash_sha256.slice(0, 10)}...\nHosted ID: ${event_file_obj.hosted_file_id_random} Event File ID: ${event_file_obj.event_file_id_random}`}
>
{#await ae_promises[event_file_obj.event_file_id_random]}
<span class="fas fa-spinner fa-spin"></span>
Downloading...
<span>
{#if ae_downloads[event_file_obj.event_file_id_random]}
{ae_downloads[event_file_obj.event_file_id_random].percent_completed}%
<span class="text-sm">
<span class="fas fa-spinner fa-spin mx-0.5"></span>
<span class="">
Downloading
{#if $ae_sess.api_download_kv[event_file_obj.hosted_file_id_random]}
{$ae_sess.api_download_kv[event_file_obj.hosted_file_id_random].percent_completed}%
{/if}
:
</span>
</span>
{:then result}
<span class="text-xs">
<span class="fas fa-{ae_util.file_extension_icon(event_file_obj.extension)} mx-0.5"></span>
{event_file_obj.extension}
{#if result === null}
<span>
<span class="fas fa-exclamation-triangle mx-1"></span>
Download failed!
</span>
{/if}
</span>
{:then}
<span class="fas fa-paper-plane" class:hidden="{hide_launch_icon}"></span> {ae_util.shorten_filename({filename: event_file_obj.filename, max_length: max_filename_length})}
{#if ae_promises[event_file_obj.event_file_id_random] === null}
<span class="fas fa-exclamation-triangle"></span>
Download failed!
{/if}
{/await}
<span class="grow text-xs md:text-sm border-l border-gray-400 pl-1">
<!-- {event_file_obj.filename_no_ext} -->
<!-- {ae_util.shorten_filename({filename: event_file_obj.filename_w_ext, max_length: 40})} -->
{ae_util.shorten_string({string: event_file_obj.filename_no_ext, begin_length: 45, max_length: 65})}
<!-- {event_file_obj.filename_no_ext.slice(0, 35)} -->
</span>
<span
class="badge variant-glass-success hover:variant-filled-success text-sm"
class:hidden={!event_file_obj.file_purpose}
>
{event_file_obj.file_purpose}
</span>
</button>
<!-- <a
href="/event/file/{event_file_obj.event_file_id_random}/download"
download
@@ -403,29 +449,138 @@ async function handle_open_file() {
</a> -->
{/if}
<!-- <a href="/event/file/{event_file_obj.event_file_id_random}/download?filename={event_file_obj.filename}&use_os=true" class="ae_btn btn_info {btn_size}">{event_file_obj.filename}</a> -->
</span>
<span class="event_file_meta" class:hidden="{hide_meta}">
<span class="event_file_created_on" class:hidden="{hide_created_on}">
{ae_util.iso_datetime_formatter(event_file_obj.created_on, 'datetime_short')}
</span>
<span class="event_file_size" class:hidden="{hide_size}">
{#if event_file_obj.file_size}{ae_util.format_bytes(event_file_obj.file_size)}{/if}
</span>
<span class="event_file_os" class:hidden="{hide_os}">
<span
class="event_file_meta grow text-sm text-gray-500 flex sm:flex-col md:flex-row gap-1 wrap items-center justify-between w-64 max-w-64 font-mono"
class:hidden="{hide_meta}"
>
<button
on:click={() => {
// let new_filename = event_file_obj.filename;
// if ($events_loc.launcher.app_mode == 'onsite' && (event_file_obj.extension == 'ppt' || event_file_obj.extension == 'pptx') && event_file_obj.open_in_os == 'win') {
// // Example: the_new_filename.pptxwin
// new_filename = event_file_obj.filename + 'win';
// }
// ae_promises[event_file_obj.event_file_id_random]
ae_promises[event_file_obj.event_file_id_random] = api.download_hosted_file({
api_cfg: $ae_api,
hosted_file_id: event_file_obj.hosted_file_id_random, // +'x'
return_file: true,
filename: event_file_obj.filename,
auto_download: true,
log_lvl: 1
});
// window.postMessage({ type: 'download_event_file', event_file_id: event_file_obj.event_file_id_random, filename: event_file_obj.filename, auto_download: true }, '*');
}}
class="event_file_os"
class:hidden="{hide_os || 1==1}"
>
{#if event_file_obj.open_in_os == 'win'}
<span class="fab fa-windows"></span> Win
{:else if event_file_obj.open_in_os == 'mac'}
<span class="fab fa-apple"></span> Mac
{:else}
<!-- <span class="fas fa-folder-open"></span> -->
<span class="fas fa-folder-open"></span>
{/if}
</button>
<Element_ae_crud
trigger_patch={ae_triggers.open_in_os}
api_cfg={$ae_api}
object_type={'event_file'}
object_id={event_file_obj.event_file_id_random}
field_name={'open_in_os'}
field_type={'button'}
field_value={ae_tmp.value__open_in_os}
allow_null={false}
hide_edit_btn={true}
outline_element={false}
show_crud={false}
display_inline={true}
class_li={''}
on:ae_crud_updated={e => {
console.log(`ae_crud_updated:`, e.detail);
events_func.handle_load_ae_obj_id__event_file({
api_cfg: $ae_api,
event_file_id: event_file_obj?.event_file_id_random,
log_lvl: log_lvl
});
}}
>
<!-- {(event_file_obj?.open_in_os ? 'Hidden' : 'Not Hidden')} -->
<button
on:click={() => {
// Go from null to win, win to mac, mac to null, null to win, etc.
if (!event_file_obj?.open_in_os) {
ae_tmp.value__open_in_os = 'win';
} else if (event_file_obj?.open_in_os == 'win') {
ae_tmp.value__open_in_os = 'mac';
} else if (event_file_obj?.open_in_os == 'mac') {
ae_tmp.value__open_in_os = null;
} else {
ae_tmp.value__open_in_os = null;
}
// $events_slct.exhibit_tracking_obj.open_in_os = !event_file_obj?.open_in_os;
ae_triggers.open_in_os = true;
}}
class="btn btn-sm transition-all hover:transition-all *:hover:inline"
class:variant-soft-success={event_file_obj?.open_in_os=='win'}
class:variant-soft-warning={event_file_obj?.open_in_os=='mac'}
disabled={!$ae_loc.trusted_access}
title="Open with: {event_file_obj?.open_in_os ?? 'Default'}"
>
{#if event_file_obj?.open_in_os == 'win'}
<span class="fab fa-windows m-1"></span>
Windows
{:else if event_file_obj?.open_in_os == 'mac'}
<!-- <span class="fas fa-toggle-off m-1"></span> -->
<span class="fab fa-apple m-1"></span>
<span class="hidden">
macOS
</span>
{:else}
<span class="fas fa-folder-open m-1"></span>
<!-- <span class="hidden">
Default
</span> -->
{/if}
<!-- {@html (event_file_obj?.hide ? '<span class="fas fa-eye m-1"></span> Unhide?' : '<span class="fas fa-eye-slash m-1"></span> Hide?')} -->
</button>
</Element_ae_crud>
<span class="event_file_created_on" class:hidden="{hide_created_on}">
<span>
<span class="fas fa-calendar-day hidden lg:inline-block"></span>
{ae_util.iso_datetime_formatter(event_file_obj.created_on, 'date_short')}
</span>
<span>
<!-- <span class="fas fa-clock"></span> -->
{ae_util.iso_datetime_formatter(event_file_obj.created_on, 'time_12_short')}
</span>
</span>
<span class="event_file_size text-right" class:hidden="{hide_size}">
<span class="fas fa-save"></span>
{#if event_file_obj.file_size}{ae_util.format_bytes(event_file_obj.file_size)}{/if}
</span>
<!-- {#if ($events_loc.launcher.app_mode == 'native' || $events_loc.launcher.app_mode == 'onsite')} -->
<!-- {#if (show_bak_download)} -->
<a href="/event/file/{event_file_obj.event_file_id_random}/download" class="event_file_download" class:hidden="{!show_bak_download}" title="Download with original filename and extension"><span class="fas fa-download"></span></a>
<!-- <a href="/event/file/{event_file_obj.event_file_id_random}/download" class="event_file_download" class:hidden="{!show_bak_download}" title="Download with original filename and extension"><span class="fas fa-download"></span></a> -->
<!-- <a href="/event/file/{event_file_obj.event_file_id_random}/download?filename={event_file_obj.filename}&use_os=true" class="ae_btn btn_info {btn_size}">{event_file_obj.filename}</a> -->
<!-- {/if} -->
</span>

View File

@@ -22,13 +22,15 @@ let ae_promises: key_val = {
};
// Event File
let lq__event_file_obj_li = liveQuery(
() => db_events.files
$: lq__event_file_obj_li = liveQuery(async () => {
let results = await db_events.files
// .where('event_session_id_random')
.where('for_id_random')
.equals(lq__event_presenter_obj?.event_presenter_id)
.sortBy('name')
);
.reverse()
.sortBy('created_on')
return results;
});
</script>
@@ -67,10 +69,10 @@ let lq__event_file_obj_li = liveQuery(
<ul class="space-y-1">
{#each $lq__event_file_obj_li as event_file_obj, index}
<li
class="flex flex-row justify-center gap-1"
class="flex flex-col md:flex-row wrap gap justify-center"
class:hidden={!$events_loc.launcher.show_content__hidden_files && event_file_obj.hide}
>
<button
<!-- <button
disabled={!$ae_loc.trusted_access}
on:click={() => {
// ae_promises[event_file_obj.event_file_id_random]
@@ -98,11 +100,7 @@ let lq__event_file_obj_li = liveQuery(
:
</span>
{:then}
<!-- <span class="fas fa-download mx-1"></span> -->
<span class="fas fa-{ae_util.file_extension_icon(event_file_obj.extension)}"></span>
<!-- <span class="text-sm">
Download:
</span> -->
{/await}
<span class="grow">
@@ -115,7 +113,7 @@ let lq__event_file_obj_li = liveQuery(
>
{event_file_obj.file_purpose}
</span>
</button>
</button> -->
<Event_launcher_file_cont
event_file_obj={event_file_obj}