File move into subfolders on distant server

Hello,

Tanks Nigel for your interest.

I tried to do the second part of a project that consists of moving files while retaining their original paths.
I’m using 2 Applescript that are started every 60 second by a .plist file placed in ~ / Library / LaunchAgents directory and loaded with terminal (launchctl load -w ~/Library/LaunchAgents/com.apfile.plist

The first Applescript has been in use for 5 years in my compagny (10 users) and retrieves the file path. (Error handling that does not work very well makes it possible to check that the file has been processed correctly)
For this first script, I did not find at the time of example with the shell.

Between the 2 scripts, the file is processed by a RIP that turns the .pdf into .ppm.

The second Applescript i’m trying to set up now, move the file by recreating its original path on the remote server. Ideally it would be fine to write in the file log the result

1- First script now in use

-- First part : recovering the folder path and putting it in front of the file name

-- Definition des 3 dossiers fixes : Emplacement à partir de la racine du disque
set D_Entree to alias ("Macintosh HD:Entree:")
set D_Sortie to "Macintosh HD:Sortie:" as string
set D_Erreur to "Macintosh HD:Erreurs:" as string

-- formatage de la date pour inscription dans le fichier log
set theDate to (current date)
set y to text -4 thru -1 of ("0000" & (year of theDate))
set m to text -2 thru -1 of ("00" & ((month of theDate) as integer))
set d to text -2 thru -1 of ("00" & (day of theDate))
set mn to time string of (current date) -- ajoute les minutes et secondes

set theDate to y & "-" & m & "-" & d & "-" & mn

-- définition du fichier de log des erreurs
set FichLog to D_Erreur & "Log_" & y & "_" & m & ".txt"

-- pour chaque dossier niveau 1 source entrée
tell application "Finder"
	
	set Niv_1 to every folder of D_Entree
	
	repeat with Dos_1 in Niv_1 -- pour chaque dossier de niveau 1(Dossier Client)
		
		set Nom_1 to name of Dos_1
		set Niv_2 to every folder of Dos_1
		
		repeat with Dos_2 in Niv_2 -- pour chaque dossier de niveau 2 contenu dans le niveau 1 (Dossier Commande)
			
			set Nom_2 to name of Dos_2
			set Niv_3 to every folder of Dos_2
			
			repeat with Dos_3 in Niv_3 -- pour chaque dossier de niveau 3 contenu dans le niveau 2 dans niveau 1 ((Dossier Support)
				
				set Nom_3 to name of Dos_3
				set Liste_Fichier to every file of Dos_3
				
				repeat with F in Liste_Fichier -- boucle sur chaque fichier du dossier
					delay 0.3 -- wait for file growing (sometimes more than 100 files at the same time)
					set N_Nom to Nom_1 & "_" & Nom_2 & "_" & Nom_3 & "_" & (name of F) -- variable N_Nom = nom du futur fichier
					set M_Alias to F as alias -- stock l'alias vers le fichier avant de changer son nom
					set the name of F to N_Nom -- change le nom du fichier avant déplacement
					delay 0.3
					-- Déplacement du fichier renommé et inscription dans le fichier log  --------------------------------
					try
						tell application "Finder" to move M_Alias to folder D_Sortie with replacing
					on error -- Don't work anymore ?
						--	open for access FichLog with write permission
						--	write theDate & " - Erreur de transfert de:  " & N_Nom & return to file the FichLog starting at eof -- écrire le message en fin de fichier-
						--	close access FichLog
						--on error
						--	try
						--		close access file the FichLog
						--	end try
						--end try
						
					end try
					try
						open for access FichLog with write permission
						write theDate & " - Ajout correct:  " & N_Nom & return to file the FichLog starting at eof -- écrire le message en fin de fichier-
						close access FichLog
					on error
						try
							close access file the FichLog
						end try
					end try
					
				end repeat -- sur chaque fichier
				
				-- supprime les dossiers vieux de plus de 45 jours
				if (creation date of (info for Dos_3 as alias) < (current date) - 45 * days) then
					
					try
						open for access FichLog with write permission
						write theDate & " - Dossier de commande > 45 jour supprime :  " & Dos_3 & return to file the FichLog starting at eof -- écrire le message en fin de fichier-
						close access FichLog
					on error
						try
							close access file the FichLog
						end try
					end try
					
					tell application "Finder" to delete Dos_3
					
				end if
				
				
			end repeat -- Niv_3
			
		end repeat -- Niv_2
		
	end repeat -- Niv_1
end tell

2- Second script on work

-- Second part: move file after treatment into the original folder path on remote server

set folderList to {}
set numberList to {}

set DestinationFolder to "Volumes:images:0_PDF:"   -- local folder "Macintosh HD:public:0_PDF:"
set sourceFolder to alias ("Macintosh HD:Sortie:")

set POSIXdestinationFolder to POSIX path of DestinationFolder


tell application "Finder" to set theFiles to files of sourceFolder
repeat with oneFile in theFiles
	set fileName to (get name of oneFile)
	
	
	--Récupération des 3 noms de dossiers et du nom de fichier de départ
	set lengthfileName to length of fileName
	
	set AppleScript's text item delimiters to "_"
	set subfolder1 to text item 1 of fileName
	set lengthsubfolder1 to length of subfolder1
	
	set subfolder2 to text item 2 of fileName
	set lengthsubfolder2 to length of subfolder2
	
	set subfolder3 to text item 3 of fileName
	set lengthsubfolder3 to length of subfolder3
	set lengthsubfolder to lengthsubfolder1 + lengthsubfolder2 + lengthsubfolder3 + 4
	
	set AppleScript's text item delimiters to ""
	set fileNamePdf to (characters lengthsubfolder thru -1 of fileName) as string
	
	set subfolder1Path to POSIXdestinationFolder & subfolder1 & "/" & subfolder2 & "/" & subfolder3
	set subfolder1Path to POSIX path of subfolder1Path
	
	try
		tell application "Finder" to set fileExists to exists (file fileName of folder (DestinationFolder & subfolder1 & ":" & subfolder2 & ":" & subfolder3 & ":"))
	on error
		set fileExists to false
	end try
	if not fileExists then
		set sourceFile to quoted form of POSIX path of (oneFile as text)
		do shell script "/usr/bin/ditto " & sourceFile & space & quoted form of (subfolder1Path & "/" & fileNamePdf)
		do shell script "/bin/rm -r " & sourceFile
		set flag to false
		
		repeat with i from 1 to count folderList
			if item i of folderList is subfolder3 then
				set flag to true
				exit repeat
			end if
		end repeat
		if flag then
			set item i of numberList to (get item i of numberList) + 1
		else
			set end of folderList to subfolder3
			set end of numberList to 1
		end if
	end if
end repeat
set resultList to {}
repeat with i from 1 to count folderList
	set end of resultList to (item i of numberList as text) & " fichier(s) ont été copié(s) dans: " & item i of folderList
end repeat
if resultList is {} then
	set resultString to "No files were copied"
else
	set {TID, text item delimiters} to {text item delimiters, return}
	set resultString to resultList as text
	set text item delimiters to TID
end if
display dialog resultString


Tanks for your time

GK

On my side I don’t use the shell.

Maybe this script using Shane Stanley’s “FileManagerLib” available at : www.macosxautomation.com/applescript/apps/ may do the job.

I tested it on local devices.

----------------------------------------------------------------
use AppleScript version "2.5"
use framework "Foundation"
use script "FileManagerLib" version "2.2.2"
use scripting additions
----------------------------------------------------------------

tell application "Finder"
	activate -- Bring to the front to display the following dialogs.
	
	set sourceDirectory to POSIX path of (choose folder with prompt "Select the folder containing the subfolders containing the file(s):")
	
	set destinationDirectory to POSIX path of (choose folder with prompt "Select a destination for the renamed file(s):")
end tell

# Build a list of files embedded in sourceDirectory
set workingFiles to objects of sourceDirectory result type paths list with searching subfolders without include folders and include invisible items
# Extract the relevant components of the path of first file
set components to my decoupe(first item of workingFiles, "/")
set partialPath to my recolle(items -4 thru -3 of components, "/") --> "D1/D2"
set lateSubFolder to item -2 of components --> "D3"

# Create the subfolders if they aren't available
set finalDest to create folder at (destinationDirectory & "/" & partialPath) use name lateSubFolder --> "xxx/D1/D2/D3"

repeat with aFile in workingFiles
	# Move the file
	move object aFile to folder finalDest
end repeat

#=====

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

#=====

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) mardi 6 aout 2019 11:39:16

Hi GK.

There are a few things I’d do differently in your second script. For instance, since oneFile is a Finder reference to the file, the instructions to get the file’s name and to get oneFile as text should ideally be given to the Finder. However, they seem to work as they are on my machine.

I’d also reduced this section:

--Récupération des 3 noms de dossiers et du nom de fichier de départ
set lengthfileName to length of fileName

set AppleScript's text item delimiters to "_"
set subfolder1 to text item 1 of fileName
set lengthsubfolder1 to length of subfolder1

set subfolder2 to text item 2 of fileName
set lengthsubfolder2 to length of subfolder2

set subfolder3 to text item 3 of fileName
set lengthsubfolder3 to length of subfolder3
set lengthsubfolder to lengthsubfolder1 + lengthsubfolder2 + lengthsubfolder3 + 4

set AppleScript's text item delimiters to ""
set fileNamePdf to (characters lengthsubfolder thru -1 of fileName) as string

set subfolder1Path to POSIXdestinationFolder & subfolder1 & "/" & subfolder2 & "/" & subfolder3
set subfolder1Path to POSIX path of subfolder1Path

… to this:

--Récupération des 3 noms de dossiers et du nom de fichier de départ
set AppleScript's text item delimiters to "_"
set {subfolder1, subfolder2, subfolder3, fileNamePdf} to text items of fileName
set AppleScript's text item delimiters to ""

set subfolder1Path to POSIXdestinationFolder & subfolder1 & "/" & subfolder2 & "/" & subfolder3

I suspect that this instruction:

tell application "Finder" to set fileExists to exists (file fileName of folder (DestinationFolder & subfolder1 & ":" & subfolder2 & ":" & subfolder3 & ":"))

… should actually be:

tell application "Finder" to set fileExists to exists (file fileNamePDF of folder (DestinationFolder & subfolder1 & ":" & subfolder2 & ":" & subfolder3 & ":"))

But I can’t see why the ditto command should be creating the folder structure on your server while not duplicating the file itself. The command seems to be getting all the necessary information. However, the shell script shown in your first post only contains the destination path, not the source. :confused:

Thanks Yvan,

I will have a look at this “FileManagerLib”, and try it. This script seems more simple that mine.
But I am a beginner and if I can assemble some parts of code found here and there, I do not always understand how it works (or not …).

Merci Yvan,
Je vais jeter un œil sur ce code et essayer de le faire fonctionner. Celui ci semble beaucoup plus simple que celui que j’utilise actuellement.
Mais je suis un débutant et si j’arrive à assembler certaines parties de code trouvé ça et là, je ne comprend pas toujours commence ça fonctionne (ou pas…)

GK

Hi Yvan.

Just looking quickly at your script, it moves all the files to the same folder instead of each file to a folder relevant to it.

Thanks for your correction Nigel,

It’s not possible to use your reducted section, because often we have file name like this : test_File_01.pdf
It is the reason i used the lenght.

I will try Yvan’s suggestion with the use of the item numbers.

GK

In your first post, you said that the files were named like this: D1_D2_D3_test.pdf. Are you saying this isn’t true? Or are you saying that some names have additional underscores which need to be kept, such as D1_D2_D3_test_File_01.pdf → /D1/D2/D3/test_File_01.pdf?

Otherwise I was going to say that, even as it is, your script successfully copies, renames, and reorganises files across the network from one of my computers to the other. I’ve tried deliberately only supplying one parameter to ditto and it errors, so …

… can’t be right.

I’ve had a go at tidying up the script and removing obvious errors, just in case it solves the problem. (This includes allowing for file names to contain more than three underscores.) But I can’t reproduce the problem myself:

-- Second part: move file after treatment into the original folder path on remote server

set folderList to {}
set numberList to {}

set DestinationFolder to "images:0_PDF:" -- NOT "Volumes:" in an HFS path
set sourceFolder to alias ("Macintosh HD:Sortie:")

tell application "Finder" to set theFiles to files of sourceFolder
repeat with oneFile in theFiles
	tell application "Finder" to set fileName to (get name of oneFile) -- tell application "Finder"
	
	--Récupération des 3 noms de dossiers et du nom de fichier de départ
	set TID to AppleScript's text item delimiters
	set AppleScript's text item delimiters to "_"
	set {subfolder1, subfolder2, subfolder3} to text items 1 thru 3 of fileName -- The three folder name parts.
	set fileNamePdf to text from text item 4 to -1 of fileName -- The rest of the name.
	set AppleScript's text item delimiters to ":"
	set fileDestinationPath to DestinationFolder & {subfolder1, subfolder2, subfolder3, fileNamePdf} -- Complete _HFS_ destination path for the file.
	set AppleScript's text item delimiters to TID
	
	-- try -- 'exists' is designed not to error.
	tell application "Finder" to set fileExists to (exists file fileDestinationPath) -- file fileNamePDF, not file fileName.
	-- end try
	
	if not fileExists then
		tell application "Finder" to set sourceFile to quoted form of POSIX path of (oneFile as text) -- tell application "Finder".
		set fileDestinationPath to quoted form of POSIX path of fileDestinationPath -- NOW get the POSIX path, in case any characters need to be changed.
		
		do shell script "/usr/bin/ditto " & sourceFile & space & fileDestinationPath
		do shell script "/bin/rm -r " & sourceFile
		set flag to false
		
		repeat with i from 1 to count folderList
			if item i of folderList is subfolder3 then
				set flag to true
				exit repeat
			end if
		end repeat
		if flag then
			set item i of numberList to (get item i of numberList) + 1
		else
			set end of folderList to subfolder3
			set end of numberList to 1
		end if
	end if
end repeat
set resultList to {}
repeat with i from 1 to count folderList
	set end of resultList to (item i of numberList as text) & " fichier(s) ont été copié(s) dans: " & item i of folderList
end repeat
if resultList is {} then
	set resultString to "No files were copied"
else
	set {TID, text item delimiters} to {text item delimiters, return}
	set resultString to resultList as text
	set text item delimiters to TID
end if
display dialog resultString

Oops.
Here is an edited version

----------------------------------------------------------------
use AppleScript version "2.5"
use framework "Foundation"
use script "FileManagerLib" version "2.2.2"
use scripting additions
----------------------------------------------------------------
property forTests : true #  during tests I use copy object so the original files remain in place

tell application "Finder"
	activate -- Bring to the front to display the following dialogs.
	
	set sourceDirectory to POSIX path of (choose folder with prompt "Select the folder containing the subfolders containing the file(s):")
	
	set destinationDirectory to POSIX path of (choose folder with prompt "Select a destination for the renamed file(s):")
end tell

# Build a list of files embedded in sourceDirectory
set workingFiles to objects of sourceDirectory result type paths list with searching subfolders without include folders and include invisible items

repeat with aFile in workingFiles
	# Extract the relevant components of the path of the file
	set components to my decoupe(aFile, "/")
	set partialPath to my recolle(items -4 thru -3 of components, "/") --> "D1/D2"
	set lateSubFolder to item -2 of components --> "D3"
	set newName to my recolle(items -4 thru -1 of components, "_") --> "D1_D2_D3_oldName.pdf" # ADDED
	
	# Create the destination subfolders if they aren't available
	set finalDest to create folder at (destinationDirectory & "/" & partialPath) use name lateSubFolder --> "xxx/D1/D2/D3"
	# Move the file
	if forTests then
		copy object aFile to folder finalDest new name newName # EDITED
	else
		move object aFile to folder finalDest new name newName # EDITED
	end if
end repeat

#=====

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

#=====

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) mardi 6 aout 2019 15:53:05

