fix doScript function error in InDesign script - javascript

I wrote a script for InDesign and used doScript to run a bat file. This script works on some systems and not on others.
The error is in the image.
I run as admin InDesign. But it gives another error.
How can I fix the error?
function batFile(str) {
var path = "~\\AppData\\Roaming\\test\\";
var filename = 'b1.bat';
var file1 = new File(path + filename);
file1.encoding = 'UTF-8';
file1.open('w');
var txt = "systeminfo | findstr /B /C:\"OS Name\" /C:\"OS Version\">%appdata%\\test\\t1.txt"
file1.write(txt);
file1.close();
var cmdcode = "CreateObject(\"WScript.Shell\").Run \"%appdata%\\test\\b1.bat\", 0, True";
app.doScript(cmdcode, ScriptLanguage.visualBasic, undefined, UndoModes.FAST_ENTIRE_SCRIPT);
var result = path + "t1.txt";
var arry = openFile2(result);
if (arry.length != 0) {
return arry;
} else {
return "null";
}
}
**
Update
I find the problem.
When a user name is composed of two parts, such as "your name" causes this problem. To address this issue, we need to put the address in two double quotations.
var txt = "systeminfo | findstr /B /C:\"OS Name\" /C:\"OS Version\">\"%appdata%\\test\\t1.txt"\"
**
Update 2
In Windows, when the user uses OneDrive, the AppData path also changes, which causes doScript not to run. for example:
c: \ users \ username \ appdata
Changes to:
c: \ users \ username \ onedrive \ appdata

This is a known bug reported in the UserVoice: https://indesign.uservoice.com/forums/601180-adobe-indesign-bugs/suggestions/41072476-type-library-is-not-automatically-created-by-cc202. A common trick to solve this is, run InDesign at least once as administrator on the client machine. This activates VBS support.

I can't tell what the problem with your script. But just in case, you can run bat file this way:
var bat_file = File("your_file.bat");
bat_file.execute();
Update
Based on your code I can offer the workaround: add & echo ok > %appdata%\\test\\ok.txt in your bat file and check if the file ok.txt exists before going further.
function batFile(str) {
var path = "~\\AppData\\Roaming\\test\\";
var filename = 'b1.bat';
var file1 = new File(path + filename);
file1.encoding = 'UTF-8';
file1.open('w');
var txt = "systeminfo | findstr /B /C:\"OS Name\" /C:\"OS Version\">%appdata%\\test\\t1.txt";
// add the file 'ok.txt' after the previous command is finished
txt += " & echo ok > %appdata%\\test\\ok.txt";
file1.write(txt);
file1.close();
// run the bat file
file1.execute();
// check if the file 'ok.txt' exists before going further
var ok = File(path + "ok.txt");
while (!ok.exists) $.sleep(100);
ok.remove();
// do stuff
var result = path + "t1.txt";
var arry = openFile2(result);
if (arry.length != 0) {
return arry;
} else {
return "null";
}
}

Related

\n problem when using javascript to exec "python -c "

function get_params(command_string,tpp){
var rt = "None"
// 如果存在->那么取出值并覆盖
if(command_string.search("->") != -1){
rt = /->(.*):/.exec(command_string)[1]
var rep = /\)(\s{0,1}->\s{0,1}.*):/.exec(command_string)[1];
command_string = command_string.replace(rep, "");
}
command_string = command_string.replace(/(^\s*)/g, "");
var func_name = /^def ([_\da-zA-Z]+)\(.*/.exec(command_string)[1]
var comon = `python -c "
import inspect
import json
from typing import *
from datetime import *
result = []
${command_string}
pass
for x in inspect.signature(${func_name}).parameters.values():
try:
result.append(dict(name=x.name, annotation=x.annotation.__name__ if x.annotation != inspect._empty else 'Undeclared', default= x.default if x.default != inspect._empty else 'Undeclared'))
except Exception:
result.append(dict(name=x.name, annotation=x.annotation._name if x.annotation != inspect._empty else 'Undeclared', default= x.default if x.default != inspect._empty else 'Undeclared'))
print(json.dumps(result))
"`
console.log(comon)
var message = execute(comon).toString();
return {
"params":GenarateParamDoc(JSON.parse(message), tpp),
"rt": rt
}
}
I try to use javascript to execute some python code by "python -c". it works in Linux,
but I don't know why failed in windows and mac,
I guess it caused by the difference between \n \r\n and \r.
so I want to ask how to fix this problem.
this project is in https://github.com/QUANTAXIS/QAHelper
you can clone it and run in vscode.

