How do I URLencode only part of a concatenated string in AppleScript - applescript

Trying to create a service that will translate selected text using https://translate.google.com.
When I select a piece of text like "Please" it works perfectly and generates the URL:
https://translate.google.com/#view=home&op=translate&sl=auto&tl=da&text=Please
When I select a piece of text like "Please help me" it generates the URL:
https://translate.google.com/%23view=home&op=translate&sl=auto&tl=da&text=Please%20help%20me
and this doesn't work. The whole URL is getting URLEncoded i guess. The "#" (hashtag) at ".com/#view" is converted to "%23" and I think this is the problem.
How do I URLEncode only the variable "input"?
on run {input, parameters}
set thelist to {"Afrikaans", "Albansk", "Amharisk", "Arabisk", "Armensk", "Aserbajdsjansk", "Baskisk", "Bengali", "Bosnisk", "Bulgarsk", "Burmesisk", "Cebuano", "Chichewa", "Dansk", "Engelsk", "Esperanto", "Estisk", "Finsk", "Fransk", "Frisisk", "Galicisk", "Georgisk", "Græsk", "Gujarati", "Haitisk kreolsk", "Hausa", "Hawaiiansk", "Hebraisk", "Hindi", "Hmong", "Hollandsk", "Hviderussisk", "Igbo", "Indonesisk", "Irsk", "Islandsk", "Italiensk", "Japansk", "Javanesisk", "Jiddisch", "Kannada", "Kasakhisk", "Katalansk", "Khmer", "Kinesisk (forenklet)", "Kinesisk (traditionelt)", "Kinyarwanda", "Kirgisk", "Koreansk", "Korsikansk", "Kroatisk", "Kurdisk", "Laotisk", "Latin", "Lettisk", "Litauisk", "Luxembourgsk", "Makedonsk", "Malagassisk", "Malajisk", "Malayalam", "Maltesisk", "Maori", "Marathi", "Mongolsk", "Nepalesisk", "Norsk", "Odia (Oriya)", "Pashto", "Persisk", "Polsk", "Portugisisk", "Punjabi", "Rumænsk", "Russisk", "Samoansk", "Serbisk", "Sesotho", "Shona", "Sindhi", "Sinhala", "Skotsk gælisk", "Slovakisk", "Slovensk", "Somalisk", "Spansk", "Sundanesisk", "Svensk", "Swahili", "Tadsjikisk", "Tagalog", "Tamil", "Tatarisk", "Telugu", "Thailandsk", "Tjekkisk", "Turkmensk", "Tyrkisk", "Tysk", "Uighursk", "Ukrainsk", "Ungarsk", "Urdu", "Usbekisk", "Vietnamesisk", "Walisisk", "Xhosa", "Yoruba", "Zulu"}
set theItem to choose from list thelist with prompt "Hvad vil du oversætte til?" default items {"Dansk"}
if theItem = {"Afrikaans"} then
set language to "af"
else if theItem = {"Albansk"} then
set language to "sq"
else if theItem = {"Amharisk"} then
set language to "am"
else if theItem = {"Arabisk"} then
set language to "ar"
else if theItem = {"Armensk"} then
set language to "hy"
else if theItem = {"Aserbajdsjansk"} then
set language to "az"
else if theItem = {"Baskisk"} then
set language to "eu"
else if theItem = {"Bengali"} then
set language to "bn"
else if theItem = {"Bosnisk"} then
set language to "bs"
else if theItem = {"Bulgarsk"} then
set language to "bg"
else if theItem = {"Burmesisk"} then
set language to "my"
else if theItem = {"Cebuano"} then
set language to "ceb"
else if theItem = {"Chichewa"} then
set language to "ny"
else if theItem = {"Dansk"} then
set language to "da"
else if theItem = {"Engelsk"} then
set language to "en"
else if theItem = {"Esperanto"} then
set language to "eo"
else if theItem = {"Estisk"} then
set language to "et"
else if theItem = {"Finsk"} then
set language to "fi"
else if theItem = {"Fransk"} then
set language to "fr"
else if theItem = {"Frisisk"} then
set language to "fy"
else if theItem = {"Galicisk"} then
set language to "gl"
else if theItem = {"Georgisk"} then
set language to "ka"
else if theItem = {"Græsk"} then
set language to "el"
else if theItem = {"Haitisk kreolsk"} then
set language to "ht"
else if theItem = {"Hausa"} then
set language to "ha"
else if theItem = {"Hawaiiansk"} then
set language to "haw"
else if theItem = {"Hebraisk"} then
set language to "iw"
else if theItem = {"Hindi"} then
set language to "hi"
else if theItem = {"Hmong"} then
set language to "hmn"
else if theItem = {"Hollandsk"} then
set language to "nl"
else if theItem = {"Hviderussisk"} then
set language to "be"
else if theItem = {"Igbo"} then
set language to "ig"
else if theItem = {"Indonesisk"} then
set language to "id"
else if theItem = {"Irsk"} then
set language to "ga"
else if theItem = {"Islandsk"} then
set language to "is"
else if theItem = {"Italiensk"} then
set language to "it"
else if theItem = {"Japansk"} then
set language to "ja"
else if theItem = {"Javanesisk"} then
set language to "jw"
else if theItem = {"Jiddisch"} then
set language to "yi"
else if theItem = {"Kannada"} then
set language to "kn"
else if theItem = {"Kasakhisk"} then
set language to "kk"
else if theItem = {"Katalansk"} then
set language to "ca"
else if theItem = {"Khmer"} then
set language to "km"
else if theItem = {"Kinesisk (forenklet)"} then
set language to "zh-CN"
else if theItem = {"Kinesisk (traditionelt)"} then
set language to "zh-TW"
else if theItem = {"Kinyarwanda"} then
set language to "rw"
else if theItem = {"Kirgisk"} then
set language to "ky"
else if theItem = {"Koreansk"} then
set language to "ko"
else if theItem = {"Korsikansk"} then
set language to "co"
else if theItem = {"Kroatisk"} then
set language to "hr"
else if theItem = {"Kurdisk"} then
set language to "ku"
else if theItem = {"Laotisk"} then
set language to "lo"
else if theItem = {"Latin"} then
set language to "la"
else if theItem = {"Lettisk"} then
set language to "lv"
else if theItem = {"Litauisk"} then
set language to "lt"
else if theItem = {"Luxembourgsk"} then
set language to "lb"
else if theItem = {"Malagassisk"} then
set language to "mg"
else if theItem = {"Malayalam"} then
set language to "ml"
else if theItem = {"Maltesisk"} then
set language to "mt"
else if theItem = {"Maori"} then
set language to "mi"
else if theItem = {"Marathi"} then
set language to "mr"
else if theItem = {"Mongolsk"} then
set language to "mn"
else if theItem = {"Nepalesisk"} then
set language to "ne"
else if theItem = {"Norsk"} then
set language to "no"
else if theItem = {"Odia (Oriya)"} then
set language to "or"
else if theItem = {"Pashto"} then
set language to "ps"
else if theItem = {"Persisk"} then
set language to "fa"
else if theItem = {"Polsk"} then
set language to "pl"
else if theItem = {"Portugisisk"} then
set language to "pt"
else if theItem = {"Punjabi"} then
set language to "pa"
else if theItem = {"Rumænsk"} then
set language to "ro"
else if theItem = {"Russisk"} then
set language to "ru"
else if theItem = {"Samoansk"} then
set language to "sm"
else if theItem = {"Serbisk"} then
set language to "sr"
else if theItem = {"Sesotho"} then
set language to "st"
else if theItem = {"Shona"} then
set language to "sn"
else if theItem = {"Sindhi"} then
set language to "sd"
else if theItem = {"Sinhala"} then
set language to "si"
else if theItem = {"Skotsk gælisk"} then
set language to "gd"
else if theItem = {"Slovakisk"} then
set language to "sk"
else if theItem = {"Slovensk"} then
set language to "sl"
else if theItem = {"Somalisk"} then
set language to "so"
else if theItem = {"Spansk"} then
set language to "es"
else if theItem = {"Sundanesisk"} then
set language to "su"
else if theItem = {"Svensk"} then
set language to "sv"
else if theItem = {"Swahili"} then
set language to "sw"
else if theItem = {"Tadsjikisk"} then
set language to "tg"
else if theItem = {"Tagalog"} then
set language to "tl"
else if theItem = {"Tamil"} then
set language to "ta"
else if theItem = {"Tatarisk"} then
set language to "tt"
else if theItem = {"Telugu"} then
set language to "te"
else if theItem = {"Thailandsk"} then
set language to "th"
else if theItem = {"Tjekkisk"} then
set language to "cs"
else if theItem = {"Turkmensk"} then
set language to "tk"
else if theItem = {"Tyrkisk"} then
set language to "tr"
else if theItem = {"Tysk"} then
set language to "de"
else if theItem = {"Uighursk"} then
set language to "ug"
else if theItem = {"Ukrainsk"} then
set language to "uk"
else if theItem = {"Ungarsk"} then
set language to "hu"
else if theItem = {"Urdu"} then
set language to "ur"
else if theItem = {"Usbekisk"} then
set language to "uz"
else if theItem = {"Vietnamesisk"} then
set language to "vi"
else if theItem = {"Walisisk"} then
set language to "cy"
else if theItem = {"Xhosa"} then
set language to "xh"
else if theItem = {"Yoruba"} then
set language to "yo"
else if theItem = {"Zulu"} then
set language to "zu"
end if
open location "https://translate.google.com/#view=home&op=translate&sl=auto&tl=" & language & "&text=" & input
end run

