Can Applescript read an XML file stored as a variable?

Very almost…

on open theseFiles
		repeat with thisFile in theseFiles
				set TEST to thisFile
				set tracks to the mediainfoFile(TEST)'s tracks
						.
						.
						.
		end repeat
end open

on mediainfoFile(inputstring)
				.
				.
				.
end mediainfoFile

(* Other handlers *)

The mediainfoFilehandler (and all the other handlers in your script) belong outside the repeat loop, and outside the on open handler. But, otherwise, yes, the principle is correct.

I’ve re-written the entire script step by step. But I seem to still have an issue with this line:


repeat with thisFile in theseFiles -- STARTS CHECKING FILES IN SEQUENCE
		set thePromo to thisFile
		set tracks to the mediainfoFile(thePromo)'s tracks -- THIS LINE

These are the handlers I’m using that you gave me:


--THIS HANDLER READS THE XML DATA:
on trackInfo given type:type as text, id:|id| as text : -1, key:key as text
	local key, |id|, type
	global tracks
	
	tell application "System Events"
		if |id| = -1 then
			set {trackdata} to the |tracks| where ¬
				value of the XML attribute "type" = |type|
		else
			set {trackdata} to the |tracks| where ¬
				value of the XML attribute "type" = |type| and ¬
				value of the XML attribute "streamid" = |id|
		end if
		
		tell (a reference to XML element named key in the trackdata) to ¬
			if it exists then
				return its value
			else
				return false
			end if
	end tell
end trackInfo

--THIS HANDLER GENERATES THE XML DOCUMENT
on mediainfoFile(inputstring) -- Only call this once per script run
	set theFile to quoted form of POSIX path of (inputstring)
	set xmltext to do shell script "usr/local/bin/mediainfo " & ¬
		theFile & " --Output=XML"
	
	tell application "System Events"
		set xml to make new XML data with properties {text:xmltext}
		set mediaInfo to XML element "Mediainfo" of xml
		set |file| to XML element "File" of mediaInfo
		
		return {|tracks|:a reference to XML elements of |file|}
	end tell
end mediainfoFile

For some reason when I try to use it as an application to check a batch of files, it doesn’t seem to activate the mediainfoFile handler and generate the XML. It works perfectly fine in my script that only does one file at a time. I thought I was following your instructions from a few posts ago properly, but I’m not sure what part I’m missing.

I really appreciate all your help, and I’m very close to finishing this and wouldn’t be this far without you.

Thanks.

I need more information to go on. Forget trying to get it to work as an application for now; focus on trying to get it to work as a script that contains a repeat loop. What goes wrong ? Where does it go wrong ? What’s the error message ? What is happening that shouldn’t happen ? What isn’t happening that should ?

Population one open handler with multiply selection:


set theseFiles to (choose file of type {"public.movie"} with multiple selections allowed)

on open theseFiles
repeat with thisFile in theseFiles
set TEST to thisFile
set tracks to the mediainfoFile(TEST)'s tracks
--mediainfoFile handler/subroutine
end repeat

This is a stripped down version of the script that I’m working with to try and figure out the problem:


set theseFiles to (choose file with multiple selections allowed)
repeat with thisFile in theseFiles
	set tracks to the mediainfoFile(thisFile)'s tracks
	set PromoCodec to (trackInfo given type:"Video", key:"Commercial_name")
	set thename to name of (info for the thisFile) & " " & PromoCodec & " "
	return thename
end repeat



--THIS HANDLER READS THE XML DATA:
on trackInfo given type:type as text, id:|id| as text : -1, key:key as text
	local key, |id|, type
	global tracks
	
	tell application "System Events"
		if |id| = -1 then
			set {trackdata} to the |tracks| where ¬
				value of the XML attribute "type" = |type|
		else
			set {trackdata} to the |tracks| where ¬
				value of the XML attribute "type" = |type| and ¬
				value of the XML attribute "streamid" = |id|
		end if
		
		tell (a reference to XML element named key in the trackdata) to ¬
			if it exists then
				return its value
			else
				return false
			end if
	end tell
end trackInfo

--THIS HANDLER GENERATES THE XML DOCUMENT
on mediainfoFile(inputstring) -- Only call this once per script run
	set theFile to quoted form of POSIX path of (inputstring)
	set xmltext to do shell script "usr/local/bin/mediainfo " & ¬
		theFile & " --Output=XML"
	
	tell application "System Events"
		set xml to make new XML data with properties {text:xmltext}
		set mediaInfo to XML element "Mediainfo" of xml
		set |file| to XML element "File" of mediaInfo
		
		return {|tracks|:a reference to XML elements of |file|}
	end tell
end mediainfoFile

on returnNumbersInString(inputstring)
	set s to quoted form of inputstring
	do shell script "sed s/[a-zA-Z\\']//g <<< " & s
	set dx to the result
	set numlist to {}
	repeat with i from 1 to count of words in dx
		set this_item to word i of dx
		try
			set this_item to this_item as number
			set the end of numlist to this_item
		end try
	end repeat
	return numlist
end returnNumbersInString

So far this only seems to process the first file in the list, no matter how many I choose. I don’t think I’m using the repeat block properly.

Ok, I’ve got the repeat step working with this script:


set theseFiles to (choose file with multiple selections allowed)
set thelist to ""
repeat with x from 1 to count of theseFiles
	set thisFile to item x of theseFiles
	set tracks to the mediainfoFile(thisFile)'s tracks
	set PromoCodec to (trackInfo given type:"Video", key:"Commercial_name")
	set thename to name of (info for the thisFile) & " " & PromoCodec & " "
	set thelist to thelist & " " & thename & " "
end repeat
return thelist


--THIS HANDLER READS THE XML DATA:
on trackInfo given type:type as text, id:|id| as text : -1, key:key as text
	local key, |id|, type
	global tracks
	
	tell application "System Events"
		if |id| = -1 then
			set {trackdata} to the |tracks| where ¬
				value of the XML attribute "type" = |type|
		else
			set {trackdata} to the |tracks| where ¬
				value of the XML attribute "type" = |type| and ¬
				value of the XML attribute "streamid" = |id|
		end if
		
		tell (a reference to XML element named key in the trackdata) to ¬
			if it exists then
				return its value
			else
				return false
			end if
	end tell
end trackInfo

--THIS HANDLER GENERATES THE XML DOCUMENT
on mediainfoFile(inputstring) -- Only call this once per script run
	set theFile to quoted form of POSIX path of (inputstring)
	set xmltext to do shell script "usr/local/bin/mediainfo " & ¬
		theFile & " --Output=XML"
	
	tell application "System Events"
		set xml to make new XML data with properties {text:xmltext}
		set mediaInfo to XML element "Mediainfo" of xml
		set |file| to XML element "File" of mediaInfo
		
		return {|tracks|:a reference to XML elements of |file|}
	end tell
end mediainfoFile

But for some reason once I add the “on open” command to try and make it into an application that’s where my variables stop populating properly. Here’s the same script as above, but with the added “on open” step to try and make it an application:


set theseFiles to (choose file with multiple selections allowed)
set thelist to ""

on open theseFiles
	repeat with x from 1 to count of theseFiles
		set thisFile to item x of theseFiles
		set tracks to the mediainfoFile(thisFile)'s tracks
		set PromoCodec to (trackInfo given type:"Video", key:"Commercial_name")
		set thename to name of (info for the thisFile) & " " & PromoCodec & " "
		set thelist to thelist & " " & thename & " "
	end repeat
end open
display dialog "..." & thelist


--THIS HANDLER READS THE XML DATA:
on trackInfo given type:type as text, id:|id| as text : -1, key:key as text
	local key, |id|, type
	global tracks
	
	tell application "System Events"
		if |id| = -1 then
			set {trackdata} to the |tracks| where ¬
				value of the XML attribute "type" = |type|
		else
			set {trackdata} to the |tracks| where ¬
				value of the XML attribute "type" = |type| and ¬
				value of the XML attribute "streamid" = |id|
		end if
		
		tell (a reference to XML element named key in the trackdata) to ¬
			if it exists then
				return its value
			else
				return false
			end if
	end tell
end trackInfo

--THIS HANDLER GENERATES THE XML DOCUMENT
on mediainfoFile(inputstring) -- Only call this once per script run
	set theFile to quoted form of POSIX path of (inputstring)
	set xmltext to do shell script "usr/local/bin/mediainfo " & ¬
		theFile & " --Output=XML"
	
	tell application "System Events"
		set xml to make new XML data with properties {text:xmltext}
		set mediaInfo to XML element "Mediainfo" of xml
		set |file| to XML element "File" of mediaInfo
		
		return {|tracks|:a reference to XML elements of |file|}
	end tell
end mediainfoFile

Is the code different when trying to make an application? I’m obviously missing something.

What you get is logical.
When your script execute return theName it exits the loop.

Try with:

set theseFiles to (choose file with multiple selections allowed)
set theNames to {}
repeat with thisFile in theseFiles
	set tracks to the mediainfoFile(thisFile)'s tracks
	set PromoCodec to (trackInfo given type:"Video", key:"Commercial_name")
	set thename to name of (info for the thisFile) & " " & PromoCodec & " "
	set end of theNames to thename
end repeat
return theNames
# Here are the handlers

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) lundi 13 mai 2019 17:41:53

