Script to Unzip Selected Item

One of the few features I miss in Devonthink is the ability to Unzip a folder directly without having to export the .zip, unzip it on the Desktop, and then re-import it.

This script automates that process.

Yes it was written by AI (Claude Opus). It appears to be reasonably well-written to me and works fine on my testing. YMMV.

tell application id "DNtp"
try
-- Get the selected record
set theRecords to selected records
if (count of theRecords) is 0 then
  display alert "No Selection" message "Please select a .zip file first."
  return
end if

set theRecord to item 1 of theRecords

-- Verify it's a zip file using filename (which always includes the extension)
set theFileName to filename of theRecord
if theFileName does not end with ".zip" then
  display alert "Not a Zip File" message "The selected record does not appear to be a .zip file." & return & return & "Filename: " & theFileName
  return
end if

-- Remember the parent group so we can import back to it
set theGroup to first parent of theRecord

-- Build the destination path in ~/Downloads
set downloadsPath to (POSIX path of (path to downloads folder))

-- Export the record to Downloads
set exportedPath to export record theRecord to downloadsPath

if exportedPath is missing value then
  display alert "Export Failed" message "Could not export the .zip file to Downloads."
  return
end if

-- Expand the zip via shell
set baseName to rich texts 1 thru -5 of theFileName
set expandedFolder to downloadsPath & baseName
do shell script "unzip -o " & quoted form of exportedPath & " -d " & quoted form of expandedFolder

-- Import the expanded folder back into the same group
set importedRecord to import path expandedFolder to theGroup
if importedRecord is not missing value then
  display notification "Imported \"" & baseName & "\" into \"" & (name of theGroup) & "\"." with title "Zip Expand Complete"
else
  display alert "Import Failed" message "The expanded folder could not be imported."
end if

on error errMsg number errNum
display alert "Error " & errNum message errMsg
end try
end tell
1 Like

I can’t see any obvious blunders. With the exception of the test for a valid zip file. I recently got send a file with the extension .pdf which was in fact a zipped PDF. To safeguard against such situations, I’d use the file utility: It looks at the content of the file and decides what format it might be then.

file something will display the string “Zip archive data” in its output, so the script could check for that.

1 Like