List of properties of list items in Applescript - applescript

I'm getting a list of files in applescript like so:
set _resourcesFolder to folder (((path to me) as string) & "Contents:Resources:")
set _signatureFiles to files of _resourcesFolder whose name extension is in {"html", "webarchive"}
Then I want to get the properties these items in separate lists. Tried it like so:
set _signatureNames to displayed name of _signatureFiles
set _signatureDate to modification date of _signatureFiles
This doesn't work. But this does:
set _signatureNames to displayed name of files of _resourcesFolder whose name extension is in {"html", "webarchive"}
set _signatureDate to modification date of files of _resourcesFolder whose name extension is in {"html", "webarchive"}
Why so?

In your first snippet, you define two lists: _resourcesFolder and _signatureFiles
In your second snippet, your code is asking for the displayed name and the modification date of one of those lists. This fails because you are addressing the list, not the items in the list.
In your third snippet, you correctly address the items individually, and all is swell.
The only other method available (based on your original snippet) is to repeat through the files in _signatureFiles and create the lists or records as part of the repeat. Your code in the third snippet is the only way to do it in a single command.

Related

Can Mac's Automator scan a folders contents & lists the files that are over a certain length?

I work in media production at a university, we work on Mac systems, but our servers are windows based.
Illegal characters & long file names are causing us problems when transferring our production files to the server.
To prevent file transfers failing & being sent to a holding pen in our DAM system i'm looking to create a simple Automator App that can be used by the production team to do the following;
Accept source folder as input for the app.
Scan contents & replace the following characters ()\/[]"*?<>|+ with an underscore.
Scan contents & for file names longer than 100 characters
Log / report on the affected files for our producers to amend.
Within Automator I have had success with replacing the illegal characters using a find & replace rule for each, but I'm not sure of the apple script that would be required to check the file name lengths & reporting all changes.
I'll be eternally grateful if anyone would be able to suggest a route forwards!
Obviously, I have no clue what you might be passing along, nor how you might be replacing the text in filenames, nor exactly what you would like to report, as you don't really provide any of those details. However, here is a straightforward way to test for filenames longer than a given length within automator.
To provide the initial file list to test, I begin with three actions:
Get Selected Finder Items
Get Folder Contents ('repeat for each subfolder found' is checked)
Filter Finder Items ('kind is document')
This will pass along a list of alias file objects to the fourth 'run applescript' action, as input.
on run {input, parameters}
set fList to input
set nList to {} -- becomes list of filenames
set cList to {} -- becomes list of filename lengths
tell application "Finder"
repeat with ff in fList -- list of file aliases
set nn to name of ff
set end of nList to nn
set end of cList to length of nn
end repeat
end tell
set longList to {}
repeat with cc from 1 to length of cList
if item cc of cList is greater than 100 then
set end of longList to item cc of nList -- names with more than 100 characters
end if
end repeat
return longList
end run
This should be run when a folder is selected in the Finder.
Essentially, what this does is take the input (i.e. list of file aliases) and create corresponding lists of filenames and filename lengths. The script then loops through the list of lengths looking for items > 100 and and returns a list of matching filenames. If instead, you set end of longList… to items from fList then it will return a list of file aliases.
If this isn't what you're looking for, please advise. The above works under Sierra.

How do I rename and move a file downloaded to 'Downloads" using Automator, with or without Applescript, Shell Script or Javascript?