This is not a direct answer to your question. However, I have a completely different approach that you may actually prefer. Basically this approach will take the text that you have a copied to your clipboard and translate it for you… to the language you have chosen. It will then show you your translated text in a dialog pop up and will also copy the translation to your clipboard.
This following animation demonstrates the process. I will trigger the translation script with a keyboard shortcut that I created in the Services Preferences.
Getting Started:
Homebrew needs to be installed on your system. If it is not
installed, you can find step by step instructions for its
installation… here —> Install Homebrew
After successful installation of Homebrew, you will need to install
the translate-shell formula. Paste this in a macOS Terminal or
Linux shell prompt. brew install translate-shell
After successful installation of the Homebrew translate-shell
formula, the trans command has tons of options. Paste this in a
macOS Terminal shell prompt man trans to learn about its features.
Now you can incorporate your "Translation" code into an Automator
Quick Action then assign it a keyboard shortcut in your Services
Preferences. You can read exactly how to use the trans shell
script command with AppleScript here ---> Run Translate Shell from
an AppleScript
Here is the code I used in Script Editor and Automator
copy (the clipboard) to theText
delay 0.1
set detectedLanguage to (do shell script "export PATH=\"/usr/local/bin:$PATH\";/usr/local/bin/trans -identify -no-ansi " & quoted form of theText & " | " & "grep Name " & "| " & "cut -c 23-")
set theList to {"Afrikaans", "Albansk", "Amharisk", "Arabisk", "Armensk", "Aserbajdsjansk", "Baskisk", "Bengali", "Bosnisk", "Bulgarsk", "Burmesisk", "Cebuano", "Chichewa", "Dansk", "Engelsk", "Esperanto", "Estisk", "Finsk", "Fransk", "Frisisk", "Galicisk", "Georgisk", "Græsk", "Gujarati", "Haitisk kreolsk", "Hausa", "Hawaiiansk", "Hebraisk", "Hindi", "Hmong", "Hollandsk", "Hviderussisk", "Igbo", "Indonesisk", "Irsk", "Islandsk", "Italiensk", "Japansk", "Javanesisk", "Jiddisch", "Kannada", "Kasakhisk", "Katalansk", "Khmer", "Kinesisk (forenklet)", "Kinesisk (traditionelt)", "Kinyarwanda", "Kirgisk", "Koreansk", "Korsikansk", "Kroatisk", "Kurdisk", "Laotisk", "Latin", "Lettisk", "Litauisk", "Luxembourgsk", "Makedonsk", "Malagassisk", "Malajisk", "Malayalam", "Maltesisk", "Maori", "Marathi", "Mongolsk", "Nepalesisk", "Norsk", "Odia (Oriya)", "Pashto", "Persisk", "Polsk", "Portugisisk", "Punjabi", "Rumænsk", "Russisk", "Samoansk", "Serbisk", "Sesotho", "Shona", "Sindhi", "Sinhala", "Skotsk gælisk", "Slovakisk", "Slovensk", "Somalisk", "Spansk", "Sundanesisk", "Svensk", "Swahili", "Tadsjikisk", "Tagalog", "Tamil", "Tatarisk", "Telugu", "Thailandsk", "Tjekkisk", "Turkmensk", "Tyrkisk", "Tysk", "Uighursk", "Ukrainsk", "Ungarsk", "Urdu", "Usbekisk", "Vietnamesisk", "Walisisk", "Xhosa", "Yoruba", "Zulu"}
activate
set theItem to choose from list theList with prompt "What Language Do You Want To Translate To?" default items {"Engelsk"}
if theItem = {"Afrikaans"} then
set theLanguage to "af"
else if theItem = {"Albansk"} then
set theLanguage to "sq"
else if theItem = {"Amharisk"} then
set theLanguage to "am"
else if theItem = {"Arabisk"} then
set theLanguage to "ar"
else if theItem = {"Armensk"} then
set theLanguage to "hy"
else if theItem = {"Aserbajdsjansk"} then
set theLanguage to "az"
else if theItem = {"Baskisk"} then
set theLanguage to "eu"
else if theItem = {"Bengali"} then
set theLanguage to "bn"
else if theItem = {"Bosnisk"} then
set theLanguage to "bs"
else if theItem = {"Bulgarsk"} then
set theLanguage to "bg"
else if theItem = {"Burmesisk"} then
set theLanguage to "my"
else if theItem = {"Cebuano"} then
set theLanguage to "ceb"
else if theItem = {"Chichewa"} then
set theLanguage to "ny"
else if theItem = {"Dansk"} then
set theLanguage to "da"
else if theItem = {"Engelsk"} then
set theLanguage to "en"
else if theItem = {"Esperanto"} then
set theLanguage to "eo"
else if theItem = {"Estisk"} then
set theLanguage to "et"
else if theItem = {"Finsk"} then
set theLanguage to "fi"
else if theItem = {"Fransk"} then
set theLanguage to "fr"
else if theItem = {"Frisisk"} then
set theLanguage to "fy"
else if theItem = {"Galicisk"} then
set theLanguage to "gl"
else if theItem = {"Georgisk"} then
set theLanguage to "ka"
else if theItem = {"Græsk"} then
set theLanguage to "el"
else if theItem = {"Haitisk kreolsk"} then
set theLanguage to "ht"
else if theItem = {"Hausa"} then
set theLanguage to "ha"
else if theItem = {"Hawaiiansk"} then
set theLanguage to "haw"
else if theItem = {"Hebraisk"} then
set theLanguage to "iw"
else if theItem = {"Hindi"} then
set theLanguage to "hi"
else if theItem = {"Hmong"} then
set theLanguage to "hmn"
else if theItem = {"Hollandsk"} then
set theLanguage to "nl"
else if theItem = {"Hviderussisk"} then
set theLanguage to "be"
else if theItem = {"Igbo"} then
set theLanguage to "ig"
else if theItem = {"Indonesisk"} then
set theLanguage to "id"
else if theItem = {"Irsk"} then
set theLanguage to "ga"
else if theItem = {"Islandsk"} then
set theLanguage to "is"
else if theItem = {"Italiensk"} then
set theLanguage to "it"
else if theItem = {"Japansk"} then
set theLanguage to "ja"
else if theItem = {"Javanesisk"} then
set theLanguage to "jw"
else if theItem = {"Jiddisch"} then
set theLanguage to "yi"
else if theItem = {"Kannada"} then
set theLanguage to "kn"
else if theItem = {"Kasakhisk"} then
set theLanguage to "kk"
else if theItem = {"Katalansk"} then
set theLanguage to "ca"
else if theItem = {"Khmer"} then
set theLanguage to "km"
else if theItem = {"Kinesisk (forenklet)"} then
set theLanguage to "zh-CN"
else if theItem = {"Kinesisk (traditionelt)"} then
set theLanguage to "zh-TW"
else if theItem = {"Kinyarwanda"} then
set theLanguage to "rw"
else if theItem = {"Kirgisk"} then
set theLanguage to "ky"
else if theItem = {"Koreansk"} then
set theLanguage to "ko"
else if theItem = {"Korsikansk"} then
set theLanguage to "co"
else if theItem = {"Kroatisk"} then
set theLanguage to "hr"
else if theItem = {"Kurdisk"} then
set theLanguage to "ku"
else if theItem = {"Laotisk"} then
set theLanguage to "lo"
else if theItem = {"Latin"} then
set theLanguage to "la"
else if theItem = {"Lettisk"} then
set theLanguage to "lv"
else if theItem = {"Litauisk"} then
set theLanguage to "lt"
else if theItem = {"Luxembourgsk"} then
set theLanguage to "lb"
else if theItem = {"Malagassisk"} then
set theLanguage to "mg"
else if theItem = {"Malayalam"} then
set theLanguage to "ml"
else if theItem = {"Maltesisk"} then
set theLanguage to "mt"
else if theItem = {"Maori"} then
set theLanguage to "mi"
else if theItem = {"Marathi"} then
set theLanguage to "mr"
else if theItem = {"Mongolsk"} then
set theLanguage to "mn"
else if theItem = {"Nepalesisk"} then
set theLanguage to "ne"
else if theItem = {"Norsk"} then
set theLanguage to "no"
else if theItem = {"Odia (Oriya)"} then
set theLanguage to "or"
else if theItem = {"Pashto"} then
set theLanguage to "ps"
else if theItem = {"Persisk"} then
set theLanguage to "fa"
else if theItem = {"Polsk"} then
set theLanguage to "pl"
else if theItem = {"Portugisisk"} then
set theLanguage to "pt"
else if theItem = {"Punjabi"} then
set theLanguage to "pa"
else if theItem = {"Rumænsk"} then
set theLanguage to "ro"
else if theItem = {"Russisk"} then
set theLanguage to "ru"
else if theItem = {"Samoansk"} then
set theLanguage to "sm"
else if theItem = {"Serbisk"} then
set theLanguage to "sr"
else if theItem = {"Sesotho"} then
set theLanguage to "st"
else if theItem = {"Shona"} then
set theLanguage to "sn"
else if theItem = {"Sindhi"} then
set theLanguage to "sd"
else if theItem = {"Sinhala"} then
set theLanguage to "si"
else if theItem = {"Skotsk gælisk"} then
set theLanguage to "gd"
else if theItem = {"Slovakisk"} then
set theLanguage to "sk"
else if theItem = {"Slovensk"} then
set theLanguage to "sl"
else if theItem = {"Somalisk"} then
set theLanguage to "so"
else if theItem = {"Spansk"} then
set theLanguage to "es"
else if theItem = {"Sundanesisk"} then
set theLanguage to "su"
else if theItem = {"Svensk"} then
set theLanguage to "sv"
else if theItem = {"Swahili"} then
set theLanguage to "sw"
else if theItem = {"Tadsjikisk"} then
set theLanguage to "tg"
else if theItem = {"Tagalog"} then
set theLanguage to "tl"
else if theItem = {"Tamil"} then
set theLanguage to "ta"
else if theItem = {"Tatarisk"} then
set theLanguage to "tt"
else if theItem = {"Telugu"} then
set theLanguage to "te"
else if theItem = {"Thailandsk"} then
set theLanguage to "th"
else if theItem = {"Tjekkisk"} then
set theLanguage to "cs"
else if theItem = {"Turkmensk"} then
set theLanguage to "tk"
else if theItem = {"Tyrkisk"} then
set theLanguage to "tr"
else if theItem = {"Tysk"} then
set theLanguage to "de"
else if theItem = {"Uighursk"} then
set theLanguage to "ug"
else if theItem = {"Ukrainsk"} then
set theLanguage to "uk"
else if theItem = {"Ungarsk"} then
set theLanguage to "hu"
else if theItem = {"Urdu"} then
set theLanguage to "ur"
else if theItem = {"Usbekisk"} then
set theLanguage to "uz"
else if theItem = {"Vietnamesisk"} then
set theLanguage to "vi"
else if theItem = {"Walisisk"} then
set theLanguage to "cy"
else if theItem = {"Xhosa"} then
set theLanguage to "xh"
else if theItem = {"Yoruba"} then
set theLanguage to "yo"
else if theItem = {"Zulu"} then
set theLanguage to "zu"
end if
set theTranslation to (do shell script "export PATH=\"/usr/local/bin:$PATH\";/usr/local/bin/trans -b :" & theLanguage & " " & quoted form of theText)
set the clipboard to theTranslation
activate
display dialog "The Translation Has Been Copied To The Clipboard For Your Convenience" & linefeed & linefeed & theTranslation with title "Your Translation Results From " & detectedLanguage & " To " & theItem buttons {"OK"}

