Getting the file extension of an image - macos

I'm modifying an AppleScript I found online for uploading images to Imgur. I'm having difficulty extracting the file extension though--despite what I've found online, nothing seems to work.
I'm trying to set a variable to the file extension (i.e. ".png", ".jpg", etc.) with the quotes around them.
on run {input, parameters}
tell application "Finder"
-- convert file paths to posix
set imagePath to POSIX path of (input as text)
-- debug display dialog imagePath as text with title "Path of File" buttons {"Okay"} default button "Okay"
--debug display dialog input as text with title "Input"
set ext to name extension of input
set apiKey to "26ff5c40cbedf50e7f81124ab473c1cc"
set curlCommand to "curl -F \"key=" & apiKey & "\" -F \"image=#" & imagePath & "\" http://api.imgur.com/2/upload"
set answer to do shell script curlCommand
set atid to AppleScript's text item delimiters
set AppleScript's text item delimiters to "<imgur_page>"
set link to text item 2 of answer
set AppleScript's text item delimiters to "<"
set link to text item 1 of link & (ext as text) --will be a direct link to the file, but the extension of the original file will matter
set AppleScript's text item delimiters to atid
set the clipboard to link
display notification "URL copied to clipboard" subtitle "Upload to Imgur complete"
end tell
end run

Instead of:
set ext to name extension of input
Try using:
set ext to (last text item of input)
This should define ext as the last text item after . in input

Related

Applescript, Automator - Find & Copy imgs in Dir/sub-dir

I am looking to make an automator workflow, or applescript (but I am not familiar with the language yet) that can use a list of names (spreadsheet or a .csv) to search a directory and its sub-directories for those specific file names (with varying extensions) and copy that image to a folder created for these images.
I've found a script that seems to be somewhat similar to what I need, but it doesn't search within sub-directories, so I've yet to actually find any images with it.
After extensive research, I've found 2 different scripts that seem to be what I need, but neither of them seem to search sub-directories. Below are the 2 scripts I've tried. If anyone could help me get these to search sub-directories, I would really appreciate it!
Script 1:
set thePhotos to paragraphs of (read (choose file with prompt "Choose a text file"))
set theSourceFolder to (choose folder with prompt "Choose source folder")
set theDestination to (choose folder with prompt "Choose destination folder")
set dupeList to {}
repeat with theName in thePhotos
try
set end of dupeList to alias ((theSourceFolder as text) & theName)
end try
end repeat
tell application "Finder" to duplicate dupeList to theDestination with replacing
set theCount1 to (count of dupeList) as text
set theCount2 to (count of thePhotos) as text
display dialog (theCount1 & " of " & theCount2 & " items copied to " & (theDestination as text)) buttons {"OK"}
Script 2
set fileContents to read (choose file with prompt "Choose a comma-delimited text file")
set theText to result
set AppleScript's text item delimiters to ","
set theTextItems to text items of theText
set AppleScript's text item delimiters to {""}
theTextItems
set theSourceFolder to (choose folder with prompt "Choose source folder") as string
set theDestination to (choose folder with prompt "Choose destination folder")
repeat with theEPSName in theTextItems
tell application "Finder"
set theEPSFile to theSourceFolder & theEPSName
move file theEPSFile to folder theDestination with replacing
end tell
end repeat
So it lets me choose the .csv to use, choose the directory to save and choose the directory to search. How can I get this script to search within sub-directories? And to someone who understands Applescript, does this look like it will function as needed?
Thank you in advance! I really appreciate any help on this, as it is my first Applescript experience, but I am excited to learn it!
This is a very fast solution using the shell and Spotlight searching.
The script creates a search criteria string
'kMDItemFSName == picture1.png || kMDItemFSName == picture2.jpg || ...'
then performs the search and copies all files by passing the found items to the cp command.
There might be a caveat if the name list is too long and exceeds the maximum length of shell parameters.
set theNames to paragraphs of (read (choose file with prompt "Choose a text file" of type "txt"))
set sourceFolder to quoted form of POSIX path of (choose folder with prompt "Choose source folder")
set destinationFolder to quoted form of POSIX path of (choose folder with prompt "Choose destination folder")
set nameList to {}
repeat with aName in theNames
set end of nameList to "kMDItemFSName == " & quoted form of aName
end repeat
set {TID, text item delimiters} to {text item delimiters, " || "}
set nameFilter to quoted form of (nameList as text)
set text item delimiters to TID
do shell script "mdfind -onlyin " & sourceFolder & " -0 " & nameFilter & " | xargs -0 -J {} cp {} " & destinationFolder

"Can't get last text item of alias" Error When Running AppleScript