Updated to use newName
in source folder :
D1
D2
D3
Devis_M06A-1908-00021.pdf
mail BioEsterel.pdf
D3-2
Ticket2.pdf
D2-2
D2-2-2
Ticket.pdf

in destination folder :
D1
D2
D3
D1_D2_D3_Devis_M06A-1908-00021.pdf
D1_D2_D3_mail BioEsterel.pdf
D3-2
D1_D2_D3-2_Ticket2.pdf
D2-2
D2-2-2
D1_D2-2_D2-2-2_Ticket.pdf

Hi Nigel,
Hi Yvan,

Thanks for your quick answers.

@Nigel: i will test your correction quickly.

@Yvan: your code is very fast, but I need an extra step between “decoupe” and “recolle” that I do not know how to set up.

Here is the workflow i need:
1- We start with .pdf file like: /sourcefolder/D1/D2/D3/file_name_01.pdf
2- “decoupe”, rename and movethe .pdf file like this (to keep the path) : /RIPsourcefolder/D1_D2_D3_file_name_01.pdf

An application (Caldera RIP) take the file in /RIPsourcefolder/ and turn the .pdf file into .ppm file and move it into /RIPdestinationfolder/

3-take the .ppm file into /RIPdestinationfolder/ and “recolle”, rename and move the .ppm file to the /finaldestinationfolder/D1/D2/D3/file_name_01.ppm