I am a newbie to programming and therefore please excuse my lack of knowledge. I have trawled the site and the internet but have not found an answer to what seems like a simple problem.
I would like to automate the filing and renaming of some personal and business documents - they are bank statements so the numbers are anonymised. I am interested in understanding the code so I can adapt it after too, for further actions (and maybe for others to use).
The documents are downloaded into the (mac) downloads folder. Typically they have this name: "Statement--12345678--98765432--1-06-2020-30-06-2020.pdf" The two sets of numbers at the beginning are not these generic ones but there are 8 figures (though the first number sometimes is not listed as it is a "0"). The second set of two numbers refers to two dates, in day--month--year format. Sometimes the first date starts on the last day of the previous month!
As a newbie I started with Automator - using a Folder Action to move the individual files to a named folder (by year). I then wanted to rename them so that the second date comes first in the name in YYYYMMDD format, so that they will automatically be listed in date order in the year folder. The full name would become "YYYYMMDD 98765432 Month YY".
I can move the files and automatically (thanks to automator); I can even add the current date at the beginning of the name in the right format (but it will be the current date not the date in the file). But I cannot do what I really want: change the name based on the date in the filename.
I then looked at AppleScript. The answers below solve the naming problem - THANK YOU!
But when I try to pick up a bunch of files - there are 25 of them (happily found and moved by Automator (Find files and Move files) the output is not recognised as an input into AppleScript. I get "Can't get files XXXX as alias" or if I try to create a variable, that is not defined (though I have tried numerous times... as {}, as "", as item 1 of input).
I do apologise if this is not clear, but I am trying my best to explain it, and do not understand terms such as 'terminal ls'.
Any help, advice and commentary gratefully received. I really do want to try to understand the code so I can apply the learning! Thank you,
John
Okay, your problem is to extract multiple parts of the name.
The trick is to explode it into small parts. GREP is a good tool, but tricky with applescript "out of the box".
I use a subroutine called "textSplit" to do the job. Once every part of the filename is available in variables, you should be able to build any file or folder name...
Here's my way to solve this :
set thisFileName to "Document--12345678--98765432--1-06-2020-30-06-2020.pdf"
-- first we split the name using the "--" separator
set mainParts to textSplit(thisFileName, "--")
-- we now copy the result to variables to handle it
copy mainParts to {prefixOne, numberOne, numberTwo, theTwoDates}
--> prefixOne = "Document"
--> numberOne = "12345678"
--> numberTwo = "98765432"
--> theTwoDates = "1-06-2020-30-06-2020.pdf"
-- get rid of the extension
set theDatesWithoutExtension to first item of textSplit(theTwoDates, ".")
-- split the dates
set splitDates to textSplit(theDatesWithoutExtension, "-")
-- copy result into nice variables
copy splitDates to {dayOne, monthOne, yearOne, dayTwo, monthTwo, yearTwo}
-- and then build the filename with whatever you want
set myNewFileName to yearOne & monthOne & dayOne & space & numberTwo & space & monthTwo & "-" & yearTwo & ".pdf"
--> "2020061 98765432 06-2020.pdf"
-- make folders, move files, rename…
-- ================================================================================================
on textSplit(theText, theDelimiter)
-- this will split a string and returns a list of substrings
set saveDelim to AppleScript's text item delimiters
set AppleScript's text item delimiters to {theDelimiter}
set theList to every text item of theText
set AppleScript's text item delimiters to saveDelim
return (theList)
end textSplit

Get Automator app result in external Applescript?

Is there a way to retrieve result of an Automator app script in an external Applescript app (not the Applescript lines in Automator)?
Something like:
tell application "My_Automator_App"
-- suppose My_Automator_App checks the Calendar to see if there some events today
-- "Show Result" in Automator will display a list
get the_Result -- list returned by Automator
end tell
I looked into this a little bit and didn't find a natural means by which AppleScript and Automator applets can communicate, although this doesn't mean one definitely doesn't exist.
In the meantime, you could implement one of a couple of workarounds/hacks that, although a little unseemly in their methods, do achieve the desired result without creating any side issues that would affect the functionality of an applet itself.
1. Use The Clipboard
Append a Copy to Clipboard action at the end of the applet's workflow, or following the action whose result you would wish to be reported.
Retrieving the clipboard from AppleScript is simple:
get the clipboard
This will probably suit return values that are simple text strings or a number. Passing an array of items from an Automator action to the clipboard isn't very reliable, sometimes only allowing access to the first item. However, this can be resolved with a small AppleScript within the workflow to process results arrays properly and convert them into an accessible format, e.g. a comma-delimited string.
However, the clipboard is also capable of storing image data, file references, and other data types, so it will be possible (if not always straightforward) to send those to be retrieved in an AppleScript.
Where possible, strings and numbers are the safest storage types.
2. Write Out To A Temporary File
To avoid using the clipboard as an intermediary, or if you wish the applet to report multiple variables without too much work, then writing the data to a temporary file is a fairly common practice, such as is done in shell scripts when persistant values are needed between multiple executions of the same script.
There's actually a special directory that gets periodically purged so that temporary data files don't accumulate: /tmp. It's hidden in Finder, but you can still create files and delete them as you would any other directory. Files that aren't access for 3 days get purged by the system.
There is a New Text File action that can write text to a file:
Specifying the /tmp directory is most easily done by creating a variable whose value is "/tmp" (without the quotes), and dragging that variable onto the appropriate field.
But my inclination would be to insert an AppleScript, or more suitably, a shell script into the workflow, with which file manipulation becomes easy and more capable.
Calendar Events Example
Using a similar example to the scenario you described, a simple applet that retrieves calendar events might have a workflow that looks like this:
where you can calibrate the first action to isolate the events you want, such as today's events. That action returns a type of object that isn't easily processed by AppleScript, but the second action extracts the relevant data in text format, summarising the list of events that the first action returned.
This is where a temporary file is useful to write out the data to a text file, which can then be retrieved in an AppleScript.
Given this Automator applet saved under the named "CalEvents", this AppleScript makes use of that applet and its result:
property tidEvents : [linefeed, linefeed, "EVENT", space] as text
property tidDetails : {tab, " to "}
property tid : a reference to my text item delimiters
run application id "com.apple.automator.CalEvents"
set tid's contents to tidEvents
set EventsSummary to read POSIX file "/tmp/EventsSummary.txt"
set EventsList to the EventsSummary's text items
set [[n], EventsList] to [it, rest] of EventsList
set n to n's last word as number
EventsList -- The final list of events from first to last
Upon its first run, the applet requires consent to access your calendar information, which only needs to be done once and will make the above script appear to fail. Once authorised, you can run the script as often as you like to get the most up-to-date content of the /tmp/EventsSummary.txt file.
Each item in the list variable EventsList is a block of text that looks like this (asterisks are my redactions for privacy, as are the address items in curly braces):
4 OF 8
Summary: GP Appointment
Status: none
Date: 07/12/2017 to 07/12/2017
Time: 14:45:00 to 15:45:00
Location: ******** Medical Centre
{Address Line 1}
{Address Line 2}
{County}
{Post Code}
United Kingdom
Notes: 01*** *****9
Each value is separated from the preceding colon by a tab character, which won't be obvious here. Also, as you can tell from the date format and address, these are British-formatted values, but yours will, of course, be whatever they are set as in Calendar.
But since each list item is much the same, extracting details for a particular event will be simple in AppleScript, first by splitting a particular event item into paragraphs, and then splitting a particular paragraph by either a tab or space character (or both) or some preposition that naturally delimits useful bits of text:
set |Event| to some item in the EventsList
set tid's contents to tidDetails
set EventDetails to {title:text item 2 of paragraph 2 ¬
, startTime:text item 2 of paragraph 5 ¬
, EndTime:text item 3 of paragraph 5} of the |Event|
which places the important event details, such as its name and start/end times, in an AppleScript record:
{title:"GP Appointment", startTime:"15:45:00", EndTime:"16:00:00"}

Replace List Item Appinventor

I have a TinyDB and in each tag of the TinyDB I have a list.
Each list has 3 items, each indexed as 1, 2 and 3.
I want to change the 3rd item, index 3.
So I have done the following
So I want to now save the change in the TinyDB
and have added a storeValue command as follows.
I figured out how to get the valuetoStore variable. As follows.
I had done this before, and thought it wrong because it still doesn't change the 3rd item in the list. But I've added a notifier to look at it and it's correct. So the "replace list item" isn't working how I thought it should. It isn't replacing the 3rd item with an "n."
Any ideas?
Thanks.
Your second try is almost correct. The only thing is, you should use the replace list item block together with the local variable name instead of retrieving the value again from TinyDB.
So what is the difference to your "solution"? Currently you assign the list to a local variable name. Then you use the replace list item block together with a list, you can't store somewhere (you are loading the list again from TinyDB). And in the end you store variable name (which doesn't have been modified at all) in TinyDB. Therefore the solution is to use the replace list item block together with the local variable name instead of retrieving the value again from TinyDB. Btw. a better name for the local variable name would be list.
Further tips
Also in the definition of the local variable name you should add a block, e.g. an empty string or 0
And if you want simplify a little bit, you can move the definition of the local variable name inside the for each loop. And alternatively of using the for each number loop, for list it's easier to use the for each item in list loop, see also the documentation. The list in your case is TinyDB1.GetTags.
As already said in the forum, generally I would use a list of lists and store it in only one tag in TinyDB
How to work with Lists by Saj
How to work with Lists and Lists of lists (pdf) by appinventor.org

