I had a need to have a random file selected within a folder to execute additional commands. Figured I would share the random selection part.
// Get the active tab
var tab = DOpus.listers.lastactive.activetab;
if (!tab) {
DOpus.Output("No active tab found.");
}
// Check if a folder is selected
var selectedItems = tab.selected;
var selectedFolder = null;
for (var e = 0; e < selectedItems.count; e++) {
var item = selectedItems(e);
if (item.is_dir) {
selectedFolder = item.realpath;
break;
}
}
// Use selected folder or default to current tab
var srcFolder = selectedFolder || tab.path;
DOpus.Output("Using folder: " + srcFolder);
// Read files in that folder
var fsu = DOpus.FSUtil();
var enumFiles = fsu.ReadDir(srcFolder);
var files = [];
while (!enumFiles.complete) {
var entry = enumFiles.Next();
if (!entry.is_dir) {
files.push(entry);
}
}
if (files.length === 0) {
DOpus.Output("No files found in folder.");
} else {
var randomIndex = Math.floor(Math.random() * files.length);
var selectedFile = files[randomIndex];
var cmd = DOpus.Create.Command();
cmd.SetSourceTab(tab);
// Deselect everything first
cmd.RunCommand('Select NONE');
// Select the random file
cmd.RunCommand('Select "' + selectedFile.name + '" EXACT');
}
You just need to select the folder you want the file from, run the JSscript, and it will unselect the folder, and randomly select a file within the folder.
After, run your additional commands, and then ?profit?