Thanks for your help

GK

I edited the script in message #10.
I hope that I understood correctly.

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) mardi 6 aout 2019 18:17:07

Your script will be structured other way (3 jobs in repeat loop). Here I show only the method, I do not tested if and how this works. So, be careful:


# Build a list of files embedded in sourceDirectory
set workingFiles to objects of sourceDirectory result type paths list with searching subfolders without include folders and include invisible items

repeat with aFile in workingFiles
	set components to my decoupe(aFile, "/")
	set partialPath to my recolle(items -4 thru -3 of components, "/") --> "D1/D2"
	set lateSubFolder to item -2 of components --> "D3"
	set newName to my recolle(items -4 thru -1 of components, "_") --> "D1_D2_D3_oldName.pdf" # ADDED
	set ripFile to duplicate aFile to RipDirectory with newName -- all this was THE FIRST PART OF JOB
	
	-- HERE GOES SECOND PART -- CONVERTING WITH "Caldera RIP". I don't know how you do this.
	-- It should process ripFile instead of aFile 
	
	-- The 3rd PART OF JOB
	set finalDest to create folder at (destinationDirectory & "/" & partialPath) use name lateSubFolder --> "xxx/D1/D2/D3"
	# Move the file
	move ripFile to destinationDirectory
	
end repeat