Related

iterate through string to get match object from the List in AppleScript

I have tried this below code, It should display "Match". But Somehow it isn't.
set mylist to {"wade", "lee"}
set username to "sarawade"
set a to (count username)
repeat a times
set mystring to do shell script "echo " & username & " | sed 's/[a-z]//'"
set username to mystring
display dialog username
repeat with theitem in mylist
if username = theitem then
display dialog "Match"
end if
end repeat
end repeat
You compare username with theitem, which is a reference to list's element. You should compare to contents of theitem instead:
set mylist to {"wade", "lee"}
set username to "sarawade"
set a to (count username)
repeat a times
set mystring to do shell script "echo " & username & " | sed 's/[a-z]//'"
set username to mystring
display dialog username
repeat with theitem in mylist
if username = contents of theitem then -- EDITED
display dialog "Match"
end if
end repeat
end repeat
NOTE: you can do it easy:
set mylist to {"wade", "lee"}
set username to "sarawade"
display dialog username with title "The username"
set matchFound to false
repeat with theitem in mylist
if username ends with (contents of theitem) then
set matchFound to true
exit repeat
end if
end repeat
if matchFound then
return contents of theitem
else
return "No match found"
end if

Export Apple photos library for importing it elsewhere

I intented to export all my photos from Mac to any other environment and this suggestion finally provided the base to solve this with applescript. That way the photos are always scaled (getting bigger than the original) but at least it works.
I know it's long but as I struggled that long with this problem, so I post the whole working solution below as an answer. Maybe someone has a better suggestion. I have refused to reverse engineer the contents in sqlite tables Photos is using, as this just may change with the next version.
Problems are various
There is no guarantee how Photos walks through the albums and folders. And as it sometimes just stops working, you have to guarantee some order, or you will never finish. So I introduced a way to start at a particular album at a particular photo. The order within the album seems to be stable. The log output written shows the unique ids of album and photo (as names may not be unique) to be able to restart it at this point. Most of the time the second attempt just works.
I did not find a way to store photos in order, so I created one single directory for each photo and stored each photo in a separate directory, so I can reimport them in order. Problem is that Photos always uses the original file name and just counts upwards if the name exists already. Using different cameras just makes it worse.
All attributes I wrote into a text file per photo, so I can reimport them later.
Error handling is quite tricky. The photos library sometimes just requests the user to press a button, which makes it hard to script it.
That's unfortunately the best I was able to come up with, it is my 1st applescript. This worked on an old Mac with Sierra and it works on more recent versions with Catalina as well. I'm almost sure the newest version will not complain. I'm still searching for a better solution.
There is little support to run it from inside Apple's script editor, only command line provides all options.
#!/usr/bin/osascript
global startAlbum, startPhoto, match, dummy, match, photoCnt, infoFd
global errorIndicator
on writePhotoAndData(thePath, mediaItem, mediaAlbum)
set ind to "X"
using terms from application "Photos"
set fName to filename of mediaItem
set fId to id of mediaItem
set photoCnt to photoCnt + 1
-- export each media to separate directory -> only chance to keep the order
if dummy then
if infoFd ≠ missing value then
set s to id of mediaAlbum & tab & id of mediaItem & tab & thePath & linefeed as text
write s to infoFd as «class utf8»
end if
else
makeEmptyPosixPath(thePath)
set exportPath to POSIX file thePath
set infoFile to POSIX file (thePath & "/" & "info.txt")
set infoText to "id" & tab & id of mediaItem & linefeed & "file" & tab & filename of mediaItem & linefeed & "album" & tab & name of mediaAlbum & linefeed
if exists name of mediaItem then set infoText to infoText & "name" & tab & name of mediaItem & linefeed
if exists description of mediaItem then set infoText to infoText & "desc" & tab & description of mediaItem & linefeed
if exists date of mediaItem then
set d to date of mediaItem
set infoText to infoText & "date" & tab & short date string of d & space & time string of d & linefeed
end if
if exists altitude of mediaItem then set infoText to infoText & "alt" & tab & altitude of mediaItem & linefeed
if exists location of mediaItem then set infoText to infoText & "location" & tab & location of mediaItem & linefeed
if exists keywords of mediaItem then
tell mediaItem to set myKeywords to keywords
repeat with keyword in myKeywords
set infoText to infoText & "keyword" & tab & keyword & linefeed
end repeat
end if
set fd to open for access infoFile with write permission
set eof fd to 0 -- of fd?
write infoText to fd starting at eof as «class utf8»
close access fd
try
tell mediaAlbum
--Not sure whether this does anything, so removed
--set settings to "JPEG - Original Size"
export {mediaItem} to (exportPath as alias)
end tell
set errorIndicator to 0
on error errStr number errNum
if errNum = -1712 then --timeout
set ind to "E"
set errorIndicator to errorIndicator + 1
if errorIndicator >= 3 then
error "3 errors in a row - exiting"
end if
else
error errStr number errNum
end if
end try
end if
log ind & tab & photoCnt & tab & id of mediaAlbum & tab & id of mediaItem & tab & name of mediaAlbum & tab & filename of mediaItem
end using terms from
end writePhotoAndData
on walkAlbum(theAlbum, thePath)
if match = 0 then
if id of theAlbum = startAlbum then
set match to 1
if startPhoto is missing value then
set match to 2
end if
else
return
end if
else if match = 1 then
if id of theAlbum is not equal to startAlbum then
set match to 3
end if
end if
set photoNum to 0
using terms from application "Photos"
set albumPath to thePath & name of theAlbum & "/"
repeat with mediaItem in media items of theAlbum
set photoNum to photoNum + 1
if match = 1 then
if id of mediaItem = startPhoto then
set match to 2
end if
else if match = 2 then
set match to 3 --photo after the photo chosen
end if
if match = 3 then
writePhotoAndData(albumPath & photoNum, mediaItem, theAlbum)
end if
end repeat
end using terms from
end walkAlbum
on walkFolder(theFolder, thePath)
using terms from application "Photos"
repeat with containedFolder in folders of theFolder
walkFolder(containedFolder, thePath & name of containedFolder & "/")
end repeat
repeat with containedAlbum in albums of theFolder
walkAlbum(containedAlbum, thePath)
end repeat
end using terms from
end walkFolder
on makePosixPath(tPath)
do shell script "mkdir -p " & quoted form of tPath
end makePosixPath
on makeEmptyPosixPath(tPath)
do shell script "rm -rf " & quoted form of tPath & " && mkdir -p " & quoted form of tPath
end makeEmptyPosixPath
on makeFolder(tPath)
do shell script "mkdir -p " & quoted form of POSIX path of tPath
end makeFolder
on walkFile(fileName, fileOffset as integer)
set thisOffset to 0
set saveDelim to text item delimiters of AppleScript
set walkFd to open for access POSIX file fileName
set rawLine to read walkFd before linefeed as «class utf8»
repeat
set thisOffset to thisOffset + 1
if fileOffset = 0 or thisOffset ≥ fileOffset then
set thisLine to rawLine as text
set text item delimiters of AppleScript to tab
set splitLine to text items of thisLine
set text item delimiters of AppleScript to saveDelim
set albumIdString to item 1 of splitLine
set photoIdString to item 2 of splitLine
set pathString to item 3 of splitLine
tell application "Photos"
set thisAlbum to album id albumIdString
set thisMedia to media item id photoIdString
end tell
writePhotoAndData(pathString, thisMedia, thisAlbum)
log "O" & tab & thisOffset
end if
try
set rawLine to read walkFd before linefeed as «class utf8»
on error errTxt number errNum
if errNum = -39 then --end of file
exit repeat
else
error "Error reading inputfile: " & errTxt
end if
end try
end repeat
end walkFile
on run (args)
set caller to class of args as string
set errorIndicator to 0
set destPath to POSIX path of (get path to home folder) & "export/photos/"
set photoCnt to 0
set startAlbum to missing value
set startPhoto to missing value
set match to 3
set dummy to false
set walkFileName to missing value
set walkFileOffset to 0
set infoFd to missing value
set infoFileName to missing value
set chooseDestinationFolder to "Select start folder (defaults to " & destPath & ")"
set chooseStart to "Give start album and photo"
set chooseDryRun to "dry-run"
if caller = "script" then
log "Running in ScriptEditor:" & name of me
set options to choose from list {chooseDestinationFolder, chooseStart, chooseDryRun} with title "Configure run" with prompt "Select options" with multiple selections allowed and empty selection allowed
if options contains chooseDryRun then set dummy to true
if options contains chooseDestinationFolder then
try
set destFolder to choose folder with prompt "Choose export directory or cancel for default location" default location (get path to home folder as alias)
set destPath to POSIX path of destFolder
end try
end if
if options contains chooseStart then
set res to display dialog "Enter Id of album to start" default answer "" buttons {"OK"} default button 1
if length of text returned of res > 0 then
set startAlbum to text returned of res
set match to 0
end if
if match = 0 then
set res to display dialog "Enter id of photo to resume after (leave empty to start with album)" default answer "" buttons {"OK"} default button 1
if length of text returned of res > 0 then
set startPhoto to text returned of res
end if
end if
end if
else if caller = "list" then
log "Running on the command line:" & name of me
set cnt to 1
repeat while cnt ≤ length of args
if item cnt of args = "-t" then
set cnt to (cnt + 1)
set destPath to item cnt of args
set cnt to (cnt + 1)
else if item cnt of args = "-a" then
set match to 0
set cnt to (cnt + 1)
set startAlbum to item cnt of args
else if item cnt of args = "-p" then
set cnt to (cnt + 1)
set startPhoto to item cnt of args
else if item cnt of args = "-h" then
return name of me & " [-t target path] [-a start album id] [-a start photo id] [-d] [-i info file path]" & linefeed ¬
& name of me & "[-t target path] -f info file [-o offset]" & linefeed ¬
& name of me & " -h .. this help"
else if item cnt of args = "-d" then
set dummy to true
else if item cnt of args = "-i" then
set cnt to (cnt + 1)
set infoFileName to item cnt of args
else if item cnt of args = "-f" then
set cnt to (cnt + 1)
set walkFileName to item cnt of args
else if item cnt of args = "-o" then
set cnt to cnt + 1
set walkFileOffset to item cnt of args
else
error "Invalid option:" & item cnt of args & " - use -h for help"
end if
set cnt to (cnt + 1)
end repeat
end if
set mySettings to "Destination directory:" & destPath
if startAlbum is not missing value then set mySettings to mySettings & linefeed & tab & "Start album id:" & tab & startAlbum
if startPhoto is not missing value then set mySettings to mySettings & linefeed & tab & "Start photo id:" & tab & startPhoto
if infoFileName ≠ missing value then
set mySettings to mySettings & linefeed & tab & "Write file '" & infoFileName & "'" & linefeed
set dummy to true
end if
if dummy then set mySettings to mySettings & linefeed & tab & "Dry run only"
if caller = "script" then
display dialog mySettings with title "Start exporting?" with icon note
else if caller = "list" then
log mySettings
else
error "Internal error - caller interface unknown"
end if
if infoFileName ≠ missing value then
set infoFd to open for access POSIX file infoFileName with write permission
set eof infoFd to 1
end if
if walkFileName ≠ missing value then
walkFile(walkFileName, walkFileOffset)
else
walkFolder(application "Photos", destPath)
end if
if infoFd ≠ missing value then close access infoFd
return "Done!"
end run