I have an AppleScript that runs as part of a Hazel routine monitoring a folder. When the script runs, it picks apart the file targeted by the Hazel routine and then attaches the file to an email and addresses the email with information from the name of the file. Unfortunately, it seems there is an error somewhere in the script, but I cannot seem to locate it.
The only semi-useful information from Console is in the title (i.e., "Can't get last text item of alias"). Here is the script:
on hazelProcessFile(theFile)
set theAttachment1 to (POSIX path of theFile)
set FileName to theFile
--remove trailing slash
set SansSlash to quoted form of text 1 through -2 of FileName
set FileName to SansSlash as text
-- remove path from FileName
set AppleScript's text item delimiters to ":"
set SansPath to last text item of FileName
set FileName to SansPath as text
-- remove extension
set AppleScript's text item delimiters to "."
set SansExtension to every text item of FileName
set last text item of SansExtension to ""
set FileName to SansExtension as text
-- parse using —
set AppleScript's text item delimiters to "—"
set clientName to first text item of FileName
set clientEmail to last text item of FileName
tell application "Airmail 2"
activate
set theMessage to make new outgoing message with properties {subject:"New Invoice from ", content:"Please find attached, infra, the current month's invoice. If you have any questions, please feel free to respond to this email. One-time payments may be made using the following secure form on our website: https://. Thank you for your continued business."}
tell theMessage
set sender to "billing#example.com"
make new to recipient at end of to recipients with properties {name:clientName, address:clientEmail}
make new mail attachment with properties {filename:theAttachment1}
compose
end tell
end tell
end hazelProcessFile
The code is commented, so it should be obvious what each section is supposed to do. I would imagine the issue is in the "remove path from FileName" section, as that is the section that has been giving me the most trouble.
theFile is obviously an alias specifier.
text item and text thru – as the name implies – expects plain text
You have to coerce the alias first to text before dealing with text and remove quoted form of, that's only needed in conjunction with do shell script.
--remove trailing slash
set FileName to theFile as text
set SansSlash to text 1 through -2 of FileName
set FileName to SansSlash
but there is no trailing slash in a HFS path
To strip the file name without extension from an alias this is much easier
tell application "System Events" to set {name:Nm, name extension:Ex} to theFile
set baseName to text 1 thru ((get offset of "." & Ex in Nm) - 1) of Nm
Edit:
Try this optimized code, the Airmail 2 part is skipped and I don't know if the EM Dash character is treated correctly in case you'll copy and paste the code.
on hazelProcessFile(theFile)
set theAttachment1 to (POSIX path of theFile)
tell application "System Events" to set {name:Nm, name extension:Ex} to theFile
set FileName to text 1 thru ((get offset of "." & Ex in Nm) - 1) of Nm
-- parse using —
set {TID, text item delimiters} to {text item delimiters, "—"}
set clientName to text item -2 of FileName
set clientEmail to text item -1 of FileName
set text item delimiters to TID
-- tell application "Airmail 2"
-- ...
end hazelProcessFile

applescript get rid of full path

I've got a choose file in my AppleScript. When I run the script and choose a file, the output is always the full file path with the file extension on the end. For example:
Macintosh HD:Developer:About Xcode.pdf
is what I don't want. I only want:
About Xcode
The below answer by Kassym Dorsel doesn't work when there is more than one . in it.
The below answer by Lri doesn't work with set x to choose file:
error "Can’t make quoted form of alias \"Macintosh HD:Applications:Firefox.app:\" into type Unicode text." number -1700 from quoted form of alias "Macintosh HD:Applications:Firefox.app:" to Unicode text
You can use the Finder to manipulate the names of Finder items:
choose file with prompt "Pick one"
set filepath to result
tell application "Finder" to set {dispName, nameExt, isHidden} to ¬
the {displayed name, name extension, extension hidden} of the filepath
if isHidden or nameExt is equal to "" then
dispName
else
(characters 1 through (-2 - (count of nameExt)) of dispName) as text
end if
set baseName to result
This will work :
set a to "Macintosh HD:Developer:About.Xcode.pdf"
set text item delimiters to ":"
set temp to last text item of a
set text item delimiters to "."
set temp to text items 1 thru -2 of temp as text
Gives => About.Xcode

Applescript download files from Http server sporadic results