on myRename(aFile, newName, partialPath)
	# Extract the relevant components of the path of the file
	set components to my decoupe(aFile, "/")
	set partialPath to my recolle(items -4 thru -3 of components, "/") --> "D1/D2"
	set lateSubFolder to item -2 of components --> "D3"
	set newName to my recolle(items -4 thru -1 of components, "_") --> "D1_D2_D3_oldName.pdf" # ADDED
end myRename

#=====

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

@KniazidisR

As far as I know, there is no law forbidding us to execute several tasks in a repeat loop.
Here I really don’t find any interest in moving four instructions in a handler.
I like handlers when I may hope to reuse them here and there or when they make a script more easy to understand or debug.
Here, at least from my point of view, such features aren’t delivered so I apologize but I will not use your handler.

More important point, your instruction:
my myRename(aFile, newName, partialPath) – IS THE FIRST PART OF JOB
fails to do the entire job.
It would be :
set newName to my myRename(aFile, newName, partialPath) – IS THE FIRST PART OF JOB

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) mardi 6 aout 2019 20:58:20

I fixed this problem as need. No I debug other mistakes

NOTE to OP: in 2) step you describe. Renaming of original file is equivalent to moving it immediately to Rip directory. So, don’t do that. Instead, duplicate it to Rip directory and rename the duplicate. NOT COPY but duplicate command should be used.