Selecting multiple files in Finder

In my applescript, I have a function which takes a selected file and writes its path into an xml file. If a folder is selected, i'm able to create a list with the files contained and send that to my function. However, if I select multiple finder items (via shift clicking), whether files or folders, I'm not able to send anything to the function.
here is the part where i get the files from the Finder
tell application "Finder"
set myPath to the selection
end tell
--if multiple files selected
if (count of myPath) is greater than 1 then
set fileList to every item of myPath
repeat with i in fileList
if (isDirectory(i)) then
else
myBigLoop(initialSuccess, i, watchFolder)
end if
end repeat
else if (isDirectory(myPath)) then
submitFolder(myPath, watchFolder)
else
set isFolder to false
set initialSuccess to true
myBigLoop(initialSuccess, myPath, watchFolder)
end if
on myBigLoop(initialSuccess, fileList, watchFolder)
repeat with myPath in fileList
if initialSuccess then
tell application "Finder"
set myFilename to myPath as alias
set myPath to the folder of myFilename
set myPath to myPath as string
set myFilename to name of myFilename
display dialog myFilename
end tell
end if --end InitialSuccess
end repeat
end myBigLoop
on isDirectory(someItem) -- someItem is a file reference
set filePosixPath to quoted form of (POSIX path of (someItem as alias))
set fileType to (do shell script "file -b " & filePosixPath)
if fileType ends with "directory" then return true
return false
end isDirectory
on submitFolder(myPath, watchFolder)
set isFolder to true
set initialSuccess to true
set fileList to item 1 of myPath
set fileList to get every file of fileList
set numFiles to count fileList
if numFiles is equal to 0 then
display dialog "There were no files in that folder."
return false
end if
myBigLoop(initialSuccess, fileList, watchFolder)
end submitFolder
I believe you should extend the Finder tell structure, because you're still working with files and folders later on:
tell application "Finder"
set myPath to the selection
--if multiple files selected
if (count of myPath) is greater than 1 then
set fileList to every item of myPath
repeat with i in fileList
if (isDirectory(i)) then
else
myBigLoop(initialSuccess, i, watchFolder)
end if
end repeat
else if (isDirectory(myPath)) then
submitFolder(myPath, watchFolder)
else
set isFolder to false
set initialSuccess to true
myBigLoop(initialSuccess, myPath, watchFolder)
end if
end tell

