Repeat function if variable is changed? - applescript

Having trouble figuring out this loop - I want the below function to repeat ONLY if myText changes (i.e. the album the individual is listening to changes) - I have been able to make it loop a certain number of times or repeat in the event the track changes, but I want it to repeat in the event the album changes.
tell application "iTunes"
repeat if myText changes
if player state is playing then
set albumName to (get album of current track)
set myText to text 1 thru 10 of albumName
end if
end repeat
end tell
open location "http://bandsite.com/shows/" & myText
When the code works without the repeat command it looks like this:
tell application "iTunes"
if player state is playing then
set albumName to (get album of current track)
set myText to text 1 thru 10 of albumName
end if
end tell
open location "http://bandsite.com/shows/" & myText
I need the whole function to repeat in the event myText changes

Save this as a stay open application:
property myList : {}
on run
set albumA to my playCheck()
if albumA ≠ false then
set end of myList to albumA
else
quit -- Quit on the next idle.
return 1 -- Please send the next idle as soon as possible.
end if
end run
on idle
set albumA to my playCheck()
if albumA ≠ false then
set end of myList to albumA
if (item -1 of myList) ≠ (item -2 of myList) then
open location "http://bandsite.com/shows/" & (text 1 thru 10 of albumA)
end if
end if
return 3
end idle
on playCheck()
tell application "iTunes"
if player state is playing then return (get album of current track)
return false
end tell
end playCheck

temptext = mytext
do
if temptext != myText
tell application "iTunes"
if player state is playing then
set albumName to (get album of current track)
set myText to text 1 thru 10 of albumName
end if
end tell
temptext = myText
end if
while temptext==text
Try this
Hope this is what you want...

Related

Applescript to extract YouTube Livestream Video ID

I want to develop an Applescript to extract youtube live stream video ID using the Channel ID.
Currently, I'm doing it manually as Youtube changes live stream video ID time to time.
For an example, I'm practising following;
Open https://www.youtube.com/embed/live_stream?channel=UCu7cGbQEMgGk8TD0ZYucM5g
Right-click on the player and select "Copy video URL"
This URL is used to an Applescript I wrote to automate Livestreamer. (This script is given below.)
As Youtube changes this URL time to time, following script has to be changed the time to time. My intention is to automate the whole process.
-- Shraddha TV and Radio Recorder --
-- Developed by Anoma --
set pathToShraddha to ((path to downloads folder as text) & "Shraddha:")
set outputExtension to ""
set ls to ""
set sourceURL to ""
set con to ""
set windowInfo to ""
set theTime to ""
set endTime to ""
display dialog "Shraddha TV or Radio" buttons {"TV", "Radio", "Cancel"} default button 1
if result = {button returned:"TV"} then
set outputExtension to ".ts"
set sourceURL to "https://www.youtube.com/watch?v=1yv7JjMP4Dw"
set ls to "livestreamer"
set con to "480p -o"
else if result = {button returned:"Radio"} then
set outputExtension to ".mp3"
set sourceURL to "http://92.222.236.128:8006"
set ls to "ffmpeg -i"
set con to "-c copy"
else
return
end if
set fn to (setFileName(outputExtension))
display dialog "Record now or later?" buttons {"Now", "Later", "Cancel"} default button 1
if result = {button returned:"Now"} then
set endTime to text returned of (display dialog "Please set the time to end recording. (Leave 'hhmm' if you want to record continuously.) " with title "Timer" default answer "hhmm" buttons {"Cancel", "Set"} default button 2)
set windowInfo to recordMedia(ls, sourceURL, con, (POSIX path of pathToShraddha as string), fn)
finishTime(endTime, windowInfo)
else if result = {button returned:"Later"} then
-- get time to be set---
set theTime to text returned of (display dialog "Please set the time to start recording." with title "Timer" default answer "hhmm" buttons {"Cancel", "Set"} default button 2)
if ((theTime as string) is equal to "hhmm") then
display dialog "Time is not set correctly"
return
end if
set endTime to text returned of (display dialog "Please set the time to end recording. (Leave 'hhmm' if you want to record continuously.) " with title "Timer" default answer "hhmm" buttons {"Cancel", "Set"} default button 2)
display dialog (getTimeInHoursAndMinutes())
display dialog theTime
set i to 0
repeat while (getTimeInHoursAndMinutes()) is less than theTime
if (i = 0) then
set i to (i + 1)
recordMedia("", "", "", "", "")
end if
delay 60
end repeat
finishTime(endTime, (recordMedia(ls, sourceURL, con, (POSIX path of pathToShraddha as string), fn)))
else
return
end if
-- This method generates the file name
on setFileName(outputExt)
set fileName to do shell script "date +'%Y-%m-%d_%H-%M-%S'"
set outputExt to the outputExt as string
set fileName to ("STV_" & fileName as string) & outputExt
return fileName as string
end setFileName
-- This method gives the current time in "hhmm" format (24hr)
on getTimeInHoursAndMinutes()
set timeStr to time string of (current date)
set hrStr to (characters 1 thru -10 of timeStr as string)
if ((count hrStr) is less than 2) then
set timeStr to ((0 & timeStr) as string)
end if
set ampm to (characters -2 thru -1 of timeStr as string)
if ((ampm as string) is equal to "PM") then
if ((hrStr as integer) is less than 12) then
set hrStr to (((hrStr as integer) + 12) as string)
end if
else
if ((hrStr as integer) = 12) then
set hrStr to (0 as string)
end if
if ((count hrStr) is less than 2) then
set hrStr to ((0 & hrStr) as string)
end if
end if
set mStr to (characters 4 thru 5 of timeStr as string)
set timeStr to (hrStr) & (mStr)
return timeStr as string
end getTimeInHoursAndMinutes
-- This method Record the stream --
on recordMedia(ls, sourceURL, con, pathToShraddhaString, fn)
tell application "Terminal"
set windowInfo to do script "caffeinate -i " & ls & space & sourceURL & space & con & space & pathToShraddhaString & fn
activate of windowInfo
end tell
return windowInfo
end recordMedia
-- This method end recording --
on finishTime(endTime, windowInfo)
if ((endTime as string) is equal to "hhmm") then
else
repeat while (getTimeInHoursAndMinutes()) is less than endTime
delay 60
end repeat
tell application "Terminal"
-- reopen
activate of windowInfo
--tell application "System Events" to keystroke "q"
tell application "System Events" to keystroke "c" using {control down}
end tell
end if
end finishTime
Could you please help me in developing the script to automate the extraction of the Livestream URL every time I run the script?
Thank you.
This is the answer given by Capitainos # Superuser.
It works really fine.
Property LivestreamURL : {}
-- set youtube_channel to choose URL -- just remove comment tag to choose this option
set youtube_channel to "https://www.youtube.com/embed/live_stream?channel=UCu7cGbQEMgGk8TD0ZYucM5g"
tell application "Safari"
launch -- background OR use 'activate' if preferred
open location youtube_channel
end tell
-- wait for Safari to load the webpage
if load_webpage(20) is false then return
tell application "Safari" to set end of LivestreamURL to do JavaScript "document.links[0].href" in document 1
set this_ID to item 1 of LivestreamURL
set channel_ID to (characters 51 thru -1 of youtube_channel) as string
set video_ID to (characters 33 thru -1 of this_ID) as string
-- return LivestreamURL -- or;
return return & "Channel ID : " & channel_ID & linefeed & "Video ID : " & video_ID & linefeed & linefeed
-- This is the Handler 'load_webpage'
on load_webpage(timeout_variable)
delay 2
repeat with i from 1 to the timeout_variable
tell application "Safari"
if (do JavaScript "document.readyState" in document 1) is "complete" then
return true
else if i is the timeout_variable then
return false
else
delay 1
end if
end tell
end repeat
return false
end load_webpage