As insomnia strike, I built a more complete code.

----------------------------------------------------------------
use AppleScript version "2.5"
use framework "Foundation"
use script "FileManagerLib" version "2.2.2"
use scripting additions
----------------------------------------------------------------
property forTests : true #  during tests I use copy object so the original files remain in place

tell application "Finder"
	activate -- Bring to the front to display the following dialogs.
	
	set sourceDirectory to POSIX path of (choose folder with prompt "Select the folder containing the subfolders containing the file(s):")
	
	set destinationDirectory to POSIX path of (choose folder with prompt "Select a destination for the renamed file(s):")
end tell

# Build a list of files embedded in sourceDirectory
set workingFiles to objects of sourceDirectory result type paths list with searching subfolders without include folders and include invisible items

set p2d to path to desktop as text
set reportPath to p2d & "myLog.txt"
my writeto(reportPath, "", «class utf8», false) # Create/Clean the log file

# build the folder used as workspace
set tempFolder to POSIX path of (path to temporary items) # Edit to fit your needs

repeat with aFile in workingFiles
	if aFile ends with ".pdf" then
		try
			# Extract the relevant components of the path of the file
			set components to my decoupe(aFile, "/")
			set partialPath to my recolle(items -4 thru -3 of components, "/") --> "D1/D2"
			set lateSubFolder to item -2 of components --> "D3"
			set newNamePdf to my recolle(items -4 thru -1 of components, "_") --> "D1_D2_D3_oldName.pdf"
			set newNamePpm to (text 1 thru -3 of newNamePdf) & "pm" --> "D1_D2_D3_oldName.ppm"
			# Create the destination subfolders if they aren't available
			set finalDest to (create folder at (destinationDirectory & partialPath) use name lateSubFolder) & "/" --> "xxx/D1/D2/D3"
			# Duplicate the file to the temp folder so it will remain available if something fail during the process
			set tempPDF to copy object aFile to folder tempFolder new name newNamePdf with replacing and return path
			#log result
			my writeto(reportPath, my horoDateur() & " The file “" & aFile & "” is duplicated as “" & tempPDF & "”" & linefeed, «class utf8», true) # Write in the log file
			
			# Now fake "Caldera RIP" code 
			
			set tempPpm to tempFolder & newNamePpm
			# For safe, delete such Ppm if it already exists
			if exists object tempPpm then remove object tempPpm
			# Now we may rename. Returning the path was coded for tests, not needed in working script
			rename object tempPDF to name newNamePpm # with return path
			# log result
			my writeto(reportPath, my horoDateur() & " The file “" & tempPDF & "” is converted as “" & tempPpm & "”" & linefeed, «class utf8», true) # Write in the log file
			
			
			# Move the Ppm file to final location.
			
			set finalPpm to move object tempPpm to folder finalDest with replacing and return path --> "xxx/D1/D2/D3/D1_D2_D3_oldName.ppm"
			#log result
			my writeto(reportPath, my horoDateur() & " The document is stored as “" & finalPpm & "”" & linefeed & linefeed, «class utf8», true) # # Write in the log file
			# Here the process ended flawlessly so we may delete the original
			if not forTests then remove object aFile
			
		on error e number n
			
			my writeto(reportPath, my horoDateur() & " Error : " & e & " number# " & n & " The original file “" & aFile & ". remains available." & linefeed & linefeed, «class utf8», true) # Write in the log file
		end try
	end if