Applescript: Passing track metadata from text file to broadcast streaming app

I know virtually nothing about AppleScript and could do with some help.
While running, my broadcast playout system (MegaSeg) writes details of the track currently playing to a textfile called "NowPlaying" which contains solely the following contents, each on its own line and without square brackets:
Title: [title]
Artist: [artist]
Album: [album]
Time: [time in some format or other]
I want to pass this to my broadcast streamer LadioCast, which can be addressed via AppleScript, so that it sends info on what is playing to the streaming server.
MegaSeg doesn't support Applescript calls like 'tell application "MegaSeg"... set trackName to name of current track' so I can't do it that way. I have no idea about how to do this.
If we imagine that I was able to grab that info, this is what I would do with it:
set lastName to ""
set lastArtist to ""
set lastAlbum to ""
repeat
** insert missing file reading section here
** in the following, "title", "artist" and "album" are from the text file **
set trackName to title
set trackArtist to artist
set trackAlbum to album
** end of missing section
if trackName is not lastName and trackArtist is not lastArtist and trackAlbum is not lastAlbum then
set lastName to trackName
set lastArtist to trackArtist
set lastAlbum to trackAlbum
tell application "LadioCast"
set metadata song to trackName & " – " & trackArtist & " – " & trackAlbum
end tell
end if
delay 15
end repeat
Thanks in advance.
--Richard E
===
I tried the suggestions from #DigiMonk and they were very helpful, but not all of them worked. First, the file is in a specific location and not on the desktop; second, I could not get 'trim_line' to work at all - I got "script does not understand trim_line message". However the text in the file seems to be already trimmed.
The script below nearly works; when run from the Applescript Editor it does seem to get the Title, Artist and Album into the variables. However when I try running it from LadioCast I get an EOF -39 error. More importantly, as soon as I run this, MegaSeg stops updating the file, forever. I am presumably locking the file to read from it and stopping MegaSeg writing to it. How do I avoid this?
set lastName to ""
set lastArtist to ""
set lastAlbum to ""
set lastTime to ""
set trackName to ""
set trackArtist to ""
set trackAlbum to ""
set sourcePath to ""
repeat
set sourcePath to open for access file "Library:MegaSeg User Data:Logs:Logs for MegaSeg System (4):NowPlaying"
set thisText to read sourcePath as text
close access file "Library:MegaSeg User Data:Logs:Logs for MegaSeg System (4):NowPlaying"
set the paragraphList to every paragraph of thisText
repeat with i from 1 to number of items in paragraphList
set thisItem to item i of paragraphList
if thisItem starts with "Title:" then
set x to the offset of "Title:" in thisItem
set trackName to (text (x + 6) thru -1 of thisItem)
else if thisItem starts with "Artist:" then
set x to the offset of "Artist:" in thisItem
set trackArtist to (text (x + 7) thru -1 of thisItem)
else if thisItem starts with "Album:" then
set x to the offset of "Album:" in thisItem
set trackAlbum to (text (x + 6) thru -1 of thisItem)
end if
end repeat
if trackName is not lastName and trackArtist is not lastArtist and trackAlbum is not lastAlbum then
set lastName to trackName
set lastArtist to trackArtist
set lastAlbum to trackAlbum
tell application "LadioCast"
set metadata song to trackName & " – " & trackArtist & " – " & trackAlbum
end tell
end if
delay 15
end repeat
May be this helps: (feed sourcePath with the path to your NowPlaying.txt file)
set sourcePath to (path to desktop) & "NowPlaying.txt" as text
set thisText to my readFile(sourcePath)
set the paragraphList to every paragraph of thisText
set lastName to ""
set lastArtist to ""
set lastAlbum to ""
set lastTime to ""
repeat with i from 1 to number of items in paragraphList
set thisItem to item i of paragraphList
--log thisItem
if thisItem starts with "Title:" then
set x to the offset of "Title:" in thisItem
set y to (text (x + 6) thru -1 of thisItem)
set lastName to my trim_line(y, " ", 2)
else if thisItem starts with "Artist:" then
set x to the offset of "Artist:" in thisItem
set y to (text (x + 7) thru -1 of thisItem)
set lastArtist to my trim_line(y, " ", 2)
else if thisItem starts with "Album:" then
set x to the offset of "Album:" in thisItem
set y to (text (x + 6) thru -1 of thisItem)
set lastAlbum to my trim_line(y, " ", 2)
else if thisItem starts with "Time:" then
set x to the offset of "Time:" in thisItem
set y to (text (x + 5) thru -1 of thisItem)
set lastTime to my trim_line(y, " ", 2)
end if
end repeat
log "lastName = '" & lastName & "'"
log "lastArtist = '" & lastArtist & "'"
log "lastAlbum = '" & lastAlbum & "'"
on readFile(thisFile)
set thisFile to thisFile as text
if thisFile is "" then return ""
try
set fi to open for access file the thisFile
set myData to read fi as text
close access file the thisFile
return myData
on error
try
close access file the thisFile
return ""
end try
end try
end readFile
on trim_line(this_text, trim_chars, trim_indicator)
-- 0 = beginning, 1 = end, 2 = both
set x to the length of the trim_chars
-- TRIM BEGINNING
if the trim_indicator is in {0, 2} then
repeat while this_text begins with the trim_chars
try
set this_text to characters (x + 1) thru -1 of this_text as string
on error
-- the text contains nothing but the trim characters
return ""
end try
end repeat
end if
-- TRIM ENDING
if the trim_indicator is in {1, 2} then
repeat while this_text ends with the trim_chars
try
set this_text to characters 1 thru -(x + 1) of this_text as string
on error
-- the text contains nothing but the trim characters
return ""
end try
end repeat
end if
return this_text
end trim_line