Upload random file hourly with photos.app and applescript

I have baby photos in a folder and I want to upload them one at a time about every hour (4000 secs not 3600 secs) to a shared iCloud album that all my relatives see on their iPhones and iPads and macs. Here is my applescript saved as an application with the keep open box checked. I think it's not quite right. What's wrong?
on idle
set importFolder to "Amac:Users:AbuDavid:Downloads:uploadBABY"
set extensionsList to {"jpg", "png", "tiff"}
tell application "Finder" to set theFiles to some file of importFolder whose name extension is in extensionsList
if (count of theFiles) < 1 then
display dialog "No images selected!" buttons "OK"
else
set albumName to "BabyDouDou"
set timeNow to time string of (current date)
set today to date string of (current date)
set albumName to albumName & " " & timeNow & " " & today
set imageList to theFiles
tell application "Photos"
activate
delay 2
import imageList into albumName skip check duplicates yes
end tell
tell application "Finder" to move theFiles to trash
end if
return 4000
end idle
There are some issues:
The Finder needs the keyword folder – not just a literal string – to specify a folder.
some file returns always one file so the count command fails and returns always 0.
albumName is a literal string as well rather than a object specifier.
Photos.app expects alias specifiers for the files to be imported rather than Finder object specifiers.
Try this
on idle
set importFolder to (path to downloads folder as text) & "uploadBABY"
set extensionsList to {"jpg", "png", "tiff"}
tell application "Finder" to set theFiles to files of folder importFolder whose name extension is in extensionsList
if (count theFiles) < 1 then
display dialog "No images selected!" buttons "OK"
else
set theFile to some item of theFiles
set albumName to "BabyDouDou"
set timeNow to time string of (current date)
set today to date string of (current date)
set albumName to albumName & " " & timeNow & " " & today
set imageList to {theFile as alias}
tell application "Photos"
activate
delay 2
if not (exists container albumName) then
set theAlbum to make new album
set name of theAlbum to albumName
else
set theAlbum to container albumName
end if
import imageList into theAlbum skip check duplicates yes
end tell
tell application "Finder" to move theFiles to trash
end if
return 4000
end idle
Made a small change to only delete the image that was uploaded and not all the images. Thank you so much.
on idle
set importFolder to (path to downloads folder as text) & "uploadBABY"
set extensionsList to {"jpg", "png", "tiff"}
tell application "Finder" to set theFiles to files of folder importFolder whose name extension is in extensionsList
if (count theFiles) < 1 then
display dialog "No images selected!" buttons "OK"
else
set theFile to some item of theFiles
set albumName to "testscript"
set imageList to {theFile as alias}
tell application "Photos"
activate
delay 2
if not (exists container albumName) then
set theAlbum to make new album
set name of theAlbum to albumName
else
set theAlbum to container albumName
end if
import imageList into theAlbum skip check duplicates yes
end tell
tell application "Finder" to move theFile to trash
end if
return 7
end idle