end repeat

#=====

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

#=====

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

#=====

(*
Handler borrowed to Regulus6633 - http://macscripter.net/viewtopic.php?id=36861
*)
on writeto(targetFile, theData, dataType, apendData)
	-- targetFile is the path to the file you want to write
	-- theData is the data you want in the file.
	-- dataType is the data type of theData and it can be text, list, record etc.
	-- apendData is true to append theData to the end of the current contents of the file or false to overwrite it
	try
		set targetFile to targetFile as «class furl»
		set openFile to open for access targetFile with write permission
		if not apendData then set eof of openFile to 0
		write theData to openFile starting at eof as dataType
		close access openFile
		return true
	on error
		try
			close access targetFile
		end try
		return false
	end try
end writeto

#=====

on horoDateur()
	set theFormatter to current application's NSDateFormatter's new()
	theFormatter's setDateFormat:"yyyy-MM-dd HH:mm:ss"
	return (theFormatter's stringFromDate:(current date)) as text
end horoDateur

#=====

@KniazidisR

You made a mixture of fileManagerLib syntax and Finder’s one.

set ripFile to duplicate aFile to RipDirectory with newName – all this was THE FIRST PART OF JOB is a wrong instruction.
There is no duplicate command in FileManagerLib.
There is a create duplicate one but it doesn’t accept the parameter with newName
The correct syntax would be :
set ripFile to copy object aFile to folder RipDirectory new name newName with return path # for safe add “and replacing

The instruction :
move ripFile to destinationDirectory is wrong too
It would be :
move object ripFile to folder destinationDirectory

I hope that I forgot nothing. Now I will retry to sleep.

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) mardi 6 aout 2019 23:01:41

I corrected an error and added code writing a log file on the desktop.

I was tested and changed all the script. This works fine and is shorter:


----------------------------------------------------------------
use AppleScript version "2.5"
use framework "Foundation"
use script "FileManagerLib" version "2.2.1"
use scripting additions
property RipDirectory : path to desktop
----------------------------------------------------------------

tell application "Finder"
	activate -- Bring to the front to display the following dialogs.
	set sourceDirectory to POSIX path of (choose folder with prompt "Select the folder containing the subfolders containing the file(s):")
	set destinationDirectory to POSIX path of (choose folder with prompt "Select a destination for the renamed file(s):")
end tell

# Build a list of files embedded in sourceDirectory
set workingFiles to objects of sourceDirectory result type files list with searching subfolders without include folders and include invisible items

repeat with aFile in workingFiles
	
	-- FIND and REMEMBER NAMES of D1,D2,D3 folders
	tell application "System Events"
		set parentFolder to container of (aFile as alias)
		set parentFolderName to name of parentFolder -- "D3"
		set grandParentFolder to container of parentFolder
		set grandParentFolderName to (name of grandParentFolder) -- "D2"
		set rootFolder to container of grandParentFolder
		set rootFolderName to (name of rootFolder) -- "D1"
	end tell
	tell application "Finder"
		set ripFile to duplicate aFile to RipDirectory -- all this was THE FIRST PART OF JOB
		set ripFile to POSIX path of (ripFile as alias)
	end tell
	
	-- HERE GOES SECOND PART -- CONVERTING WITH "Caldera RIP". I don't know how you do this.
	-- It should process ripFile instead of aFile 
	
	-- The 3rd PART OF JOB
	set partialPath to rootFolderName & "/" & grandParentFolderName -- "D1/D2"
	set finalDest to create folder at (destinationDirectory & "/" & partialPath) use name parentFolderName --> "xxx/D1/D2/D3"
	move object ripFile to folder finalDest
	