I wrote a script that downloads files from an Http server, but the results are very sporadic. If I run it three times in a row, it might work twice and error once or not work at all and return different errors.
Some of the errors I am getting are:
Error with downloading target URL (-609)
Url Access Scripting got an error: Connection is invalid.
Error with downloading target URL (-31040)
URL Access Scripting got an error: An error of type -31040 has occurred.
try
set theFileURL to "http://ftp2.nflfilmstv.com/filmsint/ftp-inet/Team/110915_game_preview_phi_atl_3200k.mp4" as text
set TID to AppleScript's text item delimiters
set AppleScript's text item delimiters to "/"
set theFile to text item -1 of theFileURL
set AppleScript's text item delimiters to TID
set theFilePath to "Macintosh HD:Users:rgilkes:Desktop:" & theFile as text
tell application "URL Access Scripting" to download theFileURL to file theFilePath with progress
on error ErrorMessage number ErrorNumber
display alert "Error with downloading target URL (" & ErrorNumber & ")" message ErrorMessage
end try
Is there a better way to download files via AppleScript or is my coding bad?
Ahhh, thanks for the preview! I'm originally a Philadelphian and still passionate about Philly sports. I hope I'm not helping a Falcons fan. At least not this week! ;)
Anyway your code looks fine although URLAccessScripting is not the most reliable way to download. Actually as of 10.7 it's no longer even is included with the OS. Curl is an alternative and usually stable. You won't get a progress window with it though. Try this. See if it's more stable. It will tell you when it's finished.
set theFileURL to "http://ftp2.nflfilmstv.com/filmsint/ftp-inet/Team/110915_game_preview_phi_atl_3200k.mp4"
set {TID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, "/"}
set theFile to text item -1 of theFileURL
set AppleScript's text item delimiters to TID
set theFilePath to (path to desktop as text) & theFile
try
do shell script "curl " & quoted form of theFileURL & " -o " & quoted form of POSIX path of theFilePath
display dialog "The download is finished!" buttons {"OK"} default button 1 with icon note giving up after 5
on error theError
display dialog "Error downloading the file:" & return & theFile & return & return & theError buttons {"OK"} default button 1 with icon 0 giving up after 5
end try

How find the file name of an executing AppleScript

How do I find the name of an executing AppleScript?
REASON: I want to create a script that changes its behavior based on its filename. Something like:
if myname is "Joe" then ACTION1
else if myname is "Frank" then ACTION2
else ACTION3
The normal way to get the name is by using "name of me". However applescripts are run by applescript runner so when you use that on a script you get "Applescript Runner" as the name. If you compile your script as an application then "name of me" will work. The only way to get the script name is by getting its path and extracting the name. Something like this would thus work for scripts...
getMyName()
tell me to display dialog result
on getMyName()
set myPath to path to me as text
if myPath ends with ":" then
set n to -2
else
set n to -1
end if
set AppleScript's text item delimiters to ":"
set myName to text item n of myPath
if (myName contains ".") then
set AppleScript's text item delimiters to "."
set myName to text 1 thru text item -2 of myName
end if
set AppleScript's text item delimiters to ""
return myName
end getMyName
Here's a method that works for all of the following:
*.scpt files (compiled AppleScript files; run in AppleScript Editor or with osascript)
*.applescript files (uncompiled AppleScript files; run in AppleScript Editor or with osascript)
command-line scripts that directly contain AppleScript (marked as executable and starting with #!/usr/bin/env osascript):
*.app files created with AppleScript Editor
*.app files created with Automator that contain AppleScript actions
Note: By contrast, it does not work for the following:
OS X services created with Automator that contain AppleScript actions (special *.workflow files) - always reports 'WorkflowServiceRunner[.xpc]'
general-purpose *.workflow files created with Automator that contain ApplesScript actions and that are run with automator - always reports 'Automator Runner[.app]'
Get the name of the running script, including filename extension (.scpt, .app, or .applescript, as the case may be):
tell application "System Events" to set myname to get name of (path to me)
If you want to remove the filename extension with a single command, use the following, do shell script-based approach:
tell application "System Events" to set myname to do shell script "rawName=" & quoted form of (get name of (path to me)) & "; printf '%s' \"${rawName%.*}\""
Here's an all-AppleScript alternative that is more verbose (yet concise by AppleScript standards):
tell application "System Events"
set myname to name of (path to me)
set extension to name extension of (path to me)
end tell
if length of extension > 0 then
# Make sure that `text item delimiters` has its default value here.
set myname to items 1 through -(2 + (length of extension)) of myname as text
end if
Finally, here's a variation: a subroutine that you can call with set myname to getMyName():
on getMyName()
local myName, tidSaved
tell application "System Events"
set myAlias to path to me -- alias to the file/bundle of the running script
set myName to name of myAlias -- filename with extension, if any.
if name extension of myAlias is not "" then -- strip away extension
set {tidSaved, AppleScript's text item delimiters} to {AppleScript's text item delimiters, {""}}
set myName to items 1 through -(2 + (length of (get name extension of myAlias))) of myName as text
set AppleScript's text item delimiters to tidSaved
end if
end tell
return myName
end getMyName
An easier way to find out the base part of the path is using name of:
tell application "Finder"
set p to path to me
set nam to name of file p as text
end tell
Maybe this:
set appname to name of current application

Resources