Renaming files in an Alfresco script - javascript

I am struggling to write a script in Alfresco to rename file extension.
The file is saved as filename.bin. I am using content rules to say when filename equals *bin rename to *pdf.
I am struggling a bit with the script and would appreciate any help.
My script is as below:
// change the name of this document
document.properties.name = document.properties.name+".pdf";
// add a new property string
document.properties["cm:locale"] = mylocalenode;
// save the property modifications
document.save();
but doesn't seem to get me anywhere.

The script as written would take a document named "filename.bin" and rename it to "filename.bin.pdf". It would then set a property called "cm:locale" equal to the value of mylocalenode, which appears to be
undefined in this snippet. I don't know what you are going for with the cm:locale so I will ignore that and give you a script that will search for the document named filename.bin and change its name.
If you would rather iterate over the children in a folder, you should be able to look at the Alfresco JavaScript API to figure out how to modify the snippet below to do that.
var results = search.luceneSearch("#cm\\:name:filename.bin");
var doc = results[0]; // assumes there is only one result, which may not be what you want
var oldName = doc.properties.name;
var newName = oldName.replace('.bin', '.pdf');
doc.properties.name = newName;
doc.save();

Adding more in this,as you are using content-rule.There is no need to search document using lucene/solr service .We can directly access document object,it refers to document on which your rule is being executed.
So the code will be like below.
var oldName = document.properties.name;
var newName = oldName.replace('.bin', '.pdf');
document.properties.name = newName;
document.save();

Related

Using an object as a lookup table: Values dont update after first call

I'm trying to implement a variable system for my html web pages. That's why I wrote a function that will take some string, search it for variables, replace them with their corresponding value and the give the new string back:
//Finish HTML files by replacing variables
handlers.insertVariables = function(file, callback){
//Load variables
let variables = require('./variables.js');
console.log(variables) //For debugging only
//Loop through all possible variables and replace
for(let key in variables){
if(variables.hasOwnProperty(key)){
let find = '{' + key + '}';
let replace = variables[key];
file = file.split(find).join(replace)
//file = file.replace('{' + key + '}', variables[key])
}
}
//Callback the new file
callback(false, file);
};
This part works without issues. Its also able to replace multiple instances of the same variable. The problem is now the external variables.js file. I made an external file for these as I will probably a few dozens of these in the future. This is the variable.js file:
//Container with all variables
let variables = {
'landing_videoID': global.newestVideo.id,
'landing_time': new Date(Date.now()).toUTCString()
};
//Export the variables
module.exports = variables;
When the handlers.insertVariables function gets called for the first time, it will receive the up-to-date values. But these then are not changing anymore. Is there something that I'm doing wrong, or is my attempt just bs in general?
Thanks for your help!
Module is cached after first require. One way to solve this problem is to export as function and call it every time as follows:
So, refactor variable.js as follows:
//Container with all variables
function getValues()
return {
'landing_videoID': global.newestVideo.id,
'landing_time': new Date(Date.now()).toUTCString()
};
}
//Export the variables
module.exports = getValues;
Then, require variable.js like this:
//Load variables
let variables = require('./variables.js')();

JSON.stringify in js

How do I get reference of the <div> id and title from a external JS by using the code below:
function recordedEvent() {
var v_Id = $(this).attr('Id');
var v_Title = $(this).attr('Title');
var o = { Title : v_Title, ObjectId : v_Id };
alert(JSON.stringify(o));
}
The function is called in the HTML with a onclick called box1().
Code in CplTemplateSetup.js is where I want to run the function from into the HTML:
content_left_30_four_click_images_right_70_head_content_template.html
Any help would be appreciated.
P.S.: JSON data (zip archive)
Well the most obvious problem is that you don't have a closing parenthesis after your callback.. otherwise the code looks good
Edit
window.lastClickedBoxData = {}; // just reassign that within your function
or
window.runThisWhenClicked = function () {
var v_Id = $(this).attr('Id');
var v_Title = $(this).attr('Title');
var o = { Title : v_Title, ObjectId : v_Id };
};
then just
$(".box").click(window.runThisWhenClicked);
I don't think that the problem that you're facing would be apparent to anyone who doesn't view your code.
You defined a function within a script tag, in the html, and called that function in the onclick attribute of the box being clicked on. To that function, this refers to the box that was clicked on. From there, you call a function within an external js document. In that function, this refers to the window object. In other words, for the code that you posted, $(this) is a jquery instance of the window object which doesn't have the attributes that you're looking for, such as id and title, so they're blank.
To see what I'm talking about open the console and add the following line of code to each of your functions:
console.log(this);
If you're having trouble doing that, the following code should work as well, but it's not as good for debugging:
alert(this);
You need all of your code to be in the html script tag or in the external document. Also, you shouldn't define the function to be called during a click event using onclick within the html. It's better to do it using javascript or jquery so that your javascript is completely separate from your html.
EDIT: You shouldn't update your question with an answer. You should edit the original question with this information so that anyone having a similar problem can find the solution. I'd have commented on the answer directly, but I don't have the reputation to do this.