end repeat

‘object’ isn’t a Finder term.

Thanks. OK, I fixed the error and now my last script works as I wanted.

Hello everyone,

Thank you for all your answers, it allows me to progress.

However, I think I am going to use two separate scripts.
The Rip Caldera being an intermediate process well apart, there can be no link between the three stages of Workflow.
(Otherwise it would be necessary to use a database and then manage it, which seems very complicated for my skills.)

I will do some tests and come back and show them to you.

GK

I edited message #16

I made a correction and added code writing a log file on the desktop.

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) mercredi 7 aout 2019 11:21:57

Hi,

Here are my two scripts between the Rip Caldera Proccess. (www.caldera.com for the curious)
I start with the example of Yvan, because I like the functions “decoupe” and “recolle”.
The part I added or modified is a lot less elegant, but seems to work as desired.

I still have to find how to write in the log file the files in error (files deposited in the source folder, but impossible to move for example - corrupted file …)

And I must also delete the folders D1, D2 and D3 not used for more than 45 days.

GK

Script 1

# Code Yvan/GK Script 1 --> Pdf vers Caldera

----------------------------------------------------------------
use AppleScript version "2.5"
use framework "Foundation"
use script "FileManagerLib" version "2.2.2"
use scripting additions
----------------------------------------------------------------
property forTests : true #  during tests I use copy object so the original files remain in place

# Working Folders
set sourceDirectory to POSIX path of ("Macintosh HD:Users:dupont:Desktop:Entree:")
set logDirectory to POSIX path of ("Macintosh HD:Users:dupont:Desktop:Logs:")
set destinationDirectory to POSIX path of ("Macintosh HD:Users:dupont:Desktop:Caldera:")

# Date use to create one log file / month
set theDate to (current date)
set y to text -4 thru -1 of ("0000" & (year of theDate))
set m to text -2 thru -1 of ("00" & ((month of theDate) as integer))
set d to text -2 thru -1 of ("00" & (day of theDate))
set mn to time string of (current date) -- ajoute les minutes et secondes

set theDate to y & "-" & m & "-" & d & "-" & mn

# create one log file / month
set reportPath to logDirectory & "Log_" & y & "_" & m & ".txt"
my writeto(reportPath, "", «class utf8», false) # Create/Clean the log file

# Build a list of files embedded in sourceDirectory
set workingFiles to objects of sourceDirectory result type paths list with searching subfolders without include folders and include invisible items

repeat with aFile in workingFiles
	# Extract the relevant components of the path of the file
	set components to my decoupe(aFile, "/")
	set partialPath to my recolle(items -4 thru -3 of components, "/") --> "D1/D2"
	set lateSubFolder to item -2 of components --> "D3"
	set newName to my recolle(items -4 thru -1 of components, "_") --> "D1_D2_D3_oldName.pdf" # ADDED
	
	# Create the destination subfolders if they aren't available
	--set finalDest to create folder at (destinationDirectory & "/" & partialPath) use name lateSubFolder --> "xxx/D1/D2/D3"
	# Move the file
	if forTests then
		copy object aFile to folder destinationDirectory new name newName 
		#log result
		my writeto(reportPath, my horoDateur() & " - PDF, ajout correct sur RIP Caldera:  " & newName & linefeed, «class utf8», true) # Write in the log file
		
	else
		move object aFile to folder finalDest new name newName 
		#log result
		my writeto(reportPath, my horoDateur() & " - PDF, ajout correct sur RIP Caldera:  " & newName & linefeed, «class utf8», true) # Write in the log file
		
	end if
end repeat

#======

-- TODO: GERER LA SUPPRESSION DES DOSSIERS D1/D2/D3 VIEUX DE PLUS DE 45 JOURS

--	--supprime les dossiers vieux de plus de 45 jours
--			if (creation date of (info for D3 ) < (current date) - 45 * days) then
--				
--				try
--					open for access FichLog with write permission
--					write theDate & " - Dossier commande ancien supprime :  " & Dos_3 & return to file the FichLog starting at eof -- écrire le message en fin de fichier-
--					close access FichLog
--				on error
--				try
--						close access file the FichLog
--					end try
--				end try
--				
--			tell application "Finder" to delete D3

--> Idem for D2 and D1