Applescript Infinite Repeat Keystrokes hangs up applications

So for an infinite monkey theorem test i need applescript to input random numbers (0-6) into TextEdit.
I have a working code which doesn't slow down the cpu or anything, but i can't terminate it after running it once without terminating TextEdit.
So my question is:
How can i improve this code so it allows me to terminate it without any concerns.
delay 2
repeat
delay 0.2
tell application "System Events"
if (item 1 of (get name of processes whose frontmost is true)) is "TextEdit" then
set r to (random number from 0 to 1)
if (r = 0) then
keystroke "0"
else if (r = 1) then
keystroke "1"
end if
end if
end tell
end repeat
It will take a long time to create a large sample with a .2 delay and keystrokes.
Try something like this:
set csvOutputPath to (POSIX path of (path to desktop as text)) & "test.txt"
set fileRef to (open for access csvOutputPath)
close access csvOutputPath
set numberList to {}
set counter to 0
repeat
set end of numberList to (random number from 0 to 1)
set counter to counter + 1
if (counter mod 10000) = 0 then
write (numberList as text) to csvOutputPath starting at eof
set numberList to {}
end if
end repeat

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

Reading lyrics from itune to make a file

I got hints from http://www.dougscripts.com/itunes/ to come up with the following code. But it needs much more improvements.
I got error when I'm done with the file generation, http://a.imageshack.us/img831/1610/screenshot20100804at113l.png, what's wrong?
I don't need to use "TextEdit" for storing a file, is there better way just store the info to the file?
tell application "iTunes"
if player state is playing then
set sel to current track as list
else if selection is not {} then
set sel to selection
end if
set noSong to ""
set summaryFile to ((path to desktop as Unicode text) & "songs2.txt")
set ff to open for access file summaryFile with write permission
repeat with this_track in sel
set the_lyrics to this_track's lyrics
set {art, nom} to {this_track's artist, this_track's name}
if the_lyrics is not "" then
tell application "TextEdit"
activate
set myVar to art & nom & the_lyrics
write myVar to ff starting at eof
end tell
else
beep
end if
end repeat
end tell
Here are two subroutines I use to manage writing data to a text file:
on WriteLog(the_text)
set this_story to the_text
set this_file to (((path to desktop folder) as text) & "MY STORY")
my write_to_file(this_story, this_file, true)
end WriteLog
on write_to_file(this_data, target_file, append_data)
try
set the target_file to the target_file as text
set the open_target_file to ¬
open for access file target_file with write permission
if append_data is false then ¬
set eof of the open_target_file to 0
write this_data to the open_target_file starting at eof
close access the open_target_file
return true
on error
try
close access file target_file
end try
return false
end try
end write_to_file
Please note write_to_file() is Apple's code from their own old Applescript site in Essential Subroutines. WriteToLog() is my own subroutine that wrote to interface with write_to_file with only one argument, the text itself. Add salt to taste. To rewrite the script accomodate the above subroutines, I would do it like this:
tell application "iTunes"
if player state is playing then
set sel to current track as list
else if selection is not {} then
set sel to selection
end if
set noSong to ""
repeat with this_track in sel
set the_lyrics to this_track's lyrics
set {art, nom} to {this_track's artist, this_track's name}
if the_lyrics is not "" then
set myVar to art & nom & the_lyrics
my WriteLog(myVar)
else
beep
end if
end repeat
end tell
you just had some things out of scope all the opening closing and writing of the text file must be done outside of itunes and texedit is not needed
set summaryFile to ((path to desktop as Unicode text) & "songs2.txt")
try
close access (summaryFile as alias) -- close the file if its open alreayd
end try
set ff to open for access file summaryFile with write permission
tell application "iTunes"
if player state is playing then
set sel to current track as list
else if selection is not {} then
set sel to selection
end if
set noSong to ""
repeat with this_track in sel
set the_lyrics to lyrics of this_track
set {art, nom} to {artist of this_track, name of this_track}
if the_lyrics is not "" then
tell me
set myVar to art & nom & the_lyrics
write myVar to ff starting at eof
end tell
else
beep
end if
end repeat
end tell
close access (summaryFile as alias)

Resources