Here is the almost finished script. It works exactly how I need it to. It can read multiple files and the error checks I’ve built in process everything correctly. The only step left is to figure out how to make it work as a droplet/application. Thank you all for your help getting me this far.


set theseFiles to (choose file with multiple selections allowed)
-- THESE ARE THE ERROR VARIABLES
set CodecError to 0 --Codec Errors will highlight the file GRAY
set DurationError to 0 --Duration Errors will highlight the file YELLOW
set InvalidDuration to 0
set InvalidS4MNumber to 0
set TotalCodecErrors to 0 -- COUNTS CODEC ERRORS
set TotalDurationErrors to 0 -- COUNTS PROMO DURATION ERRORS
set TotalS4MNumberErrors to 0 -- COUNTS BAD S4M NUMBERS IN FILENAMES
set TotalFileNameErrors to 0 -- COUNTS DURATION ERRORS OF TOP OF FILENAMES
set TotalPromoError to 0 -- RESULTS IN "FILE NOT PROPERLY PROCESSED"
set FilesWithCodecErrors to "" -- CREATES A LIST OF THE PROMOS THAT HAVE CODEC ERRORS
set FilesWithDurationErrors to "" -- CREATES A LIST OF THE PROMOS THAT HAVE DURATION ERRORS
set FilesWithFileNameErrors to "" -- CREATES A LIST OF THE PROMOS THAT HAVE FILENAME ERRORS
set FilesWithS4MNumberErrors to "" -- CREATES A LIST OF THE PROMOS THAT HAVE S4M NUMBER ERRORS
set FilesNotProcessed to "" -- CREATES A LIST OF PROMOS THAT WERE NOT PROCESSED
set theRightFormats to {"XDCAM HD422", "50.0 Mbps", "29.970 fps"} as list

repeat with x from 1 to count of theseFiles -- STARTS CHECKING FILES IN SEQUENCE
	set thePromo to item x of theseFiles
	set tracks to the mediainfoFile(thePromo)'s tracks
	
	--WHEN MEDIAINFO READS AN MXF WITH XDCAM HD422 AS THE CODEC THE FIELD IS LABELLED
	--"Commercial_Name". THIS TRY BLOCK CHECKS THE CODEC FIELD OF THE XML
	--TO MAKE SURE THE PROPER CODEC FIELD IS PRESENT
	try
		set PromoCodec to (trackInfo given type:"Video", key:"Commercial_name")
		if the PromoCodec = false then
			set CodecError to 1
		end if
		
		--IF THE PROPER CODEC IS PRESENT THIS IS WHERE THE VARIABLES ARE POPULATED BY THE MEDIAINFOFILE HANDLER
		if CodecError is equal to 0 then
			set PromoBitRate to (trackInfo given type:"Video", key:"Bit_rate")
			set PromoDuration to (trackInfo given type:"Audio", id:2, key:"Duration")
			set PromoFrameRate to (trackInfo given type:"Video", key:"Frame_rate")
			set theDuration to returnNumbersInString(PromoDuration)
			set Duration to SAR(theDuration, ", ", ".")
			set FileName to do shell script "basename " & quoted form of POSIX path of thePromo
			set S4MDuration to the first word of FileName
		end if
	end try
	
	--THIS SECTION IS WHERE THE TRUNCATED FILE NAME IS CREATED
	try
		tell application "Finder"
			set extension hidden of thePromo to false
		end tell
		
		set theName to name of (info for thePromo)
		set thePath to the POSIX path of thePromo
		
		set n to the number of characters in theName
		
		set n to (n - 11)
		
		set JustS4MNumber to (characters n through end of theName) as string
		
		set theNewPath to quoted form of ("/Users/jquimby/Desktop/Proxies/" & JustS4MNumber)
		--THE ABOVE LINE IS WHERE THE FILE WILL BE POSTED IF IT PASSES ALL TECH CHECKS
		
		set theOldpath to quoted form of thePath
		set PromoError to 0
		
	on error
		set PromoError to 1
	end try
	
	--THIS IS THE BEGINNING OF THE TECH CHECKS
	if PromoError is equal to 0 and CodecError is equal to 0 then
		set theS4MNumber to the word -2 of theName --word -2 removes the file extension
		set S4MNumberCheck to the first word of JustS4MNumber
		
		--THIS SECTION CHECKS THAT THE FIRST WORD OF THE FILE NAME IS ACTUALLY A VALID NUMBER
		try
			set DurationCheck to (S4MDuration + 2)
		on error
			set InvalidDuration to 1
		end try
		
		--THIS SECTION ENSURES THE PROMO DURATION IS WITHIN A 2 FRAME RANGE OF THE TARGET DURATION
		if InvalidDuration is equal to 0 then
			set FramesHeavy to (S4MDuration + 0.66)
			set FramesLight to (S4MDuration - 0.66)
			if Duration is greater than FramesLight and Duration is less than FramesHeavy then
				set DurationError to 0
			else
				set DurationError to 1
			end if
		end if
		
		--THIS SECTION CHECKS THAT THE S4M NUMBER IS 8 DIGITS AND CONTAINS ONLY NUMBERS
		if the number of characters of theS4MNumber is equal to 8 then
			try
				set theS4MCalc to (theS4MNumber + 2)
			on error
				set InvalidS4MNumber to 1
			end try
		else
			set InvalidS4MNumber to 1
		end if
		if the number of characters of S4MNumberCheck is not equal to 8 then
			set InvalidS4MNumber to 1
		end if
		
		--THIS SECTION CHECKS TO ENSURE THE CODEC AND BIT RATE ARE CORRECT
		if PromoCodec is not in theRightFormats and PromoBitRate is not in theRightFormats then
			set CodecError to 1
		else
			set CodecError to 0
		end if
	end if
	
	--THIS SECTION CHECKS ALL THE ERROR COUNTERS, LABELS THE FILES IN FINDER, CREATES THE ERROR LIST, AND IF THE FILE PASSES ALL CHECKS IT WILL PASTE THE FILE INTO THE DESIRED DESTINATION 	
	if PromoError is equal to 0 then
		tell application "Finder"
			if CodecError is not equal to 0 then -- CODEC ERROR CHECK
				set label index of thePromo to 2
				set TotalCodecErrors to TotalCodecErrors + 1
				set FilesWithCodecErrors to FilesWithCodecErrors & theName & "" & " 	• codec is " & PromoCodec & "
				"
				set CodecError to 0
			else
				if InvalidS4MNumber is not equal to 0 then -- BAD S4M NUMBER FORMAT IN FILENAME
					set label index of thePromo to 4
					set FilesWithS4MNumberErrors to FilesWithS4MNumberErrors & theName & "
					"
					set TotalS4MNumberErrors to TotalS4MNumberErrors + 1
					set InvalidS4MNumber to 0
				else
					if DurationError is not equal to 0 then -- PROMO IS NOT WITHIN THE 2 FRAME BUFFER FOR DURATION
						set label index of thePromo to 7
						set TotalDurationErrors to TotalDurationErrors + 1
						set FilesWithDurationErrors to FilesWithDurationErrors & theName & "
						"
						set DurationError to 0
					else
						if InvalidDuration is not equal to 0 then -- BAD DURATION FORMAT IN FILENAME
							set label index of thePromo to 3
							set TotalFileNameErrors to TotalFileNameErrors + 1
							set FilesWithFileNameErrors to FilesWithFileNameErrors & theName & "
					" & " 	• length is " & (round (Duration / 30)) & " seconds
					"
							set InvalidDuration to 0
						else
							set label index of thePromo to 6
							do shell script "cp " & theOldpath & " " & theNewPath --THIS IS THE STEP THAT ACTUALLY COPIES THE FILE TO THE NEW LOCATION
						end if
					end if
				end if
			end if
		end tell
		set PromoError to 0
	end if
	if PromoError is not equal to 0 then
		tell application "Finder"
			set label index of thePromo to 5
			set TotalPromoError to TotalPromoError + 1
			set FilesNotProcessed to FilesNotProcessed & (name of (info for thePromo)) & "
				"
		end tell
	end if
end repeat -- END OF INDIVIDUAL FILE CHECK REPEAT LOOP

--THIS IS WHERE THE BATCH ERROR MESSAGES BEGIN

tell application "Finder"
	if FilesWithCodecErrors is not equal to "" then
		display dialog "..." & TotalCodecErrors & " file(s) are not the proper codec...
" & FilesWithCodecErrors & "
(Label colour: red)" buttons "Thanks"
	end if
	if FilesWithS4MNumberErrors is not equal to "" then
		display dialog "..." & TotalS4MNumberErrors & " file(s) do not have a proper S4M number...
	" & FilesWithS4MNumberErrors & "(Label colour: blue)" buttons "Thanks"
	end if
	if FilesWithDurationErrors is not equal to "" then
		display dialog "..." & TotalDurationErrors & " file(s) were not the proper duration...
	" & FilesWithDurationErrors & "(Label colour: yellow)" buttons "Thanks"
	end if
	if FilesWithFileNameErrors is not equal to "" then
		display dialog "..." & TotalFileNameErrors & " file(s) had incorrect durations in their file name(s).
	" & FilesWithFileNameErrors & "(Label colour: purple)" buttons "Thanks"
	end if
	if FilesNotProcessed is not equal to "" then
		display dialog "..." & TotalPromoError & " file(s) were not properly processed.
		" & FilesNotProcessed & "(Label colour: orange)" buttons "Thanks"
	end if
	if FilesWithCodecErrors is equal to "" and FilesWithS4MNumberErrors is equal to "" and FilesWithDurationErrors is equal to "" and FilesWithFileNameErrors is equal to "" and FilesNotProcessed is equal to "" then
		display dialog "All OK!" & theName & "
		(Label colour: green)" buttons "Thanks"
	end if