#=====

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

#=====

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

#=====

on writeto(targetFile, theData, dataType, apendData)
	-- targetFile is the path to the file you want to write
	-- theData is the data you want in the file.
	-- dataType is the data type of theData and it can be text, list, record etc.
	-- apendData is true to append theData to the end of the current contents of the file or false to overwrite it
	try
		set targetFile to targetFile as «class furl»
		set openFile to open for access targetFile with write permission
		--if not apendData then set eof of openFile to 0
		write theData to openFile starting at eof as dataType
		close access openFile
		return true
	on error
		try
			close access targetFile
		end try
		return false
	end try
end writeto

#=====

on horoDateur()
	set theFormatter to current application's NSDateFormatter's new()
	theFormatter's setDateFormat:"yyyy-MM-dd HH:mm:ss"
	return (theFormatter's stringFromDate:(current date)) as text
end horoDateur

#=====

#================
Rip Caldera Process
#================

Script2

# Code Yvan/GK Script 2  --> Caldera-ppm vers Serveur

----------------------------------------------------------------
use AppleScript version "2.5"
use framework "Foundation"
use script "FileManagerLib" version "2.2.2"
use scripting additions
----------------------------------------------------------------
property forTests : true #  during tests I use copy object so the original files remain in place

# Working Folders	
set sourceDirectory to POSIX path of ("Macintosh HD:Users:dupont:Desktop:CalderaPPM:")
set logDirectory to POSIX path of ("Macintosh HD:Users:dupont:Desktop:Logs:")
set destinationDirectory to POSIX path of ("images:0_PPM:") -- Folder on remote server -- local folder for test("Macintosh HD:Users:dupont:Desktop:0_PPM:") --

# Date use to create one log file / month
set theDate to (current date)
set y to text -4 thru -1 of ("0000" & (year of theDate))
set m to text -2 thru -1 of ("00" & ((month of theDate) as integer))
set d to text -2 thru -1 of ("00" & (day of theDate))
set mn to time string of (current date) -- ajoute les minutes et secondes

set theDate to y & "-" & m & "-" & d & "-" & mn

# create one log file / month
set reportPath to logDirectory & "Log_" & y & "_" & m & ".txt"
my writeto(reportPath, "", «class utf8», false) # Create/Clean the log file

# Build a list of files embedded in sourceDirectory
set workingFiles to objects of sourceDirectory result type paths list without searching subfolders and include invisible items --include folders and include invisible items

repeat with aFile in workingFiles
	# Extract the relevant components of the path of the file
	set components to my decoupe(aFile, "/")
	# Extract the relevant components of the file
	set components to item -1 of components
	set components to my decoupe(components, "_")
	set nbcomponents to (number of components)
	
	set partialPath to my recolle(items 1 thru 3 of components, "/") --> "D1/D2/D3"
	set ppmName to my recolle(items 4 thru nbcomponents of components, "_") --> Nom du fichier d'origne
	
	# Create the destination subfolders if they aren't available
	set finalDest to create folder at (destinationDirectory & "/" & partialPath) --> "xxx/D1/D2/D3"
	# Move the file
	if forTests then
		copy object aFile to folder finalDest new name ppmName 
		#log result
		my writeto(reportPath, my horoDateur() & " - Ppm, ajout correct sur Prepstation:  " & ppmName & linefeed, «class utf8», true) # Write in the log file
		
	else
		move object aFile to folder finalDest new name ppmName 
		#log result
		my writeto(reportPath, my horoDateur() & " - Ppm, ajout correct sur Prepstation:  " & ppmName & linefeed, «class utf8», true) # Write in the log file
		
	end if
end repeat


#=====

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

#=====

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

#=====

on writeto(targetFile, theData, dataType, apendData)
	-- targetFile is the path to the file you want to write
	-- theData is the data you want in the file.
	-- dataType is the data type of theData and it can be text, list, record etc.
	-- apendData is true to append theData to the end of the current contents of the file or false to overwrite it
	try
		set targetFile to targetFile as «class furl»
		set openFile to open for access targetFile with write permission
		--if not apendData then set eof of openFile to 0
		write theData to openFile starting at eof as dataType
		close access openFile
		return true
	on error
		try
			close access targetFile
		end try
		return false
	end try
end writeto

#=====

on horoDateur()
	set theFormatter to current application's NSDateFormatter's new()
	theFormatter's setDateFormat:"yyyy-MM-dd HH:mm:ss"
	return (theFormatter's stringFromDate:(current date)) as text
end horoDateur

#=====