Folder image to iTunes artwork in applescript : not working anymore

Anyone of you guys could point me to why this applescript (which was working on snow leopard) does not work anymore on 10.7 Lion.
It intend to copy the file named "folder.jpg" from each album folder into ID3 tags of selected mp3 in iTunes.
property tempfile : ((path to temporary items as string) & "itunespicturefile_temporaire.pict")
global vPictFolder
tell application "iTunes"
set v_TrackSelection to selection
if v_TrackSelection is not {} then
repeat with vTrack in v_TrackSelection
set vPictFolder to my (ParentFromPath(location of vTrack as string)) as text
set thisPict to my getpictData("folder.jpg")
if thisPict is not "" then
delete artworks of vTrack
set data of artwork 1 of vTrack to (thisPict)
end if
end repeat
else
display dialog ("select tracks first !")
end if
end tell
on getpictData(vAlbumpictName)
tell application "Finder" to tell file vAlbumpictName of folder vPictFolder to if exists then
set t_file to it as string
else
display dialog vPictFolder & vAlbumpictName
return ""
end if
do shell script "/opt/local/bin/convert " & quoted form of POSIX path of t_file & " " & quoted form of POSIX path of tempfile
display dialog "ok"
return read (tempfile as alias) from 513 as picture
end getpictData
on ParentFromPath(thePath)
set wantPath to true
set thePath to (thePath as text)
set saveDelim to AppleScript's text item delimiters
set AppleScript's text item delimiters to {":"}
set pathAsList to text items of thePath
if the last character of thePath is ":" then
set idx to (the number of text items in thePath) - 2
else
set idx to -2
end if
if wantPath then
set folderName to ((text items 1 through idx of pathAsList) as text) & ":"
else
set folderName to item idx of pathAsList
end if
set AppleScript's text item delimiters to saveDelim
return folderName
end ParentFromPath
Because Picture format (".pict") is not supported on Lion and newer OS.
You can use the term picture to read a image file (JPEG, PNG, ...), the format will not be in the Picture format , but the original format of the file.
tell application "iTunes"
set v_TrackSelection to selection
if v_TrackSelection is not {} then
repeat with vTrack in v_TrackSelection
set vPictFolder to my (ParentFromPath(location of vTrack as string)) as text
set thisPict to my getpictData(vPictFolder & "folder.jpg")
if thisPict is not "" then
delete artworks of vTrack
set data of artwork 1 of vTrack to (thisPict)
end if
end repeat
else
display dialog ("select tracks first !")
end if
end tell
on getpictData(tFile)
try
return (read (tFile as alias) as picture)
end try
display dialog tFile
return "" -- not exists
end getpictData

Resources