Use Automator and Applescript to move files to folders based on File Name

I have a folder which contains the following files:
Elephant.19864.archive.other.pdf
Elephant.17334.other.something.pdf
Turnip.19864.something.knight.pdf
Camera.22378.nothing.elf.pdf
I want these files moved to the following structure
Archive
Elephant
Elephant.19864.pdf
Elephant.17334.pdf
Turnip
Turnip.19864.pdf
Camera.HighRes
Camera.HighRes.22378.pdf
The generated files consist of a word or multiple words, followed by a sequence of number, followed by other words and then the extension. I want to move these into a folder named the word or words before the numbers, and remove all of the words between the numbers and the extension (.pdf in this case).
If the folder does not exist, then I have to create it.
I thought this would be quite simple using Automator or an AppleScript, but I don't seem to be able to get my head around it.
Is this easy using Automator/AppleScript if so, what should I be looking at
It's easy, it's just not obvious at first. Some things to get you started.
To parse the file names to get your folder names, you need to separate the name into a list...
set AppleScript's text item delimiters to {"."}
set fileNameComponents to (every text item in fileName) as list
set AppleScript's text item delimiters to oldDelims
--> returns: {"Elephant", "19864", "archive", "other", "pdf"}
The list has a 1-based index, so item 1 is "Elephant" and item 5 is "pdf". To mash the file name together, then all you need is this
set theFileName to (item 1 of fileNameComponents & item 2 of fileNameComponents & item 5 of fileNameComponents) as string
To create a folder, just use the following...
tell application "Finder"
set theNewFolder to make new folder at (theTargetFolder as alias) with properties {name:newFolderName, owner privileges:read write, group privileges:read write, everyones privileges:read write}
end tell
To move a file, all you need is this...
tell application "Finder"
set fileMoved to move theTargetFile to theTargetFolder
end tell
To rename a file, use something like the following...
set theFileToRename to theTargetFilePath as alias -- alias is important here
set name of theFileToRename to theFileName
I suggest first creating a list of all of the target files, then for each file in the list create the folders based on its name, move the file, finally renaming it once it is in its final location.
Add salt to taste.

Resources