initialise timezoneJS with JSON files

I'm working with timezone-js: https://github.com/mde/timezone-js. I have a list of predefined timezones I want to work with. So I pre-parsed JSON Data of those timezones.
But how exactly am I supposed to use this data?
var _tz = timezoneJS.timezone;
_tz.loadingScheme = _tz.loadingSchemes.MANUAL_LOAD;
_tz.loadZoneJSONData('/major_cities.json', true);
I can read the data, like here. But how am I supposed to use the tz variable to initialise timezoneJS?
I'm thinking that I'm supposed to do something like this first:
timezoneJS.timezone.loadZoneDataFromObject(_tz);
And then initialise it... And then initialise timezoneJS, but if I initialise now, I'll get an error that it can't find the default timezone: Uncaught Error: Error retrieving "null/northamerica" zoneinfo files, probably because I've supplied the json data.
Can I'd like to know what to do to use the json file, so I can create timezoneJS.Date objects.
First of all, tz_ is just a short cut which prevents writing timezoneJS.timezone in the subsequent lines.
Now, there are two options. If you have your file major_cities.json on the server and you want to initialize timezoneJS you just have to do what you wrote:
var _tz = timezoneJS.timezone;
_tz.loadingScheme = _tz.loadingSchemes.MANUAL_LOAD;
_tz.loadZoneJSONData('/major_cities.json', true);
and you're all set. The second option is that you have an object containing data from that file. In such case you should use loadZoneDataFromObject instead of loadZoneJSONData, namely:
var _tz = timezoneJS.timezone;
_tz.loadingScheme = _tz.loadingSchemes.MANUAL_LOAD;
_tz.loadZoneDataFromObject(majorCitiesObject);
After that, you should not try calling the init function, hence timezoneJS is already initialized by the loadZoneJSONData. If you want to create a date, just call new timezoneJS.Date(). The following lines should give you a hint:
var timezoneName = 'Europe/London';
var newDate = new timezoneJS.Date(timezoneName);
console.log(newDate.toString());
console.log(newDate.toISOString());
Result should be sth like:
2013-04-08 11:56:33
2013-04-08T10:56:33.019Z

Can javascript file get its own name?

I am trying to build some sort of logger functionality in javascript. Is there any API for a script to get its own filename?
This should work:
(new Error).fileName
Or you can try this:
var filepath;
(function(){
var scripts = document.getElementsByTagName('script');
filepath = scripts[ scripts.length-1 ].src;
}());
The second option gives you the path of your script file.
I see two ways:
put into every JS file a variable var filename = 'script.js';
get the filename using <script> tag name
JS can not get filename like bash/perl/c scripts.
If we can get the current script's tag, then we can read its src attribute. Excerpt from https://stackoverflow.com/a/22745553/4396817 below:
document.currentScript will return the element whose script is currently being processed.
<script>
var me = document.currentScript;
</script>
Benefits
Simple and explicit. Reliable.
Don't need to modify the script tag
Works with asynchronous scripts (defer & async)
Works with scripts inserted dynamically
Problems
Will not work in older browsers and IE.
...So from there, we can simply read the src attribute!
<script src="http://website.com/js/script.js">
alert(document.currentScript.src);
</script>
// Alerts "http://website.com/js/script.js"
Unfortunately this is not possible.
If you change your approach, getting function names may help you which is sometimes possible. Your best chance would be extracting function name from "arguments.callee". This only works if function is defined like
function FN() { ... }
And does not work when
var FN = function() { ... }
this is my modification that fixes a few possible issues, but adds a requirement.
It needs you to name the file in a certain way, so for example if you have a .js file, but you want to know which version is loaded (for example to tell a php server). so your js file would be "zoom_v34.js".
var version;
(function(){
var scripts = document.getElementsByTagName('script');
for (var i=0; i<scripts.length; i++) {
var start = scripts[i].src.indexOf('zoom_');
if (start != -1) { var end = scripts[i].src.indexOf('.',start); version = scripts[i].src.substr(start+6,end-start-6); break; }
}
}());
post='login{JS:'+version+'}';
You can try putting this at the top of your JavaScript file:
window.myJSFilename = "";
window.onerror = function(message, url, line) {
if (window.myJSFilename != "") return;
window.myJSFilename = url;
}
throw 1;
Make sure you have only functions below this. The myJSFilename global variable will contain the full path of the JavaScript file, and the filename can be parsed from that. Tested in IE11, but it should work elsewhere.

