Files
photoassistant/internal/js/files_support.js

649 lines
25 KiB
JavaScript

// GLOBAL ICON array
ICON={}
ICON["Import"]="import"
ICON["Storage"]="db"
ICON["Bin"]="trash"
// grab all selected thumbnails and return a <div> containing the thumbnails
// with extra yr and date attached as attributes so we can set the default
// dir name for a move directory - not used in del, but no harm to include them
function GetSelnAsDiv()
{
seln=''
$('.highlight').each(function( index ) {
seln+='<div fname="' + $(this).attr('fname') + '" yr="' + $(this).attr('yr') +
'" date="' + $(this).attr('date') +
'" class="px-1 col col-auto">' + $(this).children().parent().html() + '</div>'
seln+='<input type="hidden" name="eid-'+index+'" value="'+$(this).attr('id')+'">'
} )
return '<div class="row col-12">'+seln+'</div>'
}
// return a list of eid=<id> for each selected thumbnail
function GetSelnAsData()
{
to_del=''
$('.highlight').each(function( index ) { to_del+='&eid-'+index+'='+$(this).attr('id') } )
return to_del
}
// use an ajax POST to force an AI scan on the selected image(s)
function RunAIOnSeln(person)
{
post_data = GetSelnAsData()
post_data += '&person='+person.replace('ai-','')
$.ajax({ type: 'POST', data: post_data, url: '/run_ai_on', success: function(data){ CheckForJobs() } })
}
// code to change the associated image/icon when the move to selection box (import or storage paths) is changed
function change_rp_sel()
{
icon_url = $('option:selected', '#rp_sel').attr('icon_url')
$('#move_path_icon').html( '<svg id="move_path_icon" width="20" height="20" fill="currentColor"><use xlink:href="'
+ icon_url + '"></svg>' )
seld_ptype=$('option:selected', '#rp_sel').attr('path_type')
$('#move_path_type').val( seld_ptype )
// clear all 'existing' buttons
$('.move_Import').addClass('d-none')
$('.move_Storage').addClass('d-none')
// show just selected path's (relevant) buttons
$('.move_'+seld_ptype).removeClass('d-none')
}
// POST to see if there are any other existing directories named around this date
// (if so display them as options for a move)
function GetExistingDirsAsDiv( dt, divname, ptype )
{
$.ajax({
type: 'POST', data: null, url: '/get_existing_paths/'+dt,
success: function(data) {
$('#'+divname).html(data)
dirs = JSON.parse(data)
s=''
dirs.forEach( function(item, index) {
if( item.ptype != ptype )
vis = 'd-none '
else
vis = ''
s+= '<button class="btn btn-outline-primary move_'+item.ptype+ ' ' + vis + '" '
s+= 'onClick="$(\'#prefix\').val(\''+item.prefix.replace("\'","\\\'")+'\'); '
s+='$(\'#suffix\').val(\''+item.suffix.replace("\'","\\\'")+'\');return false;">'
s+=item.prefix+item.suffix
s+='</button>'
} )
if( s == '' )
$('#existing').html('')
else
$('#move_'+ptype).removeClass('invisible')
$('#'+divname).html(s)
}
} )
}
// wrapper to do some clean up before POST to /move_files or /delete_files
// used to remove the highlighted item(s) && reset the numbering so highlighting continues to work
function MoveOrDelCleanUpUI()
{
// remove the images being moved (so UI immediately 'sees' the move)
$("[name^=eid-]").each( function() { $('#'+$(this).attr('value')).remove() } )
// reorder the images via ecnt again, so future highlighting can work
document.mf_id=0; $('.figure').each( function() { $(this).attr('ecnt', document.mf_id ); document.mf_id++ } )
$('#dbox').modal('hide')
}
// show the DBox for a move file, includes all thumbnails of selected files to move
// and a pre-populated folder to move them into, with text field to add a suffix
function MoveDBox(path_details, db_url)
{
$('#dbox-title').html('Move Selected File(s) to new directory in Storage Path')
div =`
<div class="form-row col-12">
<p class="col">Moving the following files?</p>
</div>
<form id="mv_fm" class="form form-control-inline col-12">
<input id="move_path_type" name="move_path_type" type="hidden"
`
div += ' value="' + path_details[0].type + '"></input>'
div+=GetSelnAsDiv()
yr=$('.highlight').first().attr('yr')
dt=$('.highlight').first().attr('date')
div+='<div class="row">Use Existing Directory (in the chosen path):</div><div id="existing"></div>'
GetExistingDirsAsDiv( dt, "existing", path_details[0].type )
div+=`
<div class="input-group my-3">
<alert class="alert alert-primary my-auto py-1">
`
// NB: alert-primary here is a hack to get the bg the same color as the alert primary by
div+= '<svg id="move_path_icon" width="20" height="20" fill="currentColor"><use xlink:href="' + path_details[0].icon_url + '"></svg>'
div+= '<select id="rp_sel" name="rel_path" class="text-primary alert-primary py-1 border border-primary rounded" onChange="change_rp_sel()">'
for(p of path_details) {
div+= '<option path_type="'+p.type+'" icon_url="'+p.icon_url+'">'+p.path+'</option>'
}
div+= '</select>'
div+=`
</alert>
<input id="prefix" type="text" name="prefix" class="text-primary text-right form-control"
`
div+="value="+yr+'/'+dt+"-"
div+=`
"></input>
<input id="suffix" type="text" name="suffix" class="form-control" placeholder="name"> </input>
</div>
<div class="form-row col-12 mt-2">
<button onClick="$('#dbox').modal('hide'); return false;" class="btn btn-outline-secondary offset-1 col-2">Cancel</button>
<button id="move_submit" onClick="MoveOrDelCleanUpUI(); $.ajax({ type: 'POST', data: $('#mv_fm').serialize(), url: '/move_files', success: function(data) {
if( $(location).attr('pathname').match('search') !== null ) { window.location='/' }; CheckForJobs() } }); return false" class="btn btn-outline-primary col-2">Ok</button>
</div>
</form>
`
$('#dbox-content').html(div)
$('#dbox').modal('show')
$("#prefix").keypress(function (e) { if (e.which == 13) { $("#move_submit").click(); return false; } } )
$("#suffix").keypress(function (e) { if (e.which == 13) { $("#move_submit").click(); return false; } } )
}
// show the DBox for a delete/restore file, includes all thumbnails of selected files
// with appropriate coloured button to Delete or Restore files`
function DelDBox(del_or_undel)
{
to_del = GetSelnAsData()
$('#dbox-title').html(del_or_undel+' Selected File(s)')
div ='<div class="row col-12"><p class="col">' + del_or_undel + ' the following files?</p></div>'
div+=GetSelnAsDiv()
div+=`<div class="row col-12 mt-3">
<button onClick="$('#dbox').modal('hide')" class="btn btn-outline-secondary col-2">Cancel</button>
`
div+=`
<button onClick="MoveOrDelCleanUpUI(); $.ajax({ type: 'POST', data: to_del, url:
`
if( del_or_undel == "Delete" )
div+=`
'/delete_files',
success: function(data){
if( $(location).attr('pathname').match('search') !== null ) { window.location='/' }; CheckForJobs() } }); return false" class="btn btn-outline-danger col-2">Ok</button>
</div>
`
else
// just force page reload to / for now if restoring files from a search path -- a search (by name)
// would match the deleted/restored file, so it would be complex to clean up the UI (and can't reload, as DB won't be changed yet)
div+=`
'/restore_files',
success: function(data){
if( $(location).attr('pathname').match('search') !== null ) { window.location='/' }; CheckForJobs() } }); return false" class="btn btn-outline-success col-2">Ok</button>
</div>
`
$('#dbox-content').html(div)
$('#dbox').modal('show')
}
// show the DBox for a lame quick version of file details
function DetailsDBox()
{
$('#dbox-title').html('Details of Selected File(s)')
var div ='<div class="row col-12">'
$('.highlight').each(function( index ) {
div += "<div class='col-3' style='background-color:lightgray'>Name:</div><div class='col-9' style='background-color:lightgray'>" + $(this).attr('fname') + "</div>"
div += "<div class='col-3'>Date:</div><div class='col-9'>" + $(this).attr('pretty_date') + "</div>"
dir = $(this).attr('in_dir')
if( dir.slice(-1) != "/" )
dir=dir.concat('/')
div += "<div class='col-3'>Dir:</div><div class='col-9'>" + dir + "</div>"
div += "<div class='col-3'>Size:</div><div class='col-9'>" + $(this).attr('size') + " MB</div>"
div += "<div class='col-3'>Hash:</div><div class='col-9'>" + $(this).attr('hash') + "</div>"
div += "<div class='col-3'>Path Type:</div><div class='col-9'>" + $(this).attr('path_type') + "</div>"
} )
div += `
</div>
<br>
<div class="form-row col-12">
<button onClick="$('#dbox').modal('hide'); return false;" class="btn btn-outline-secondary offset-1 col-2">Cancel</button>
</div>
`
$('#dbox-content').html(div)
$('#dbox').modal('show')
}
// function to change the size of thumbnails (and resets button bar to newly
// selected size)
function ChangeSize(clicked_button,sz)
{
$('.sz-but.btn-info').removeClass('btn-info text-white').addClass('btn-outline-info')
$(clicked_button).addClass('btn-info text-white').removeClass('btn-outline-info')
$('.thumb').attr( {height: sz, style: 'font-size:'+sz+'px' } )
$('#size').val(sz)
sz=sz-22
$('.svg').height(sz);
$('.svg').width(sz);
$('.svg_cap').width(sz);
}
// DoSel is called when a click event occurs, and sets the selection via adding
// 'highlight' to the class of the appropriate thumbnails
// e == event (can see if shift/ctrl held down while left-clicking
// el == element the click is on
// this allows single-click to select, ctrl-click to (de)select 1 item, and
// shift-click to add all elements between highlighted area and clicked area,
// whether you click after highlight or before
function DoSel(e, el)
{
if( e.ctrlKey || document.fake_ctrl === 1 )
{
$(el).toggleClass('highlight')
if( document.fake_ctrl === 1 )
document.fake_ctrl=0
return
}
if( e.shiftKey || document.fake_shift === 1 )
{
st=Number($('.highlight').first().attr('ecnt'))
end=Number($('.highlight').last().attr('ecnt'))
clicked=Number($(el).attr('ecnt'))
// if we shift-click first element, then st/end are NaN, so just highlightthe one clicked
if( isNaN(st) )
{
$('.entry').slice( clicked, clicked+1 ).addClass('highlight')
return
}
if( clicked > end )
$('.entry').slice( end, clicked+1 ).addClass('highlight')
else
$('.entry').slice( clicked, st ).addClass('highlight')
if( document.fake_shift === 1 )
document.fake_shift=0
return
}
$('.highlight').removeClass('highlight')
$(el).addClass('highlight')
}
// if a selection exists, enable move & del/restore buttons otherwise disable them
function SetButtonState() {
var sel=false
$('.highlight').each(function( index ) { sel=true } )
if( sel ) {
$('#move').attr('disabled', false )
$('#del').attr('disabled', false )
} else {
$('#move').attr('disabled', true )
$('#del').attr('disabled', true )
}
}
// Check if the set of highlights are either only figures, dirs or both
// used to work out what options are shown in the file context menu
function FiguresOrDirsOrBoth() {
var figure=false
var dir=false
$('.highlight').each(function( index ) {
if( $(this).hasClass('figure') ) {
figure=true
}
if( $(this).hasClass('dir') ) {
dir=true
}
} )
if( figure & ! dir )
return "figure"
if( ! figure & dir )
return "dir"
return "both"
}
// Check if the set of highlights contain Bin and Not Bin...
// if its both, then no del/restore is possible in context menu
// otherwise can either set del or restore appropriately
function SelContainsBinAndNotBin() {
var bin=false
var not_bin=false
$('.highlight').each(function( index ) {
if( $(this).attr('path_type') == "Bin" ) {
bin=true
} else {
not_bin=true
}
} )
if( bin && not_bin )
return true
else
return false
}
// checks to see if there is no selection active
function NoSel() {
var sel=false
$('.highlight').each(function( index ) { sel=true } )
// func looks for No Selection, so if sel is true and we have a sel, return false (i.e. NOT No Sel -> Sel )
if( sel )
return false
else
return true
}
/**
* Renders a group header or entry based on the object and options.
* @param {Object} obj - The object containing file/directory details.
* @param {Object} last - Tracks the last printed group (e.g., { printed: null }).
* @param {Object} ecnt - Entry counter (e.g., { val: 0 }).
* @returns {string} - Generated HTML string.
*/
function addFigure( obj, last, ecnt)
{
let html = "";
// Grouping logic
if (OPT.grouping === "Day") {
if (last.printed !== obj.file_details.day) {
html += `<div class="row ps-3"><h6>Day: ${obj.file_details.day} of ${obj.file_details.month}/${obj.file_details.year}</h6></div>`;
last.printed = obj.file_details.day;
}
} else if (OPT.grouping === "Week") {
if (last.printed !== obj.file_details.woy) {
html += `<div class="row ps-3"><h6>Week #: ${obj.file_details.woy} of ${obj.file_details.year}</h6></div>`;
last.printed = obj.file_details.woy;
}
} else if (OPT.grouping === "Month") {
if (last.printed !== obj.file_details.month) {
html += `<div class="row ps-3"><h6>Month: ${obj.file_details.month} of ${obj.file_details.year}</h6></div>`;
last.printed = obj.file_details.month;
}
}
/*
{% if not entry_data %}
<span class="alert alert-danger p-2 col-auto"> No matches for: '{{search_term}}'</span>
{% endif %}
*/
// Image/Video/Unknown entry
if (obj.type.name === "Image" || obj.type.name === "Video" || obj.type.name === "Unknown") {
if (!OPT.folders || isTopLevelFolder(obj.in_dir.in_path.path_prefix + '/' + obj.in_dir.rel_path + '/' + obj.name, OPT.cwd)) {
const pathType = obj.in_dir.in_path.type.name;
const size = obj.file_details.size_mb;
const hash = obj.file_details.hash;
const inDir = `${obj.in_dir.in_path.path_prefix}/${obj.in_dir.rel_path}`;
const fname = obj.name;
const yr = obj.file_details.year;
const date = `${yr}${String(obj.file_details.month).padStart(2, '0')}${String(obj.file_details.day).padStart(2, '0')}`;
const prettyDate = `${obj.file_details.day}/${obj.file_details.month}/${obj.file_details.year}`;
const type = obj.type.name;
html += `
<figure id="${obj.id}" ecnt="${ecnt}" class="col col-auto g-0 figure entry m-1"
path_type="${pathType}" size="${size}" hash="${hash}" in_dir="${inDir}"
fname="${fname}" yr="${yr}" date="${date}" pretty_date="${prettyDate}" type="${type}">
${renderMedia(obj)}
</figure>
`;
}
}
// Directory entry
else if (obj.type.name === "Directory" && OPT.folders) {
const dirname = obj.dir_details.rel_path.length
? `${obj.dir_details.in_path.path_prefix}/${obj.dir_details.rel_path}`
: obj.dir_details.in_path.path_prefix;
if (isTopLevelFolder(dirname, OPT.cwd)) {
html += `
<figure class="col col-auto g-0 dir entry m-1" id="${obj.id}" ecnt="${ecnt}" dir="${dirname}" type="Directory">
<svg class="svg" width="${OPT.size - 22}" height="${OPT.size - 22}" fill="currentColor">
<use xlink:href="/internal/icons.svg#Directory"></use>
</svg>
<figcaption class="svg_cap figure-caption text-center text-wrap text-break">${obj.name}</figcaption>
</figure>
`;
html += `<script>f=$('#${obj.id}'); w=f.find('svg').width(); f.find('figcaption').width(w);</script>`;
}
}
$('#figures').append( html )
return
}
// Helper function to render media (image/video/unknown)
function renderMedia(obj) {
const isImageOrUnknown = obj.type.name === "Image" || obj.type.name === "Unknown";
const isVideo = obj.type.name === "Video";
const path = `${obj.in_dir.in_path.path_prefix}/${obj.in_dir.rel_path}/${obj.name}`;
const thumb = obj.file_details.thumbnail
? `<a href="${path}"><img alt="${obj.name}" class="thumb" height="${OPT.size}" src="data:image/jpeg;base64,${obj.file_details.thumbnail}"></a>`
: `<a href="${path}"><svg width="${OPT.size}" height="${OPT.size}" fill="white"><use xlink:href="/internal/icons.svg#unknown_ftype"/></svg></a>`;
let mediaHtml = `<div style="position:relative; width:100%">${thumb}`;
if (isImageOrUnknown) {
if (OPT.search_term) {
mediaHtml += `
<div style="position:absolute; bottom: 0px; left: 2px;">
<svg width="16" height="16" fill="white"><use xlink:href="/internal/icons.svg#${getLocationIcon(obj)}"/></svg>
</div>
`;
}
mediaHtml += `
<div id="s${obj.id}" style="display:none; position:absolute; top: 50%; left:50%; transform:translate(-50%, -50%);">
<img height="64px" src="/internal/throbber.gif">
</div>
`;
} else if (isVideo) {
mediaHtml += `
<div style="position:absolute; top: 0px; left: 2px;">
<svg width="16" height="16" fill="white"><use xlink:href="/internal/icons.svg#film"/></svg>
</div>
`;
if (OPT.search_term) {
mediaHtml += `
<div style="position:absolute; bottom: 0px; left: 2px;">
<svg width="16" height="16" fill="white"><use xlink:href="/internal/icons.svg#${getLocationIcon(obj)}"/></svg>
</div>
`;
}
}
mediaHtml += `</div>`;
return mediaHtml;
}
// Helper: Check if path is a top-level folder of cwd
function isTopLevelFolder(path, cwd) {
// Implement your logic here
return true; // Placeholder
}
// Helper: Get location icon (placeholder)
function getLocationIcon(obj) {
return ICON[obj.in_dir.in_path.type.name]
}
// POST to get entry ids, and then getPage for a specified directory
function getDirEntries(dir_id, back)
{
data={}
data.dir_id=dir_id
data.back=back
$.ajax({
type: 'POST',
url: '/get_dir_entries',
data: JSON.stringify(data), // Stringify the data
contentType: 'application/json', // Set content type
dataType: 'json', // Expect JSON response
success: function(res) {
document.entries=res
// rebuild entryList/pageList as each dir comes with new entries
entryList=res.map(obj => obj.id);
pageList=entryList.slice(0, OPT.how_many)
if( back )
document.back_id = res[0].in_dir.eid
drawPageOfFigures()
},
error: function(xhr, status, error) {
console.error("Error:", error);
}
});
}
// this function draws all the figures from document.entries - called when we
// change pages, but also when we change say grouping/other OPTs
function drawPageOfFigures()
{
$('#figures').empty()
var last = { printed: null }
var ecnt=0
if( OPT.folders )
{
if( document.entries.length && document.entries[0].in_dir.rel_path == '' )
{
gray="_gray"
back=""
cl=""
}
else
{
gray=""
back="Back"
cl="back"
}
// back button, if gray/back decide if we see grayed out folder and/or the name of the folder we go back to
html=`<div class="col col-auto g-0 m-1">
<figure id="${document.back_id}" ecnt="0" class="${cl} entry m-1" type="Directory">
<svg class="svg" width="${OPT.size-22}" height="${OPT.size-22}">
<use xlink:href="internal/icons.svg#folder_back${gray}"/>
</svg>
<figcaption class="figure-caption text-center">${back}</figcaption>
</figure>
</div>`
ecnt++
/*
<script>f=$('#_back'); w=f.find('svg').width(); f.find('figcaption').width(w);</script>
*/
$('#figures').append(html)
}
for (const obj of document.entries) {
addFigure( obj, last, ecnt )
ecnt++
}
$('.figure').click( function(e) { DoSel(e, this ); SetButtonState(); return false; });
$('.figure').dblclick( function(e) { dblClickToViewEntry( $(this).attr('id') ) } )
// for dir, getDirEntries 2nd param is back (or "up" a dir)
$(".dir").click( function(e) { document.back_id=this.id; getDirEntries(this.id,false) } )
$(".back").click( function(e) { getDirEntries(this.id,true) } )
}
// Function to get the 'page' of entry ids out of entryList
function getPage(pageNumber,viewing_idx=0)
{
// before we do anything, disabled left/right arrows on viewer to stop
// getting another event before we have the data for the page back
$('#la').prop('disabled', true)
$('#ra').prop('disabled', true)
const startIndex = (pageNumber - 1) * OPT.how_many;
const endIndex = startIndex + OPT.how_many;
pageList = entryList.slice(startIndex, endIndex);
// set up data to send to server to get the entry data for entries in pageList
data={}
data.ids = pageList
data.query = 99999
$.ajax({
type: 'POST',
url: '/get_entries_by_ids',
data: JSON.stringify(data), // Stringify the data
contentType: 'application/json', // Set content type
dataType: 'json', // Expect JSON response
success: function(res) {
document.entries=res
// add all the figures to files_div
drawPageOfFigures()
// noting we could have been in files_div, or viewer_div, update both jic
// and fix viewer_div - update viewing, arrows and image/video too
document.viewing=document.entries[viewing_idx]
resetNextPrevButtons()
ViewImageOrVideo()
},
error: function(xhr, status, error) {
console.error("Error:", error);
}
});
return
}
// Quick Function to check if we are on the first page
function isFirstPage(pageNumber)
{
return pageNumber <= 1;
}
// Function to check if we are on the last page
function isLastPage(pageNumber)
{
const totalPages = Math.ceil(entryList.length / OPT.how_many);
return pageNumber >= totalPages;
}
// given an id in the list, return which page we are on (page 1 is first page)
function getPageNumberForId(id) {
const idx = entryList.indexOf(id);
// should be impossible but jic
if (idx === -1) {
return -1; // or null, if you prefer
}
return Math.floor(idx / OPT.how_many) + 1;
}
// if we are on first page, disable prev, it not ensure next is enabled
// if we are on last page, disable next, it not ensure prev is enabled
function resetNextPrevButtons()
{
if ( isFirstPage( getPageNumberForId(pageList[0]) ) )
$('.prev').prop('disabled', true).addClass('disabled');
else
$('.prev').prop('disabled', false).removeClass('disabled');
if ( isLastPage( getPageNumberForId(pageList[0]) ) )
$('.next').prop('disabled', true).addClass('disabled');
else
$('.next').prop('disabled', false).removeClass('disabled');
}
// get list of eids for the next page, also make sure next/prev buttons make sense for page we are on
function nextPage()
{
// pageList[0] is the first entry on this page
const currentPage=getPageNumberForId( pageList[0] )
// should never happen / just return pageList unchanged
if ( currentPage === -1 || isLastPage( currentPage ) )
{
console.error( "WARNING: seems first on pg=" + firstEntryOnPage + " of how many=" + OPT.how_many + " gives currentPage=" + currentPage + " and we cant go next page?" )
return
}
getPage( currentPage+1 )
resetNextPrevButtons()
return
}
// get list of eids for the prev page, also make sure next/prev buttons make sense for page we are on
function prevPage()
{
// pageList[0] is the first entry on this page
const currentPage=getPageNumberForId( pageList[0] )
// should never happen / just return pageList unchanged
if (currentPage === 1 || currentPage === -1 )
{
console.error( "WARNING: seems first on pg=" + firstEntryOnPage + " of how many=" + OPT.how_many + " gives currentPage=" + currentPage + " and we cant go prev page?" )
return
}
getPage( currentPage-1 )
resetNextPrevButtons()
return
}
function isMobile() {
try{ document.createEvent("TouchEvent"); return true; }
catch(e){ return false; }
}