Convert path string from unc to uri, replacing slashes with backslashes in Google Apps Script

I need to convert a path this UNC. I have searched and search and cannot piece anything together.
"\\NAS_01\GlobalShare\Docs\Customers\2017\S\Smith, John\photo1.jpg"
I need to remove the "\NAS_01\GlobalShare\Docs\Customers\" portion of the path and also "photo1.jpg" and end up with:
2017\S\Smith, John\
so that I can pass it to the following function:
function getDriveFolderNoCreate(path, rootFolder) {
var name, folder, search, fullpath;
// Remove extra slashes and trim the path
fullpath = path.replace(/^\/*|\/*$/g, '').replace(/^\s*|\s*$/g, '').split("/");
// Always start with the main Drive folder
folder = rootFolder;
for (var subfolder in fullpath) {
name = fullpath[subfolder];
search = folder.getFoldersByName(name);
if (search.hasNext()) {
var folder = search.next;
var folderID = folder.getId();
return folderID;
}
}
}
My intention is to return a url to open the Google Drive folder with the same path.
I ended up with a multi-part solution that works very well.
I paste the fill UNC path to cell B2.
This formula is in B3 =Index(split(B2, "\"), 0, 8)
It returns the exact folder name i need.
Then in my gs file:
function findDriveFolder() {
var pFId = "XYZ1233333333333";
var input = SpreadsheetApp.getActive().getRange("B3").getValue();
var folders = DriveApp.getFoldersByName(input);
Logger.log("folders: " + folders[0]);
while (folders.hasNext()) {
var folder = folders.next();
var url = folder.getUrl();
showAnchor("View Folder", url);
}
}
function showAnchor(name,url) {
var html = '<html><body>'+name+'</body></html>';
var ui = HtmlService.createHtmlOutput(html)
SpreadsheetApp.getUi().showModelessDialog(ui,"Files Folder");
}
I have not implemented the searchFolders part yet that I hope will speed it up. At least it's working for now.
Apps Script needs your input backslashes to be escaped if you are writing the string yourself (i.e. testing input).
wrong:
input = "\\NAS_01\GlobalShare\Docs\Customers\2017\S\Smith, John\photo1.jpg"
right:
input = "\\\\NAS_01\\GlobalShare\\Docs\\Customers\\2017\\S\\Smith, John\\photos1.jpg"
In Apps Script then, I am able to get the matching portion with the following regex:
/\d{4}\\[A-Z]\\.+\\/
i.e:
function unc2uri(input) {
const forwardSlash = String.fromCharCode(47);
const backSlash = String.fromCharCode(92);
if(!input)
input = '\\\\NAS_01\\GlobalShare\\Docs\\Customers\\2017\\S\\Smith, John\\photo1.jpg';
// Should show \\NAS_01\GlobalShare\Docs\Customers\2017\S\Smith, John\photo1.jpg
Logger.log(input);
const matcher = /\d{4}\\[A-Z]\\.+\\/;
const arrayOfMatches = input.match(matcher);
// Should show [2017\S\Smith, John\].
Logger.log(arrayOfMatches);
}
To verify, ask for the input string from someplace else (example, Browser.inputBox) and pass that to the above as input:
function readInput() {
unc2uri(Browser.inputBox("What's the path?"));
}
In the inputBox, you would enter the string you expect to be sent, as we view it, i.e. \\NAS_01\GlobalShare\Docs\Customers\2017\S\Smith, John\photo1.jpg

alfresco javascript inheritance and paths

I am writing a simple script on javascript for Alfresco Community. I have the script runnign everytime a new file is uploaded.
I need to check wether an specific filename (label.txt) exists in the folder. If it exists, I will use the information contained in the file for later treatment.
If I set the filename alone it works as long as the folder itself is the one with the script asigned, it works perfecly.
var labelFile = space.childByNamePath("label.txt");
if (labelFile != null)
{
...
}
When i set the inheritance of the script to lower level folders the script runs but still tries to find the label.txt file in the root folder. I am trying to locate the actual path of the uploaded document:
var dpath = document.displayPath + "/label.txt";
var labelFile = space.childByNamePath(dpath);
logFile.content += "labelFile: " + labelFile.displayPath + "\r\n";
if (labelFile != null)
{
...
}
I am getting a supposedly correct path in the dpath var, but I get a NULL result on the file object so I cannot read the file and its content.
What I am doing wrong?
What is "space" there? Try using "companyhome", see this for further ideas. http://docs.alfresco.com/4.0/references/API-JS-rootscoped.html
The current space ScriptNode (if any). For a script executing from a
rule, the space object is the space in which the rule resides. If the rule is inherited, this may not be the expected space.
The problem was not about inheritance, but space.childByNamePath just accepting relative paths, not absolute, so I ahd to calculate it from the space root:
var dpath = document.displayPath;
var dpatharray = dpath.split("/");
var dpathlength = dpatharray.length;
var spath = space.displayPath;
var spatharray = spath.split("/");
var spathlength = spatharray.length;
var labelpath = "";
for (var i=spathlength + 1; i<dpathlength; i++)
{
labelpath += dpatharray[i] + "/";
}
var labelFile = space.childByNamePath(labelpath + "label.txt");

Photoshop Javascript script: Rename file and saveAs

Im new to using JS with photoshop and have some trouble. What I want to do is to get rid of the word "Online" in the file name of the current document and then save a JPG with new file name in a different folder.
With the help of the adobe reference I came up with the following script:
//Path where the final jpg should be saved
var JPGquality = 12;
var docPath="C:\Users\user\Desktop\test";
var docName='';
docName = activeDocument.name;
//Set new file name by replacing "_Online_" with "_"
var NewName = docName.replace("_Online_", "_");
var saveFile = new File(docPath+'/'+NewName+ '.jpg');
//Save JPG
function SaveJPEG(saveFile, jpegQuality) {
jpgSaveOptions = new JPEGSaveOptions();
jpgSaveOptions.embedColorProfile = true;
jpgSaveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
jpgSaveOptions.matte = MatteType.NONE;
jpgSaveOptions.quality = jpegQuality; //1-12
activeDocument.saveAs(saveFile, jpgSaveOptions, true,Extension.LOWERCASE);
}
The Script runs through but therewithout errors but nothing happens. It would be very helpful if someone could tell me what Ive done wrong. Hope someone helps me figuring out how to fix this ;)
I use this:
function saveAsJPG() {
jpgFile = new File(outputFolder + "/" + _CardFileName + ".jpg");
jpgSaveOptions = new JPEGSaveOptions();
jpgSaveOptions.embedColorProfile = true;
jpgSaveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
jpgSaveOptions.matte = MatteType.NONE;
jpgSaveOptions.quality = 12;
docRef.saveAs(jpgFile, jpgSaveOptions, true, Extension.LOWERCASE);
}
Try to use forward slashes in your docPath:
var docPath="C:/Users/user/Desktop/test";
\t (tab) and \u (beginning of a Unicode sequence) have special meanings in JS strings.
Or you can escape them, of course:
var docPath="C:\\Users\\user\\Desktop\\test";
The best way to write paths in javascript for photoshop automation is '/c/users/user/' That works on both mac and windows and you don't need to escape the backslashes

Quicker searching in JScript using the Bash

I am using the following JScript code to search for a string inside a file:
var myFile = aqFile.OpenTextFile(fileToSearchIn, aqFile.faRead, aqFile.ctANSI);
while(!myFile.IsEndOfFile())
{
s = myFile.ReadLine();
if (aqString.Find(s, searchString) != -1)
Log.Checkpoint(searchString + " found.", s);
}
myFile.Close();
This is rather slow. I was thinking about using bash commands in order to speed up the search in file process:
var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec("C:\\cygwin\\bin\\bash.exe -c 'cat \"" + folderName + "/" + fileName + "\"'");
while (!oExec.StdOut.AtEndOfStream)
Log.Checkpoint(oExec.StdOut.ReadLine());
while (!oExec.StdErr.AtEndOfStream)
Log.Error(oExec.StdErr.ReadLine());
Since every time bash.exe is started a new window opens the searching is not faster than before. Is there a possibility to have the bash run in the background using another switch?
Every invocation of WshShell.Exec will start a new process which is costly. If your textfile is not too big this will prevent spawning a new process:
var myFile = aqFile.OpenTextFile(fileToSearchIn, aqFile.faRead, aqFile.ctANSI);
var myFileData = myFile.Read(myFile.Size);
var index = myFileData.indexOf(searchString);
if(index>0)
{
Log.Checkpoint(searchString + " found.", index);
}
myFile.Close();
This will not print the whole line but the index of the found location. If you want the whole line, search for line endings from there.

Categories