Pass vars to JavaScript via the SRC attribute

In my HTML file I have linked to the JS with:
src="myscript.js?config=true"
Can my JS directly read the value of this var like this?
alert (config);
This does not work, and the FireFox Error Console says "config is not defined". How do I read the vars passed via the src attribute in the JS file? Is it this simple?
<script>
var config=true;
</script>
<script src="myscript.js"></script>
You can't pass variables to JS the way you tried. SCRIPT tag does not create a Window object (which has a query string), and it is not server side code.
Yes, you can, but you need to know the exact script file name in the script :
var libFileName = 'myscript.js',
scripts = document.head.getElementsByTagName("script"),
i, j, src, parts, basePath, options = {};
for (i = 0; i < scripts.length; i++) {
src = scripts[i].src;
if (src.indexOf(libFileName) != -1) {
parts = src.split('?');
basePath = parts[0].replace(libFileName, '');
if (parts[1]) {
var opt = parts[1].split('&');
for (j = opt.length-1; j >= 0; --j) {
var pair = opt[j].split('=');
options[pair[0]] = pair[1];
}
}
break;
}
}
You have now an 'options' variable which has the arguments passed. I didn't test it, I changed it a little from http://code.google.com/p/canvas-text/source/browse/trunk/canvas.text.js where it works.
You might have seen this done, but really the JS file is being preprocessed server side using PHP or some other language first. The server side code will print/echo the javascript with the variables set. I've seen a scripted ad service do this before, and it made me look into seeing if it can be done with plain ol' js, but it can't.
You need to use Javascript to find the src attribute of the script and parse the variables after the '?'. Using the Prototype.js framework, it looks something like this:
var js = /myscript\.js(\?.*)?$/; // regex to match .js
var jsfile = $$('head script[src]').findAll(function(s) {
return s.src.match(js);
}).each(function(s) {
var path = s.src.replace(js, ''),
includes = s.src.match(/\?.*([a-z,]*)/);
config = (includes ? includes[1].split('=');
alert(config[1]); // should alert "true" ??
});
My Javascript/RegEx skills are rusty, but that's the general idea. Ripped straight from the scriptaculous.js file!
Your script can however locate its own script node and examine the src attribute and extract whatever information you like.
var scripts = document.getElementsByTagName ('script');
for (var s, i = scripts.length; i && (s = scripts[--i]);) {
if ((s = s.getAttribute ('src')) && (s = s.match (/^(.*)myscript.js(\?\s*(.+))?\s*/))) {
alert ("Parameter string : '" + s[3] + "'");
break;
}
}
Whether or not this SHOULD be done, is a fair question, but if you want to do it, http://feather.elektrum.org/book/src.html really shows how. Assuming your browser blocks when rendering script tags (currently true, but may not be future proof), the script in question is always the last script on the page up to that point.
Then using some framework and plugin like jQuery and http://plugins.jquery.com/project/parseQuery this becomes pretty trivial. Surprised there's not a plugin for it yet.
Somewhat related is John Resig's degrading script tags, but that runs code AFTER the external script, not as part of the initialization: http://ejohn.org/blog/degrading-script-tags/
Credits: Passing parameters to JavaScript files , Passing parameters to JavaScript files
Using global variables is not a so clean or safe solution, instead you can use the data-X attributes, it is cleaner and safer:
<script type="text/javascript" data-parameter_1="value_1" ... src="/js/myfile.js"></script>
From myfile.js you can access the data parameters, for instance with jQuery:
var parameter1 = $('script[src*="myfile.js"]').data('parameter_1');
Obviously "myfile.is" and "parameter_1" have to match in the 2 sources ;)
You can do that with a single line code:
new URL($('script').filter((a, b, c) => b.src.includes('myScript.js'))[0].src).searchParams.get("config")
It's simpler if you pass arguments without names, just like function calls.
In HTML:
<script src="abc.js" data-args="a,b"></script>
Then, in JavaScript:
const args=document.currentScript.dataset.args.split(',');
Now args contains the array ['a','b'].

Categories