end tell


--THIS HANDLER READS THE XML DATA:
on trackInfo given type:type as text, id:|id| as text : -1, key:key as text
	local key, |id|, type
	global tracks
	
	tell application "System Events"
		if |id| = -1 then
			set {trackdata} to the |tracks| where ¬
				value of the XML attribute "type" = |type|
		else
			set {trackdata} to the |tracks| where ¬
				value of the XML attribute "type" = |type| and ¬
				value of the XML attribute "streamid" = |id|
		end if
		
		tell (a reference to XML element named key in the trackdata) to ¬
			if it exists then
				return its value
			else
				return false
			end if
	end tell
end trackInfo

--THIS HANDLER GENERATES THE XML DATA
on mediainfoFile(inputstring) -- Only call this once per script run
	set theFile to quoted form of POSIX path of (inputstring)
	set xmltext to do shell script "usr/local/bin/mediainfo " & ¬
		theFile & " --Output=XML"
	
	tell application "System Events"
		set xml to make new XML data with properties {text:xmltext}
		set mediaInfo to XML element "Mediainfo" of xml
		set |file| to XML element "File" of mediaInfo
		
		return {|tracks|:a reference to XML elements of |file|}
	end tell
end mediainfoFile

--THIS HANDLER EXTRACTS NUMBERS FROM A STRING
on returnNumbersInString(inputstring)
	set s to quoted form of inputstring
	do shell script "sed s/[a-zA-Z\\']//g <<< " & s
	set dx to the result
	set numlist to {}
	repeat with i from 1 to count of words in dx
		set this_item to word i of dx
		try
			set this_item to this_item as number
			set the end of numlist to this_item
		end try
	end repeat
	return numlist
end returnNumbersInString

--THIS HANDLER SEARCHES A STRING FOR SPECIFIED CHARACTERS AND REPLACES THEM WITH THE DESIGNATED CHARACTERS
on SAR(main_text, search_text, replace_text)
	set old_delims to AppleScript's text item delimiters
	try
		set AppleScript's text item delimiters to search_text
		considering case
			set parts to every text item of main_text
		end considering
		set AppleScript's text item delimiters to replace_text
		set newText to (parts as string)
	end try
	set AppleScript's text item delimiters to old_delims
	return newText
end SAR

I thought it would be as simple as changing:


set theseFiles to (choose file with multiple selections allowed)

to:


on open theseFiles

then adding an “End Open” after I end the repeat. But I start getting the “PromoCodec” not defined error again. Is there something I’m missing in modifying the script so it can work as a droplet?

Save the code below as an application.
It will behave as a droplet if you dop selected files on its icon.

on run
	
	set theseFiles to (choose file with multiple selections allowed)
	common(theseFiles)
end run

on open sel
	common(sel)
	# CAUTION. Given a feature of the open handler, the list of files may be trated as two separate lists according to the quarantine status of the dropped files.
end open

on common(theseFiles)
	# Here most of your code
	
	# Fake code
	set thePaths to my recolle(theseFiles, linefeed)
	display dialog thePaths
end common

# Now your existing handlers


#===== Just to show the structure at work

on recolle(l, d)
	local oTIDs, t
	set {oTIDs, AppleScript's text item delimiters} to {AppleScript's text item delimiters, d}
	set t to l as text
	set AppleScript's text item delimiters to oTIDs
	return t
end recolle

#=====

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) lundi 13 mai 2019 19:53:54

This might be better done like this:

set theseFiles to (choose file with multiple selections allowed)
set thelist to {}
repeat with i from 1 to count of theseFiles
		set thisFile to item i of theseFiles
		set tracks to the mediainfoFile(thisFile)'s tracks
		set PromoCodec to (trackInfo given type:"Video", key:"Commercial_name")
		set thename to name of (info for the thisFile) & space & PromoCodec
		set the end of thelist to thename
end repeat
return thelist

This returns an AppleScript list that looks like this: (I used the same infofile twice)[format]{“mediainfo.xml XDCAM HD422”, “mediainfo.xml XDCAM HD422”}[/format]If you want it as a text-based list, say, one item per line, then:

set the text item delimiters to linefeed
return thelist as text

which produces this:[format]“mediainfo.xml XDCAM HD422
mediainfo.xml XDCAM HD422”[/format]

It feels a bit awkward having to resort to using a counter variable to iterate through the list. The reason you felt you had to do that is because of the way the two different types of loop reference the items in the list: using a counter variable as above, one retrieves the list item directly:

set thisFile to item i of theseFiles

Using an iterator, the items in the list are retrieved as references, and need to be dereferenced (or evaluated) first:

repeat with thisFile in theseFiles
		thisFile as alias
		--OR:
		thisFile's contents
				.
				.
				.
end repeat

Therefore, you may find the problem that was solved by using the counter variable also gets solved like this:

set theseFiles to (choose file with multiple selections allowed)
set thelist to {}
repeat with thisFile in theseFiles
		set tracks to the mediainfoFile(thisFile as alias)'s tracks
		set PromoCodec to (trackInfo given type:"Video", key:"Commercial_name")
		set thename to name of (info for the thisFile) & space & PromoCodec
		set the end of thelist to thename
end repeat
return thelist

I’m still not a fan of the way you blanket lines of code within try blocks that don’t need it. Here’s an example:

try
		tell application "Finder"
		    set extension hidden of thePromo to false
		end tell

		set theName to name of (info for thePromo)
		set thePath to the POSIX path of thePromo
		set n to the number of characters in theName
		set n to (n - 11)
		set JustS4MNumber to (characters n through end of theName) as string
		set theNewPath to quoted form of ("/Users/jquimby/Desktop/Proxies/" & JustS4MNumber)
		--THE ABOVE LINE IS WHERE THE FILE WILL BE POSTED IF IT PASSES ALL TECH CHECKS
		set theOldpath to quoted form of thePath
		set PromoError to 0
on error
		set PromoError to 1
end try

This was chosen at random, actually, but having gone through each line individually, I can’t discern how any of them would ever throw an error; and, if there were a risk, how there wouldn’t be a very simple way to prevent it, or rectify it upon catching.

One line that is very potentially capable of throwing an error (and it would only be through bad luck and not poor coding), is set extension hidden of thePromo to false. Assuming thePromo is a well-formed file reference that Finder can understand, then the only risk is from Finder being temperamental: so, if it were busy, or it just decided not to let you access the property, it might error. Simply waiting until Finder is not blocked and then re-running the script solves that problem.

However, consider whether you need to set this property at all… It looks like you might be doing it to ensure theName is assigned the full filename including extension, however this property is not affected by the visibility of the extension in Finder (only the displayed name accounts for this). If you do need to set the property, then you may as well move the declaration of theName into the Finder block, and use Finder to access the name (rather than the deprecated info for). It doesn’t make a huge difference, given that info for has been deprecated for about ten years and still works perfectly reliably and actually much faster than Finder. I’ll let you decide.

The only other line capable of throwing an error is: set JustS4MNumber to (characters n through end of theName) as string. Firstly, I’m going to suggest you re-write this line to:

set JustS4MNumber to text n thru -1 of theName

The reason for this is that retrieving characters produces a list, which you then have to coerce back to text, and that is subject to text item delimiters, which you haven’t set. Instead, obtain a text range gives you the substring as one chunk of text, so there’s no need to coerce and no risk of getting back a string you didn’t expect. Now, the only way this can throw an error is if n is 0, i.e. if theName happened to be 11 characters long.

In summation for this particular try block, I would suggest it is completely unnecessary, and you simply need to ensure the thePromo is a valid file reference; and n isn’t 0 (or, rather, the name of your files are at least 12 characters long).

I see Yvan has given some guidance about moving the script to an application.

Oh, you can debug this quite simply by:

on open theseFiles
		return choose from list paragraphs of (theseFiles as text)

which will allow you to examine exactly what list of files is getting passed through to the on open handler. Given what Yvan noted about the possibility of split lists of files if some are quarantined, resulting in theseFiles being a list of lists, you might see if it makes a difference were you to flatten the list and guarantee it is one-dimensional. Here’s a simple flatten() handler:

to flatten(L)
		local L
		
		if L = {} then return {}
		if L's class ≠ list then return {L}
		
		flatten(L's first item) & flatten(rest of L)
end flatten

To illustrate its function:

set L to {{1, 3, 4, {4, 5, {4, {{5}}, 5}, 5, {4, 3, 4}}, 4, 2, 3, 3}, {2, 3, {4, 5}}, 4}
flatten(L)

[format]Result:
{1, 3, 4, 4, 5, 4, 5, 5, 5, 4, 3, 4, 4, 2, 3, 3, 2, 3, 4, 5, 4}[/format]

I’ve tried all suggestions, and I’m still getting the error. I think the error is within these lines:


on open theseFiles
repeat with i from 1 to count of theseFiles -- STARTS CHECKING FILES IN SEQUENCE
	set thePromo to item i of theseFiles
	set tracks to the mediainfoFile(thePromo)'s tracks
	
	try
		set PromoCodec to (trackInfo given type:"Video", key:"Commercial_name")
		if the PromoCodec = false then
			set CodecError to 1
		end if
		
		if CodecError is equal to 0 then
			set PromoBitRate to (trackInfo given type:"Video", key:"Bit_rate")
			set PromoDuration to (trackInfo given type:"Audio", id:2, key:"Duration")
			set PromoFrameRate to (trackInfo given type:"Video", key:"Frame_rate")
			set theDuration to returnNumbersInString(PromoDuration)
			set Duration to SAR(theDuration, ", ", ".")
			set FileName to do shell script "basename " & quoted form of POSIX path of thePromo
			set S4MDuration to the first word of FileName
		end if
	end try
end open

Inevitably, when I get to this line further down the script:


if PromoCodec is not in theRightFormats and PromoBitRate is not in theRightFormats then

I receive an error saying PromoCodec is not defined.

Yvan - I tried your suggestion, and I still run into the same issue.

If I remove the Try block from the above script it tells me that “tracks” is not defined. Looking at Yvan’s suggestion, I see that it shouldn’t be an issue using a handler within a handler. I’m just confused as to why I can have a script working perfectly, but as soon as I try to make it an application it breaks.

If I add “on run” at the top and “end run” at the bottom (before my handlers) and export as an application it works, but I can’t drag/drop files onto it. I have to double click on the app, select the files I want to process, then it will process them correctly. I just can’t get my head around why using “on open” seems to break(for lack of a better word) this line:


set tracks to the mediainfoFile(thePromo)'s tracks

CK - I used your suggested return line to see what was being passed through the on open command, and all the files I selected were passed through. Once I add “on open” it just for some reason will either not read or not generate the XML properly is my only guess. Or maybe it’s the repeat line? I’ve tried both of these versions to no avail:


	repeat with i from 1 to count of theseFiles -- STARTS CHECKING FILES IN SEQUENCE
		set thePromo to item i of theseFiles
		set tracks to the mediainfoFile(thePromo)'s tracks

and


repeat with i from 1 to count of theseFiles -- STARTS CHECKING FILES IN SEQUENCE
set thePromo to item i of theseFiles
set tracks to the mediainfoFile(thePromo as alias)'s tracks

I’ve progressively moved the “return” command down through the script to find where things stop populating.


on open theseFiles
	-- THESE ARE THE ERROR VARIABLES
	set CodecError to 0 --Codec Errors will highlight the file GRAY
	set DurationError to 0 --Duration Errors will highlight the file YELLOW
	set InvalidDuration to 0
	set InvalidS4MNumber to 0
	set TotalCodecErrors to 0 -- COUNTS CODEC ERRORS
	set TotalDurationErrors to 0 -- COUNTS PROMO DURATION ERRORS
	set TotalS4MNumberErrors to 0 -- COUNTS BAD S4M NUMBERS IN FILENAMES
	set TotalFileNameErrors to 0 -- COUNTS DURATION ERRORS OF TOP OF FILENAMES
	set TotalPromoError to 0 -- RESULTS IN "FILE NOT PROPERLY PROCESSED"
	set FilesWithCodecErrors to "" -- CREATES A LIST OF THE PROMOS THAT HAVE CODEC ERRORS
	set FilesWithDurationErrors to "" -- CREATES A LIST OF THE PROMOS THAT HAVE DURATION ERRORS
	set FilesWithFileNameErrors to "" -- CREATES A LIST OF THE PROMOS THAT HAVE FILENAME ERRORS
	set FilesWithS4MNumberErrors to "" -- CREATES A LIST OF THE PROMOS THAT HAVE S4M NUMBER ERRORS
	set FilesNotProcessed to "" -- CREATES A LIST OF PROMOS THAT WERE NOT PROCESSED
	set theRightFormats to {"XDCAM HD422", "50.0 Mbps", "29.970 fps"} as list
	
	repeat with i from 1 to count of theseFiles -- STARTS CHECKING FILES IN SEQUENCE
		set thePromo to item i of theseFiles
		set tracks to the mediainfoFile(thePromo)'s tracks
		
		--WHEN MEDIAINFO READS AN MXF WITH XDCAM HD422 AS THE CODEC THE FIELD IS LABELLED
		--"Commercial_Name". THIS TRY BLOCK CHECKS THE CODEC FIELD OF THE XML
		--TO MAKE SURE THE PROPER CODEC FIELD IS PRESENT
		try
			set PromoCodec to trackInfo given type:"Video", key:"Commercial_name"
----------------------------------------------------------------------------------------------------------------
			return choose from list paragraphs of (PromoCodec as text)
----------------------------------------------------------------------------------------------------------------
			if the PromoCodec = false then
				set CodecError to 1
			end if
			
			--IF THE PROPER CODEC IS PRESENT THIS IS WHERE THE VARIABLES ARE POPULATED BY THE MEDIAINFOFILE HANDLER
			if CodecError is equal to 0 then
				set PromoBitRate to (trackInfo given type:"Video", key:"Bit_rate")
				set PromoDuration to (trackInfo given type:"Audio", id:2, key:"Duration")
				set PromoFrameRate to (trackInfo given type:"Video", key:"Frame_rate")
				set theDuration to returnNumbersInString(PromoDuration)
				set Duration to SAR(theDuration, ", ", ".")
				set FileName to do shell script "basename " & quoted form of POSIX path of thePromo
				set S4MDuration to the first word of FileName
			end if
		end try
end open

--THIS HANDLER READS THE XML DATA:
on trackInfo given type:type as text, id:|id| as text : -1, key:key as text
	local key, |id|, type
	global tracks
	
	tell application "System Events"
		if |id| = -1 then
			set {trackdata} to the |tracks| where ¬
				value of the XML attribute "type" = |type|
		else
			set {trackdata} to the |tracks| where ¬
				value of the XML attribute "type" = |type| and ¬
				value of the XML attribute "streamid" = |id|
		end if
		
		tell (a reference to XML element named key in the trackdata) to ¬
			if it exists then
				return its value
			else
				return false
			end if
	end tell
end trackInfo

--THIS HANDLER GENERATES THE XML DATA
on mediainfoFile(inputstring) -- Only call this once per script run
	set theFile to quoted form of POSIX path of (inputstring)
	set xmltext to do shell script "usr/local/bin/mediainfo " & ¬
		theFile & " --Output=XML"
	
	tell application "System Events"
		set xml to make new XML data with properties {text:xmltext}
		set mediaInfo to XML element "Mediainfo" of xml
		set |file| to XML element "File" of mediaInfo
		
		return {|tracks|:a reference to XML elements of |file|}
	end tell
end mediainfoFile

--THIS HANDLER EXTRACTS NUMBERS FROM A STRING
on returnNumbersInString(inputstring)
	set s to quoted form of inputstring
	do shell script "sed s/[a-zA-Z\\']//g <<< " & s
	set dx to the result
	set numlist to {}
	repeat with i from 1 to count of words in dx
		set this_item to word i of dx
		try
			set this_item to this_item as number
			set the end of numlist to this_item
		end try
	end repeat
	return numlist
end returnNumbersInString

--THIS HANDLER SEARCHES A STRING FOR SPECIFIED CHARACTERS AND REPLACES THEM WITH THE DESIGNATED CHARACTERS
on SAR(main_text, search_text, replace_text)
	set old_delims to AppleScript's text item delimiters
	try
		set AppleScript's text item delimiters to search_text
		considering case
			set parts to every text item of main_text
		end considering
		set AppleScript's text item delimiters to replace_text
		set newText to (parts as string)
	end try
	set AppleScript's text item delimiters to old_delims
	return newText
end SAR

theseFiles populates and thePromo populates, which leads me to believe my XML handlers should work properly. But for some reason they aren’t.

I was reluctant to do that but see no alternate way to exchange seriously.

I inserted your original code in the proposed structure. I got :

on run
	set theseFiles to (choose file with multiple selections allowed)
	common(theseFiles)
end run
on open sel
	common(sel)
end open

on common(theseFiles)
	-- THESE ARE THE ERROR VARIABLES
	set CodecError to 0 --Codec Errors will highlight the file GRAY
	set DurationError to 0 --Duration Errors will highlight the file YELLOW
	set InvalidDuration to 0
	set InvalidS4MNumber to 0
	set TotalCodecErrors to 0 -- COUNTS CODEC ERRORS
	set TotalDurationErrors to 0 -- COUNTS PROMO DURATION ERRORS
	set TotalS4MNumberErrors to 0 -- COUNTS BAD S4M NUMBERS IN FILENAMES
	set TotalFileNameErrors to 0 -- COUNTS DURATION ERRORS OF TOP OF FILENAMES
	set TotalPromoError to 0 -- RESULTS IN "FILE NOT PROPERLY PROCESSED"
	set FilesWithCodecErrors to "" -- CREATES A LIST OF THE PROMOS THAT HAVE CODEC ERRORS
	set FilesWithDurationErrors to "" -- CREATES A LIST OF THE PROMOS THAT HAVE DURATION ERRORS
	set FilesWithFileNameErrors to "" -- CREATES A LIST OF THE PROMOS THAT HAVE FILENAME ERRORS
	set FilesWithS4MNumberErrors to "" -- CREATES A LIST OF THE PROMOS THAT HAVE S4M NUMBER ERRORS
	set FilesNotProcessed to "" -- CREATES A LIST OF PROMOS THAT WERE NOT PROCESSED
	set theRightFormats to {"XDCAM HD422", "50.0 Mbps", "29.970 fps"} as list
	
	repeat with x from 1 to count of theseFiles -- STARTS CHECKING FILES IN SEQUENCE
		set thePromo to item x of theseFiles
		set tracks to the mediainfoFile(thePromo)'s tracks
		
		--WHEN MEDIAINFO READS AN MXF WITH XDCAM HD422 AS THE CODEC THE FIELD IS LABELLED
		--"Commercial_Name". THIS TRY BLOCK CHECKS THE CODEC FIELD OF THE XML
		--TO MAKE SURE THE PROPER CODEC FIELD IS PRESENT
		try
			set PromoCodec to (trackInfo given type:"Video", key:"Commercial_name")
			if the PromoCodec = false then
				set CodecError to 1
			end if
			
			--IF THE PROPER CODEC IS PRESENT THIS IS WHERE THE VARIABLES ARE POPULATED BY THE MEDIAINFOFILE HANDLER
			if CodecError is equal to 0 then
				set PromoBitRate to (trackInfo given type:"Video", key:"Bit_rate")
				set PromoDuration to (trackInfo given type:"Audio", id:2, key:"Duration")
				set PromoFrameRate to (trackInfo given type:"Video", key:"Frame_rate")
				set theDuration to returnNumbersInString(PromoDuration)
				set Duration to SAR(theDuration, ", ", ".")
				set FileName to do shell script "basename " & quoted form of POSIX path of thePromo
				set S4MDuration to the first word of FileName
			end if
		end try
		
		--THIS SECTION IS WHERE THE TRUNCATED FILE NAME IS CREATED
		try
			tell application "Finder"
				set extension hidden of thePromo to false
			end tell
			
			set theName to name of (info for thePromo)
			set thePath to the POSIX path of thePromo
			
			set n to the number of characters in theName
			
			set n to (n - 11)
			
			set JustS4MNumber to (characters n through end of theName) as string
			
			set theNewPath to quoted form of ("/Users/jquimby/Desktop/Proxies/" & JustS4MNumber)
			--THE ABOVE LINE IS WHERE THE FILE WILL BE POSTED IF IT PASSES ALL TECH CHECKS
			
			set theOldpath to quoted form of thePath
			set PromoError to 0
			
		on error
			set PromoError to 1
		end try
		
		--THIS IS THE BEGINNING OF THE TECH CHECKS
		if PromoError is equal to 0 and CodecError is equal to 0 then
			set theS4MNumber to the word -2 of theName --word -2 removes the file extension
			set S4MNumberCheck to the first word of JustS4MNumber
			
			--THIS SECTION CHECKS THAT THE FIRST WORD OF THE FILE NAME IS ACTUALLY A VALID NUMBER
			try
				set DurationCheck to (S4MDuration + 2)
			on error
				set InvalidDuration to 1
			end try
			
			--THIS SECTION ENSURES THE PROMO DURATION IS WITHIN A 2 FRAME RANGE OF THE TARGET DURATION
			if InvalidDuration is equal to 0 then
				set FramesHeavy to (S4MDuration + 0.66)
				set FramesLight to (S4MDuration - 0.66)
				if Duration is greater than FramesLight and Duration is less than FramesHeavy then
					set DurationError to 0
				else
					set DurationError to 1
				end if
			end if
			
			--THIS SECTION CHECKS THAT THE S4M NUMBER IS 8 DIGITS AND CONTAINS ONLY NUMBERS
			if the number of characters of theS4MNumber is equal to 8 then
				try
					set theS4MCalc to (theS4MNumber + 2)
				on error
					set InvalidS4MNumber to 1
				end try
			else
				set InvalidS4MNumber to 1
			end if
			if the number of characters of S4MNumberCheck is not equal to 8 then
				set InvalidS4MNumber to 1
			end if
			
			--THIS SECTION CHECKS TO ENSURE THE CODEC AND BIT RATE ARE CORRECT
			if PromoCodec is not in theRightFormats and PromoBitRate is not in theRightFormats then
				set CodecError to 1
			else
				set CodecError to 0
			end if
		end if
		
		--THIS SECTION CHECKS ALL THE ERROR COUNTERS, LABELS THE FILES IN FINDER, CREATES THE ERROR LIST, AND IF THE FILE PASSES ALL CHECKS IT WILL PASTE THE FILE INTO THE DESIRED DESTINATION 	
		if PromoError is equal to 0 then
			tell application "Finder"
				if CodecError is not equal to 0 then -- CODEC ERROR CHECK
					set label index of thePromo to 2
					set TotalCodecErrors to TotalCodecErrors + 1
					set FilesWithCodecErrors to FilesWithCodecErrors & theName & "" & " 	• codec is " & PromoCodec & "
				"
					set CodecError to 0
				else
					if InvalidS4MNumber is not equal to 0 then -- BAD S4M NUMBER FORMAT IN FILENAME
						set label index of thePromo to 4
						set FilesWithS4MNumberErrors to FilesWithS4MNumberErrors & theName & "
					"
						set TotalS4MNumberErrors to TotalS4MNumberErrors + 1
						set InvalidS4MNumber to 0
					else
						if DurationError is not equal to 0 then -- PROMO IS NOT WITHIN THE 2 FRAME BUFFER FOR DURATION
							set label index of thePromo to 7
							set TotalDurationErrors to TotalDurationErrors + 1
							set FilesWithDurationErrors to FilesWithDurationErrors & theName & "
						"
							set DurationError to 0
						else
							if InvalidDuration is not equal to 0 then -- BAD DURATION FORMAT IN FILENAME
								set label index of thePromo to 3
								set TotalFileNameErrors to TotalFileNameErrors + 1
								set FilesWithFileNameErrors to FilesWithFileNameErrors & theName & "
					" & " 	• length is " & (round (Duration / 30)) & " seconds
					"
								set InvalidDuration to 0
							else
								set label index of thePromo to 6
								do shell script "cp " & theOldpath & " " & theNewPath --THIS IS THE STEP THAT ACTUALLY COPIES THE FILE TO THE NEW LOCATION
							end if
						end if
					end if
				end if
			end tell
			set PromoError to 0
		end if
		if PromoError is not equal to 0 then
			tell application "Finder"
				set label index of thePromo to 5
				set TotalPromoError to TotalPromoError + 1
				set FilesNotProcessed to FilesNotProcessed & (name of (info for thePromo)) & "
				"
			end tell
		end if
	end repeat -- END OF INDIVIDUAL FILE CHECK REPEAT LOOP
	
	--THIS IS WHERE THE BATCH ERROR MESSAGES BEGIN
	
	tell application "Finder"
		if FilesWithCodecErrors is not equal to "" then
			display dialog "..." & TotalCodecErrors & " file(s) are not the proper codec...
" & FilesWithCodecErrors & "
(Label colour: red)" buttons "Thanks"
		end if
		if FilesWithS4MNumberErrors is not equal to "" then
			display dialog "..." & TotalS4MNumberErrors & " file(s) do not have a proper S4M number...
	" & FilesWithS4MNumberErrors & "(Label colour: blue)" buttons "Thanks"
		end if
		if FilesWithDurationErrors is not equal to "" then
			display dialog "..." & TotalDurationErrors & " file(s) were not the proper duration...
	" & FilesWithDurationErrors & "(Label colour: yellow)" buttons "Thanks"
		end if
		if FilesWithFileNameErrors is not equal to "" then
			display dialog "..." & TotalFileNameErrors & " file(s) had incorrect durations in their file name(s).
	" & FilesWithFileNameErrors & "(Label colour: purple)" buttons "Thanks"
		end if
		if FilesNotProcessed is not equal to "" then
			display dialog "..." & TotalPromoError & " file(s) were not properly processed.
		" & FilesNotProcessed & "(Label colour: orange)" buttons "Thanks"
		end if
		if FilesWithCodecErrors is equal to "" and FilesWithS4MNumberErrors is equal to "" and FilesWithDurationErrors is equal to "" and FilesWithFileNameErrors is equal to "" and FilesNotProcessed is equal to "" then
			display dialog "All OK!" & theName & "
		(Label colour: green)" buttons "Thanks"
		end if
	end tell
end common

--THIS HANDLER READS THE XML DATA:
on trackInfo given type:type as text, id:|id| as text : -1, key:key as text
	local key, |id|, type
	global tracks
	
	tell application "System Events"
		if |id| = -1 then
			set {trackdata} to the |tracks| where ¬
				value of the XML attribute "type" = |type|
		else
			set {trackdata} to the |tracks| where ¬
				value of the XML attribute "type" = |type| and ¬
				value of the XML attribute "streamid" = |id|
		end if
		
		tell (a reference to XML element named key in the trackdata) to ¬
			if it exists then
				return its value
			else
				return false
			end if
	end tell
end trackInfo

--THIS HANDLER GENERATES THE XML DATA
on mediainfoFile(inputstring) -- Only call this once per script run
	set theFile to quoted form of POSIX path of (inputstring)
	set xmltext to do shell script "usr/local/bin/mediainfo " & ¬
		theFile & " --Output=XML"
	
	tell application "System Events"
		set xml to make new XML data with properties {text:xmltext}
		set mediaInfo to XML element "Mediainfo" of xml
		set |file| to XML element "File" of mediaInfo
		
		return {|tracks|:a reference to XML elements of |file|}
	end tell
end mediainfoFile

--THIS HANDLER EXTRACTS NUMBERS FROM A STRING
on returnNumbersInString(inputstring)
	set s to quoted form of inputstring
	do shell script "sed s/[a-zA-Z\\']//g <<< " & s
	set dx to the result
	set numlist to {}
	repeat with i from 1 to count of words in dx
		set this_item to word i of dx
		try
			set this_item to this_item as number
			set the end of numlist to this_item
		end try
	end repeat
	return numlist
end returnNumbersInString

--THIS HANDLER SEARCHES A STRING FOR SPECIFIED CHARACTERS AND REPLACES THEM WITH THE DESIGNATED CHARACTERS
on SAR(main_text, search_text, replace_text)
	set old_delims to AppleScript's text item delimiters
	try
		set AppleScript's text item delimiters to search_text
		considering case
			set parts to every text item of main_text
		end considering
		set AppleScript's text item delimiters to replace_text
		set newText to (parts as string)
	end try
	set AppleScript's text item delimiters to old_delims
	return newText
end SAR

Saved as an application, it may be used as an applet - entry point by on run or as a droplet - entry point by on open.

To be sure that everything was OK, I tried to use it from the script editor which uses the entry : on run.
Alas I got an error which I don’t understand.

Here is the event log:

tell application "Script Editor"
	choose file with multiple selections allowed
		--> {alias "SSD 500:Users:**********:Desktop:theXML 1.xml", alias "SSD 500:Users:**********:Desktop:theXML 2.xml"}
end tell
tell current application
	do shell script "usr/local/bin/mediainfo '/Users/**********/Desktop/theXML 1.xml' --Output=XML"
		--> "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<MediaInfo
    xmlns=\"https://mediaarea.net/mediainfo\"
    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
    xsi:schemaLocation=\"https://mediaarea.net/mediainfo https://mediaarea.net/mediainfo/mediainfo_2_0.xsd\"
    version=\"2.0\">
<creatingLibrary version=\"19.04\" url=\"https://mediaarea.net/MediaInfo\">MediaInfoLib</creatingLibrary>
<media ref=\"/Users/**********/Desktop/theXML 1.xml\">
<track type=\"General\">
<FileExtension>xml</FileExtension>
<FileSize>3034</FileSize>
<StreamSize>3034</StreamSize>
<File_Modified_Date>UTC 2019-04-27 09:16:59</File_Modified_Date>
<File_Modified_Date_Local>2019-04-27 11:16:59</File_Modified_Date_Local>
</track>
</media>
</MediaInfo>
"
end tell
tell application "System Events"
	make new XML data with properties {text:"<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<MediaInfo
    xmlns=\"https://mediaarea.net/mediainfo\"
    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
    xsi:schemaLocation=\"https://mediaarea.net/mediainfo https://mediaarea.net/mediainfo/mediainfo_2_0.xsd\"
    version=\"2.0\">
<creatingLibrary version=\"19.04\" url=\"https://mediaarea.net/MediaInfo\">MediaInfoLib</creatingLibrary>
<media ref=\"/Users/**********/Desktop/theXML 1.xml\">
<track type=\"General\">
<FileExtension>xml</FileExtension>
<FileSize>3034</FileSize>
<StreamSize>3034</StreamSize>
<File_Modified_Date>UTC 2019-04-27 09:16:59</File_Modified_Date>
<File_Modified_Date_Local>2019-04-27 11:16:59</File_Modified_Date_Local>
</track>
</media>
</MediaInfo>
"}
		--> XML data id "sans titre 1"
	get XML element "Mediainfo" of XML data id "sans titre 1"
		--> error number -1728 from XML element "Mediainfo" of XML data id "sans titre 1"
Résultat :
error "Erreur dans System Events : Il est impossible d’obtenir XML element \"Mediainfo\" of XML data id \"sans titre 1\"." number -1728 from XML element "Mediainfo" of XML data id "sans titre 1"

The content of the passed xml file is :

<?xml version="1.0" encoding="UTF-8"?> /Users/jquimby/Desktop/test.mxf MXF XDCAM HD422 OP-1a Closed / Complete 31.0 MiB 5s 5ms 52.0 Mbps 2019-04-03 15:32:46.000 Adobe Systems Incorporated Adobe Media Encoder 1.0.0.0.1 Adobe Systems Incorporated Adobe Media Encoder 1.0.0.0.1 512 MPEG Video XDCAM HD422 Version 2 4:2:2@High Yes Custom M=3, N=15 Frame 5s 5ms 50.0 Mbps 1 920 pixels 1 080 pixels 16:9 29.970 fps Component YUV 4:2:2 8 bits Interlaced Top Field First Lossy 0.805 29.8 MiB (96%) 0 BT.709 BT.709 768 PCM Little Frame (AES) 5s 5ms Constant 1 152 Kbps 1 channel 48.0 KHz 24 bits 704 KiB (2%) 0 1024 PCM Little Frame (AES) 5s 5ms Constant 1 152 Kbps 1 channel 48.0 KHz 24 bits 704 KiB (2%) 0 1280-CC1 EIA-608 Ancillary data / CDP 5s 5ms Constant 0.00 Byte (0%) 0

The Unix file mediainfo is decribed as:

Type: Exécutable Unix
Taille: 13 936176 octets (13,9 Mo sur disque)
Emplacement: SSD 500 - usr - local - bin
Créé: mardi 23 avril 2019 à 16:06
Modifié: mardi 23 avril 2019 à 16:06

What is the wrongdoer ?

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) mardi 14 mai 2019 21:34:02

The two XMLs are completely different. You’re taking XML that was previously produced as output from that shell script program, and which you now have saved in a file on your desktop; and you’re trying to run that file back through the same shell script again, which produces completely different XML that isn’t suitable for this script.

JQ is sourcing his files from some other place, and he needs to run them through the shell script in order to produce the XML he requires. You and I already have that XML, which JQ provided at the start. Therefore, you should comment out the first three lines of the mediainfoFile() handler, and declare xmltext like this:

set xmltext to read the inputstring

OK, so this is an issue of variable scope that I mentioned in one of my previous replies when I brought up the notion of global variables. I may have also mentioned something about an implicit run handler (or, rather, referred to the run handler and put the word “implicitly” in brackets somewhere in the sentence).

Anyway, before I go on, I’ll just tell you the solution first, then the explanation can follow. Keep your script as you have it (no need to declare an explicit run handler); keep your open handler; at the top of the script, add the line:

global tracks

ExplanationThe run handler: Implicit vs. Explicit
Every set of AppleScript commands is contained within a handler, including the ones that don’t appear to be so, because they are sitting outside of all the other handler declarations and appear to be unconfined. Those are the commands that AppleScript executes by default, without needing to call upon a handler yourself, and I previously referred to those lines of code as “the main” part of the script (a misnomer). In fact, they are contained inside a run handler, even though this can be very unapparent to a layman reading the script in those instances we choose not to declare the run handler explicitly:[format]tell application “Finder” to activate

(* more code *)

on myHandler()

    (* some code *)

end myHandler
.
.
.
(* other user-defined handlers )[/format]Here, though the declaration of the run handler cannot be seen, any command not put inside another handler is, by default, part of the run handler. It is said to be declared implicitly, and thus referred to as the implicit run handler (its existence is implied, even if not seen). Adding in the handler declaration:[format]on run
tell application “Finder” to stop being so slow
.
.
(
more code *)
.
.
end run

on myHandler()

    (* some code *)

end myHandler
.
.
.
(* other user-defined handlers *)[/format]now makes the run handler explicit. If you were to try and declare your run handler explicitly, then put command expressions outside of it (and not contained inside other handlers), the script would fail to compile (you can, however, declare properties and uninitialised variables outside the run handler, but variables always get initialised within a handler).

Variable Scope
As I mentioned before, variables exist and are bound inside the scope (I previously also referred to this as the domain) of the handler in which they are declared. One handler does not ordinarily have access to another handler’s variables. You can grant a handler access to variables in the run handler’s domain (also called the top-level of the script object) by declaring a global instance of it inside the handler that wants access (another misnomer, as it remains the same instance of the variable, and it’s the handler that gains access to the domain in which the variable lives). This does not make the variable global in the AppleScript domain (i.e. in the scope of the script as a whole), and the other user-defined handlers won’t have access to it unless they also declare a global instance of it themselves.

This is what the situation was for you and I when we were testing the script inside Script Editor where the “main” part of the script was living inside an implicit run handler, which is where the variable tracks lived.

When the changes were made to create an Application script, the lines of code previously existing in the run handler were wrapped inside the open handler, and this meant the tracks variable got bound within the local scope of the open handler and inaccessible to other handlers regardless of attempts to access the global variable domain.

The solution is to declare the tracks variable as global in the AppleScript domain, i.e. outside all handlers, including the run handler. Now every handler in the script has access to this variable and can change its value. They don’t need to contain an explicit global declaration themselves, although I tend to add one inside any handler that utilises the variable as a way of keeping track of scopes that overlap and which parts of the script are making changes to it. It’s also why I always have explicit declarations for my local variables inside a handler; this isn’t necessary, but it helps make it clear and obvious when a local instance of a variable overrides any previous global declaration of a variable using the same identifier.

But, as a general rule, don’t declare global variables. As this lesson has taught us with just a single global variable, it’s easy to lose track of where they are and who’s doing what to them. The safer way to pass a value from one domain to another, e.g. from the top-level script object to one of its handlers, is, where possible (which it almost always is), to declare a handler that takes arguments and passing it the value of the variable that’s needed.

Lastly, I’m going to pick apart your try blocks again. Ultimately, it is your decision, but I think you’re having a tough time seeing how genuinely unnecessary they are in your script, and only causing trouble, as is evident by how it obscured what was happening with the PromoCodec and tracks variables until you physically removed the try statement:

“THIS TRY BLOCK CHECKS THE CODEC FIELD OF THE XML TO MAKE SURE THE PROPER CODEC FIELD Commercial_Name IS PRESENT”

If this were true, you wouldn’t need the two if…then conditional blocks checking to determine whether PromoCodec is set to false (which would indicate the Commercial_Name field was absent) and choosing whether to execute the subsequent lines. You could simply remove those conditional statements, let the error get caught, which would skip the lines of code inside the rest of the try block and continue executing what comes after.

But that is not the way to do it. Rather, get rid of the try block, and use a single conditional statement that will cater for both Commerical_Name’s presence or absence:

set PromoCodec to (trackInfo given type:"Video", key:"Commercial_name")
if PromoCodec ≠ false then
		--IF THE PROPER CODEC IS PRESENT THIS IS WHERE THE VARIABLES ARE POPULATED BY THE MEDIAINFOFILE HANDLER		
		set PromoBitRate to (trackInfo given type:"Video", key:"Bit_rate")
		set PromoDuration to (trackInfo given type:"Audio", id:2, key:"Duration")
		set PromoFrameRate to (trackInfo given type:"Video", key:"Frame_rate")
		set theDuration to returnNumbersInString(PromoDuration)
		set Duration to SAR(theDuration, ", ", ".")
		set FileName to do shell script "basename " & quoted form of POSIX path of thePromo
		set S4MDuration to the first word of FileName
end if

Thank you everyone for your incredible help and patience. I’m now able to run the script as an application. I would not have been able to do this without all of your help as this kind of script is way beyond my scope as a script writer.

CK - One question about your note about Try blocks. The original script was using them to catalog errors and mark files with a flag depending on the issue with the file. The script will be used to process sometimes as many as 100 files at a time and we use the Try blocks/Error counters to identify any technical issues with an individual file inside the batch being processed. I see the logic with the alteration of the PromoCodec try block, but I would need to keep the if statements in for the error counters.

Would altering/removing the Try blocks make the script more efficient (ie. run faster)?

Here is the final script application (that still includes the Try blocks):


on open theseFiles
	global tracks
	
	-- THESE ARE THE ERROR VARIABLES
	set CodecError to 0 --Codec Errors will highlight the file GRAY
	set DurationError to 0 --Duration Errors will highlight the file YELLOW
	set InvalidDuration to 0
	set InvalidS4MNumber to 0
	set TotalCodecErrors to 0 -- COUNTS CODEC ERRORS
	set TotalDurationErrors to 0 -- COUNTS PROMO DURATION ERRORS
	set TotalS4MNumberErrors to 0 -- COUNTS BAD S4M NUMBERS IN FILENAMES
	set TotalFileNameErrors to 0 -- COUNTS DURATION ERRORS OF TOP OF FILENAMES
	set TotalPromoError to 0 -- RESULTS IN "FILE NOT PROPERLY PROCESSED"
	set FilesWithCodecErrors to "" -- CREATES A LIST OF THE PROMOS THAT HAVE CODEC ERRORS
	set FilesWithDurationErrors to "" -- CREATES A LIST OF THE PROMOS THAT HAVE DURATION ERRORS
	set FilesWithFileNameErrors to "" -- CREATES A LIST OF THE PROMOS THAT HAVE FILENAME ERRORS
	set FilesWithS4MNumberErrors to "" -- CREATES A LIST OF THE PROMOS THAT HAVE S4M NUMBER ERRORS
	set FilesNotProcessed to "" -- CREATES A LIST OF PROMOS THAT WERE NOT PROCESSED
	set theRightFormats to {"XDCAM HD422", "50.0 Mbps", "29.970 fps"} as list
	
	repeat with i from 1 to count of theseFiles -- STARTS CHECKING FILES IN SEQUENCE
		set thePromo to item i of theseFiles
		set tracks to the mediainfoFile(thePromo)'s tracks
		
		--WHEN MEDIAINFO READS AN MXF WITH XDCAM HD422 AS THE CODEC THE FIELD IS LABELLED
		--"Commercial_Name". THIS TRY BLOCK CHECKS THE CODEC FIELD OF THE XML
		--TO MAKE SURE THE PROPER CODEC FIELD IS PRESENT
		try
			set PromoCodec to (trackInfo given type:"Video", key:"Commercial_name")
			if the PromoCodec = false then
				set CodecError to 1
			end if
			
			--IF THE PROPER CODEC IS PRESENT THIS IS WHERE THE VARIABLES ARE POPULATED BY THE MEDIAINFOFILE HANDLER
			if CodecError is equal to 0 then
				set PromoBitRate to (trackInfo given type:"Video", key:"Bit_rate")
				set PromoDuration to (trackInfo given type:"Audio", id:2, key:"Duration")
				set PromoFrameRate to (trackInfo given type:"Video", key:"Frame_rate")
				set theDuration to returnNumbersInString(PromoDuration)
				set Duration to SAR(theDuration, ", ", ".")
				set FileName to do shell script "basename " & quoted form of POSIX path of thePromo
				set S4MDuration to the first word of FileName
			end if
		end try
		
		--THIS SECTION IS WHERE THE TRUNCATED FILE NAME IS CREATED
		try
			tell application "Finder"
				set extension hidden of thePromo to false
			end tell
			
			set theName to name of (info for thePromo)
			set thePath to the POSIX path of thePromo
			
			set n to the number of characters in theName
			
			set n to (n - 11)
			
			set JustS4MNumber to (characters n through end of theName) as string
			
			set theNewPath to quoted form of ("/Volumes/Post_SAN_02/Post_SAN_02/GLOBAL/Producers/Jason/Troubleshooting/RunwayTest/" & JustS4MNumber)
			--THE ABOVE LINE IS WHERE THE FILE WILL BE POSTED IF IT PASSES ALL TECH CHECKS
			
			
			set theOldpath to quoted form of thePath
			set PromoError to 0
			
		on error
			set PromoError to 1
		end try
		
		--THIS IS THE BEGINNING OF THE TECH CHECKS
		if PromoError is equal to 0 and CodecError is equal to 0 then
			set theS4MNumber to the word -2 of theName --word -2 removes the file extension
			set S4MNumberCheck to the first word of JustS4MNumber
			
			--THIS SECTION CHECKS THAT THE FIRST WORD OF THE FILE NAME IS ACTUALLY A VALID NUMBER
			try
				set DurationCheck to (S4MDuration + 2)
			on error
				set InvalidDuration to 1
			end try
			
			--THIS SECTION ENSURES THE PROMO DURATION IS WITHIN A 2 FRAME RANGE OF THE TARGET DURATION
			if InvalidDuration is equal to 0 then
				set FramesHeavy to (S4MDuration + 0.66)
				set FramesLight to (S4MDuration - 0.66)
				if Duration is greater than FramesLight and Duration is less than FramesHeavy then
					set DurationError to 0
				else
					set DurationError to 1
				end if
			end if
			
			--THIS SECTION CHECKS THAT THE S4M NUMBER IS 8 DIGITS AND CONTAINS ONLY NUMBERS
			if the number of characters of theS4MNumber is equal to 8 then
				try
					set theS4MCalc to (theS4MNumber + 2)
				on error
					set InvalidS4MNumber to 1
				end try
			else
				set InvalidS4MNumber to 1
			end if
			if the number of characters of S4MNumberCheck is not equal to 8 then
				set InvalidS4MNumber to 1
			end if
			
			--THIS SECTION CHECKS TO ENSURE THE CODEC AND BIT RATE ARE CORRECT
			if PromoCodec is not in theRightFormats and PromoBitRate is not in theRightFormats then
				set CodecError to 1
			else
				set CodecError to 0
			end if
		end if
		
		--THIS SECTION CHECKS ALL THE ERROR COUNTERS, LABELS THE FILES IN FINDER, CREATES THE ERROR LIST, AND IF THE FILE PASSES ALL CHECKS IT WILL PASTE THE FILE INTO THE DESIRED DESTINATION 	
		if PromoError is equal to 0 then
			tell application "Finder"
				if CodecError is not equal to 0 then -- CODEC ERROR CHECK
					set label index of thePromo to 2
					set TotalCodecErrors to TotalCodecErrors + 1
					set FilesWithCodecErrors to FilesWithCodecErrors & theName & "" & " 	• codec is " & PromoCodec & return
					set CodecError to 0
				else
					if InvalidS4MNumber is not equal to 0 then -- BAD S4M NUMBER FORMAT IN FILENAME
						set label index of thePromo to 4
						set FilesWithS4MNumberErrors to FilesWithS4MNumberErrors & theName & return
						set TotalS4MNumberErrors to TotalS4MNumberErrors + 1
						set InvalidS4MNumber to 0
					else
						if DurationError is not equal to 0 then -- PROMO IS NOT WITHIN THE 2 FRAME BUFFER FOR DURATION
							set label index of thePromo to 3
							set TotalDurationErrors to TotalDurationErrors + 1
							set FilesWithDurationErrors to FilesWithDurationErrors & theName & return
							set DurationError to 0
						else
							if InvalidDuration is not equal to 0 then -- BAD DURATION FORMAT IN FILENAME
								set label index of thePromo to 6
								set TotalFileNameErrors to TotalFileNameErrors + 1
								set FilesWithFileNameErrors to FilesWithFileNameErrors & theName & return
								set InvalidDuration to 0
							else
								set label index of thePromo to 6
								do shell script "cp " & theOldpath & " " & theNewPath --THIS IS THE STEP THAT ACTUALLY COPIES THE FILE TO THE NEW LOCATION
							end if
						end if
					end if
				end if
			end tell
			set PromoError to 0
		end if
		if PromoError is not equal to 0 then
			tell application "Finder"
				set label index of thePromo to 5
				set TotalPromoError to TotalPromoError + 1
				set FilesNotProcessed to FilesNotProcessed & (name of (info for thePromo)) & "
				"
			end tell
		end if
	end repeat -- END OF INDIVIDUAL FILE CHECK REPEAT LOOP
	
	
	--THIS IS WHERE THE BATCH ERROR MESSAGES BEGIN
	
	tell application "Finder"
		if FilesWithCodecErrors is not equal to "" then
			display dialog ("..." & TotalCodecErrors & " file(s) are not the proper codec..." & return & return & FilesWithCodecErrors as text) & return & "(Label colour: red)" buttons "Thanks"
		end if
		if FilesWithS4MNumberErrors is not equal to "" then
			display dialog ("..." & TotalS4MNumberErrors & " file(s) do not have a proper S4M number..." & return & return & FilesWithS4MNumberErrors as text) & return & "(Label colour: blue)" buttons "Thanks"
		end if
		if FilesWithDurationErrors is not equal to "" then
			display dialog ("..." & TotalDurationErrors & " file(s) were not the proper duration..." & return & return & FilesWithDurationErrors as text) & return & "(Label colour: yellow)" buttons "Thanks"
		end if
		if FilesWithFileNameErrors is not equal to "" then
			display dialog ("..." & TotalFileNameErrors & " file(s) had incorrect durations in their file name(s)." & return & return & FilesWithFileNameErrors as text) & return & "(Label colour: purple)" buttons "Thanks"
		end if
		if FilesNotProcessed is not equal to "" then
			display dialog ("..." & TotalPromoError & " file(s) were not properly processed." & return & return & FilesNotProcessed as text) & return & "(Label colour: orange)" buttons "Thanks"
		end if
		if FilesWithCodecErrors is equal to "" and FilesWithS4MNumberErrors is equal to "" and FilesWithDurationErrors is equal to "" and FilesWithFileNameErrors is equal to "" and FilesNotProcessed is equal to "" then
			display dialog ("All OK!" & return & return & theName as text) & "(Label colour: green)" buttons "Thanks"
		end if
	end tell
end open

--THIS HANDLER READS THE XML DATA:
on trackInfo given type:type as text, id:|id| as text : -1, key:key as text
	local key, |id|, type
	global tracks
	
	tell application "System Events"
		if |id| = -1 then
			set {trackdata} to the |tracks| where ¬
				value of the XML attribute "type" = |type|
		else
			set {trackdata} to the |tracks| where ¬
				value of the XML attribute "type" = |type| and ¬
				value of the XML attribute "streamid" = |id|
		end if
		
		tell (a reference to XML element named key in the trackdata) to ¬
			if it exists then
				return its value
			else
				return false
			end if
	end tell
end trackInfo

--THIS HANDLER GENERATES THE XML DATA
on mediainfoFile(inputstring) -- Only call this once per script run
	set theFile to quoted form of POSIX path of (inputstring)
	set xmltext to do shell script "usr/local/bin/mediainfo " & ¬
		theFile & " --Output=XML"
	
	tell application "System Events"
		set xml to make new XML data with properties {text:xmltext}
		set mediaInfo to XML element "Mediainfo" of xml
		set |file| to XML element "File" of mediaInfo
		
		return {|tracks|:a reference to XML elements of |file|}
	end tell
end mediainfoFile

--THIS HANDLER EXTRACTS NUMBERS FROM A STRING
on returnNumbersInString(inputstring)
	set s to quoted form of inputstring
	do shell script "sed s/[a-zA-Z\\']//g <<< " & s
	set dx to the result
	set numlist to {}
	repeat with i from 1 to count of words in dx
		set this_item to word i of dx
		try
			set this_item to this_item as number
			set the end of numlist to this_item
		end try
	end repeat
	return numlist
end returnNumbersInString

--THIS HANDLER SEARCHES A STRING FOR SPECIFIED CHARACTERS AND REPLACES THEM WITH THE DESIGNATED CHARACTERS
on SAR(main_text, search_text, replace_text)
	set old_delims to AppleScript's text item delimiters
	try
		set AppleScript's text item delimiters to search_text
		considering case
			set parts to every text item of main_text
		end considering
		set AppleScript's text item delimiters to replace_text
		set newText to (parts as string)
	end try
	set AppleScript's text item delimiters to old_delims
	return newText
end SAR

One more question. I want to add a line that would modify the file name of all files that passed the through all the error checks. I want to add a date stamp in the format of mmmdd and add it before the last word of the original file name. This is the script I wrote to test creating/inserting the date stamp:


set theFile to (choose file)
set theFilename to name of (info for theFile)
set TodaysDate to (current date) as string
set TruncatedDate to word 2 of TodaysDate & word 3 of TodaysDate
set NewFilename to SAR(theFilename, (word -2 of theFilename), TruncatedDate & " " & (word -2 of the theFilename))
tell application "Finder" to set name of theFile to NewFilename

on SAR(main_text, search_text, replace_text)
	set old_delims to AppleScript's text item delimiters
	try
		set AppleScript's text item delimiters to search_text
		considering case
			set parts to every text item of main_text
		end considering
		set AppleScript's text item delimiters to replace_text
		set newText to (parts as string)
	end try
	set AppleScript's text item delimiters to old_delims
	return newText
end SAR

The modifications I’ve made to the larger script are as follows:


on open theseFiles
	global tracks
	set TodaysDate to (current date) as string --NEW LINE
	set TruncatedDate to word 2 of TodaysDate & word 3 of TodaysDate --NEW LINE
	
	-- THESE ARE THE ERROR VARIABLES	


set theName to name of (info for thePromo)
			set thePath to the POSIX path of thePromo
			
			set n to the number of characters in theName
			
			set n to (n - 11)
			
			set JustS4MNumber to (characters n through end of theName) as string
			
			set theNewPath to quoted form of ("/Volumes/Post_SAN_02/Post_SAN_02/GLOBAL/Producers/Jason/Troubleshooting/RunwayTest/" & JustS4MNumber)
			--THE ABOVE LINE IS WHERE THE FILE WILL BE POSTED IF IT PASSES ALL TECH CHECKS
			
			set NewFilename to SAR(theName, (word -2 of theName), TruncatedDate & " " & (word -2 of the theName)) -- NEW LINE TO CREATE DESIRED NEW FILE NAME
			
			set theOldpath to quoted form of thePath
			set PromoError to 0

and lastly:


if PromoError is equal to 0 then
			tell application "Finder"
				if CodecError is not equal to 0 then -- CODEC ERROR CHECK
					set label index of thePromo to 2
					set TotalCodecErrors to TotalCodecErrors + 1
					set FilesWithCodecErrors to FilesWithCodecErrors & theName & "" & " 	• codec is " & PromoCodec & return
					set CodecError to 0
				else
					if InvalidS4MNumber is not equal to 0 then -- BAD S4M NUMBER FORMAT IN FILENAME
						set label index of thePromo to 4
						set FilesWithS4MNumberErrors to FilesWithS4MNumberErrors & theName & return
						set TotalS4MNumberErrors to TotalS4MNumberErrors + 1
						set InvalidS4MNumber to 0
					else
						if DurationError is not equal to 0 then -- PROMO IS NOT WITHIN THE 2 FRAME BUFFER FOR DURATION
							set label index of thePromo to 3
							set TotalDurationErrors to TotalDurationErrors + 1
							set FilesWithDurationErrors to FilesWithDurationErrors & theName & return
							set DurationError to 0
						else
							if InvalidDuration is not equal to 0 then -- BAD DURATION FORMAT IN FILENAME
								set label index of thePromo to 5
								set TotalFileNameErrors to TotalFileNameErrors + 1
								set FilesWithFileNameErrors to FilesWithFileNameErrors & theName & return
								set InvalidDuration to 0
							else
								set label index of thePromo to 6
								set TotalDeliveredFiles to TotalDeliveredFiles + 1
								set DeliveredFiles to DeliveredFiles & theName & return
								set name of theName to NewFilename -- NEW LINE TO RENAME FILE THAT HAS PASSED TECH CHECKS
								do shell script "cp " & theOldpath & " " & theNewPath --THIS IS THE STEP THAT ACTUALLY COPIES THE FILE TO THE NEW LOCATION
							end if
						end if
					end if
				end if
			end tell
			set PromoError to 0
		end if

But I get this error once I try to tell the Finder to rename the file:

Can’t set name of “30 911 AN MON 00773484.mxf” to “30 911 AN MON May15 00773484.mxf”. (-10006)

My test script changes the file name with no issue. Once I add the pieces into the larger script though I get a Finder error. As far as I know, where I’ve put the line to rename the file should not cause a conflict with the other instances of calling theName as all those steps have been completed.