Alfresco : Non-Administrator users cannot turn a site into moderate mode - javascript

I've got an issue on the Share part of my Alfresco application.
Indeed, when I'm logged in under a normal account (not administrator) and I go to a created site that dont have his "Moderate" option checked, I've got an error message each time I want to modify the site's details and check the moderate option.
The error message is the following :
04110011 Wrapped Exception (with status template): 04110169 Failed to execute script 'classpath*:alfresco/templates/webscripts/org/alfresco/repository/site/site.put.json.js': 04110168 Access denied. You don't have the permission to perform this operation.
The problem never occurs when the site has already been created under the "moderate" option or when your logged in under the administrator account.
Here you have the console log :
ERROR [extensions.webscripts.AbstractRuntime] Exception from executeScript - redirecting to status template error: 04110001 Wrapped Exception (with status template): 04110097 Failed to execute script 'classpath*:alfresco/templates/webscripts/org/alfresco/repository/site/site.put.json.js': 04110096 Access refusé. Vous n'avez pas la permission de réaliser cette opération.
org.springframework.extensions.webscripts.WebScriptException: 04110001 Wrapped Exception (with status template): 04110097 Failed to execute script 'classpath*:alfresco/templates/webscripts/org/alfresco/repository/site/site.put.json.js': 04110096 Access refusé. Vous n'avez pas la permission de réaliser cette opération.
at org.springframework.extensions.webscripts.AbstractWebScript.createStatusException(AbstractWebScript.java:758)
at org.springframework.extensions.webscripts.DeclarativeWebScript.execute(DeclarativeWebScript.java:171)
at org.alfresco.repo.web.scripts.RepositoryContainer$2.execute(RepositoryContainer.java:383)
at org.alfresco.repo.transaction.RetryingTransactionHelper.doInTransaction(RetryingTransactionHelper.java:381)
at org.alfresco.repo.web.scripts.RepositoryContainer.transactionedExecute(RepositoryContainer.java:436)
at org.alfresco.repo.web.scripts.RepositoryContainer.transactionedExecuteAs(RepositoryContainer.java:466)
at org.alfresco.repo.web.scripts.RepositoryContainer.executeScript(RepositoryContainer.java:304)
at org.springframework.extensions.webscripts.AbstractRuntime.executeScript(AbstractRuntime.java:333)
at org.springframework.extensions.webscripts.AbstractRuntime.executeScript(AbstractRuntime.java:189)
at org.springframework.extensions.webscripts.servlet.WebScriptServlet.service(WebScriptServlet.java:118)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.alfresco.web.app.servlet.GlobalLocalizationFilter.doFilter(GlobalLocalizationFilter.java:58)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Unknown Source)
Caused by: org.alfresco.scripts.ScriptException: 04110097 Failed to execute script 'classpath*:alfresco/templates/webscripts/org/alfresco/repository/site/site.put.json.js': 04110096 Access refusé. Vous n'avez pas la permission de réaliser cette opération.
at org.alfresco.repo.jscript.RhinoScriptProcessor.execute(RhinoScriptProcessor.java:194)
at org.alfresco.repo.processor.ScriptServiceImpl.executeScript(ScriptServiceImpl.java:282)
at org.alfresco.repo.web.scripts.RepositoryScriptProcessor.executeScript(RepositoryScriptProcessor.java:102)
at org.springframework.extensions.webscripts.AbstractWebScript.executeScript(AbstractWebScript.java:981)
at org.springframework.extensions.webscripts.DeclarativeWebScript.execute(DeclarativeWebScript.java:86)
... 24 more
Caused by: org.alfresco.repo.security.permissions.AccessDeniedException: 04110096 Access refusé. Vous n'avez pas la permission de réaliser cette opération.
at org.alfresco.repo.security.permissions.impl.ExceptionTranslatorMethodInterceptor.invoke(ExceptionTranslatorMethodInterceptor.java:48)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.alfresco.repo.audit.AuditMethodInterceptor.proceedWithAudit(AuditMethodInterceptor.java:217)
at org.alfresco.repo.audit.AuditMethodInterceptor.proceed(AuditMethodInterceptor.java:184)
at org.alfresco.repo.audit.AuditMethodInterceptor.invoke(AuditMethodInterceptor.java:137)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:107)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy53.setPermission(Unknown Source)
at org.alfresco.repo.site.SiteServiceImpl.setModeratedPermissions(SiteServiceImpl.java:1680)
at org.alfresco.repo.site.SiteServiceImpl.updateSite(SiteServiceImpl.java:1068)
at org.alfresco.repo.site.script.Site.save(Site.java:279)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.mozilla.javascript.MemberBox.invoke(MemberBox.java:155)
at org.mozilla.javascript.NativeJavaMethod.call(NativeJavaMethod.java:243)
at org.mozilla.javascript.optimizer.OptRuntime.callProp0(OptRuntime.java:119)
at org.mozilla.javascript.gen.c44._c11(file:/C:/workspace_starter/Tomcat/home/tomcat/webapps/alfresco/WEB-INF/classes/alfresco/templates/webscripts/org/alfresco/repository/site/site.put.json.js:337)
at org.mozilla.javascript.gen.c44.call(file:/C:/workspace_starter/Tomcat/home/tomcat/webapps/alfresco/WEB-INF/classes/alfresco/templates/webscripts/org/alfresco/repository/site/site.put.json.js)
at org.mozilla.javascript.optimizer.OptRuntime.callName0(OptRuntime.java:108)
at org.mozilla.javascript.gen.c44._c0(file:/C:/workspace_starter/Tomcat/home/tomcat/webapps/alfresco/WEB-INF/classes/alfresco/templates/webscripts/org/alfresco/repository/site/site.put.json.js:366)
at org.mozilla.javascript.gen.c44.call(file:/C:/workspace_starter/Tomcat/home/tomcat/webapps/alfresco/WEB-INF/classes/alfresco/templates/webscripts/org/alfresco/repository/site/site.put.json.js)
at org.mozilla.javascript.ContextFactory.doTopCall(ContextFactory.java:393)
at org.mozilla.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:2834)
at org.mozilla.javascript.gen.c44.call(file:/C:/workspace_starter/Tomcat/home/tomcat/webapps/alfresco/WEB-INF/classes/alfresco/templates/webscripts/org/alfresco/repository/site/site.put.json.js)
at org.mozilla.javascript.gen.c44.exec(file:/C:/workspace_starter/Tomcat/home/tomcat/webapps/alfresco/WEB-INF/classes/alfresco/templates/webscripts/org/alfresco/repository/site/site.put.json.js)
at org.alfresco.repo.jscript.RhinoScriptProcessor.executeScriptImpl(RhinoScriptProcessor.java:472)
at org.alfresco.repo.jscript.RhinoScriptProcessor.execute(RhinoScriptProcessor.java:190)
... 28 more
Caused by: net.sf.acegisecurity.AccessDeniedException: Access is denied.
at net.sf.acegisecurity.vote.AffirmativeBased.decide(AffirmativeBased.java:86)
at net.sf.acegisecurity.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:394)
at net.sf.acegisecurity.intercept.method.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:77)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.alfresco.repo.security.permissions.impl.ExceptionTranslatorMethodInterceptor.invoke(ExceptionTranslatorMethodInterceptor.java:44)
... 58 more
The error come from the "site.put.json.js" webscript, that contains the following source code :
<import resource="classpath:alfresco/module/customAlfrescoAMP/javascript/tsUtils.js">
<import resource="classpath:alfresco/module/customAlfrescoAMP/javascript/ts-constants.js">
function main()
{
// Get the site
var shortName = url.extension;
var site = siteService.getSite(shortName);
if (site != null)
{
// Updafte the sites details
if (json.has("title") == true)
{
site.title = json.get("title");
}
if (json.has("description") == true)
{
site.description = json.get("description");
}
// Use the visibility flag before the isPublic flag
if (json.has("visibility") == true)
{
site.visibility = json.get("visibility");
}
else if (json.has("isPublic") == true)
{
// Deal with deprecated isPublic flag accordingly
var isPublic = json.getBoolean("isPublic");
if (isPublic == true)
{
site.visibility = siteService.PUBLIC_SITE;
}
else
{
site.visibility = siteService.PRIVATE_SITE;
}
}
//début modif T&S
if (!site.node.hasAspect("st:siteType"))
{
site.node.addAspect("st:siteType");
}
var siteType = "";
if (json.has("type") == true)
{
siteType = json.get("type");
}
var assocs = site.node.assocs["st:siteTypeAssoc"];
if (assocs != null && assocs.length == 1) {
site.node.removeAssociation(assocs[0], "st:siteTypeAssoc");
assocs[0].remove();
}
var siteTypeNode = site.node.createNode(null, "cm:content");
siteTypeNode.content = siteType;
site.node.createAssociation(siteTypeNode, "st:siteTypeAssoc");
var siteiconNodeRef = null;
if (json.has("siteiconNodeRef"))
{
siteiconNodeRef = json.get("siteiconNodeRef");
}
if (siteiconNodeRef != null && siteiconNodeRef != "")
{
var image = search.findNode(siteiconNodeRef);
// ensure cm:person has 'cm:preferences' aspect applied - as we want to add the avatar as
// the child node of the 'cm:preferenceImage' association
if (!site.node.hasAspect("st:siteIcon"))
{
site.node.addAspect("st:siteIcon");
}
// remove old image child node if we already have one
var assocs = site.node.assocs["st:siteIconAssoc"];
if (assocs != null && assocs.length == 1)
{
site.node.removeAssociation(assocs[0], "st:siteIconAssoc");
//no need to remove the image ?
//assocs[0].remove();
}
//images are created in userhome, move them to the site
image.move(site.node);
site.node.createAssociation(image, "st:siteIconAssoc");
}
//fin modif T&S
// Save the site
site.save();
var members = site.listMembers(null, null, 0);
var templateNodeRef = search.luceneSearch( "#\\{http\\://www.alfresco.org/model/content/1.0\\}name:\"edit-site-mail.ftl\"")[0].nodeRef;
for (username in members)
{
/*var mail = actions.create("mail");
mail.parameters.to_many = users;
mail.parameters.subject = EDIT_SITE_MAIL_SUBJECT + site.title;
mail.parameters.template = templateNodeRef;
mail.execute(site.node);
*/
createAndSendHtmlMail(site.node, EDIT_SITE_MAIL_SUBJECT + site.title, people.getPerson(username).properties["cm:email"], "", templateNodeRef, null);
}
// Pass the model to the template
model.site = site;
}
else
{
// Return 404
status.setCode(status.STATUS_NOT_FOUND, "Site " + shortName + " does not exist");
return;
}
}
main();
So, if you have any suggestion...

Related

Creating a bat file to download a program and I can't find the issue

Says the url is wrong but it seems right to me.
I'm trying to download a file from the internet launch the program, then after the process ends to delete the program.
Any help would be great
process will be
start exe ---> to create the simple downloader ---> add parameters via bat file ---> launch the file -----> wait for the process to end -----> delete the files downloaded.
I have yet to add the wait process and delete commands
#if (#X)==(#Y) #end /****** jscript comment ******
#echo off
::::::::::::::::::::::::::::::::::::
::: compile the script ::::
::::::::::::::::::::::::::::::::::::
setlocal
if exist simpledownloader.exe goto :skip_compilation
set "frm=%SystemRoot%\Microsoft.NET\Framework\"
:: searching the latest installed .net framework
for /f "tokens=* delims=" %%v in ('dir /b /s /a:d /o:-n "%SystemRoot%\Microsoft.NET\Framework\v*"') do (
if exist "%%v\jsc.exe" (
rem :: the javascript.net compiler
set "jsc=%%~dpsnfxv\jsc.exe"
goto :break_loop
)
)
echo jsc.exe not found && exit /b 0
:break_loop
call %jsc% /nologo /out:"simpledownloader.exe" "%~dpsfnx0"
::::::::::::::::::::::::::::::::::::
::: end of compilation ::::
::::::::::::::::::::::::::::::::::::
:skip_compilation
:: download the file
::
::::::::::
:: simpledownloader.exe "%%~1" "%%~2"
simpledownloader.exe "https://download.splashtop.com/sos/SplashtopSOS.exe" sos.exe
sos.exe
:: del /q simpledownloader.exe
::
::::::::
::
exit /b 0
****** end of jscript comment ******/
import System;
var arguments:String[] = Environment.GetCommandLineArgs();
var webClient:System.Net.WebClient = new System.Net.WebClient();
print("Downloading " + arguments[1] + " to " + arguments[2]);
try {
webClient.DownloadFile(arguments[1], arguments[2]);
} catch (e) {
Console.BackgroundColor = ConsoleColor.Green;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n\nProblem with downloading " + arguments[1] + " to " + arguments[2] + "Check if the internet address is valid");
Console.ResetColor();
Environment.Exit(5);
}
I think I found something for you I made some adjustments for you.
Happy scripting!
#echo off
IF EXIST sos.exe goto delete
IF NOT EXIST sos.exe goto skip
:delete
echo delete
del /f sos.exe
timeout 5
:skip
echo skip
rem :: the first argument is the script name as it will be used for proper help message
cscript //E:JScript //nologo "%~f0" "%~nx0" %*
start sos.exe
exit /b %errorlevel%
#if (#X)==(#Y) #end JScript comment */
// global variables and constants
var ARGS = WScript.Arguments;
var scriptName=ARGS.Item(0);
var url="";
var saveTo="";
var user=0;
var pass=0;
var proxy=0;
var bypass="";
var proxy_user=0;
var proxy_pass=0;
var certificate=0;
var force=true;
//ActiveX objects
//Use the right version of MSXML
/*var progIDs = [ 'Msxml2.DOMDocument.6.0', 'Msxml2.DOMDocument.5.0', 'Msxml2.DOMDocument.4.0', 'Msxml2.DOMDocument.3.0', 'Msxml2.DOMDocument' ]
for (var i = 0; i < progIDs.length; i++) {
try {
var XMLHTTPObj = new ActiveXObject(progIDs[i]);
}catch (ex) {
}
}
if typeof XMLHTTPObj === 'undefined'{
WScript.Echo ("You are using too ancient windows or you have no installed IE");
WScript.Quit(1);
}*/
var XMLHTTPObj = new ActiveXObject("MSXML2.XMLHTTP");
var FileSystemObj = new ActiveXObject("Scripting.FileSystemObject");
var AdoDBObj = new ActiveXObject("ADODB.Stream");
function existsItem(path){
return FileSystemObj.FolderExists(path)||FileSystemObj.FileExists(path);
}
stripTrailingSlash = function(path){
while (path.substr(path.length - 1,path.length) == '\\') {
path=path.substr(0, path.length - 1);
}
return path;
}
function deleteItem(path){
if (FileSystemObj.FileExists(path)){
FileSystemObj.DeleteFile(path);
return true;
} else if (FileSystemObj.FolderExists(path) ) {
FileSystemObj.DeleteFolder(stripTrailingSlash(path));
return true;
} else {
return false;
}
}
function writeFile(fileName,data ){
AdoDBObj.Type = 1;
AdoDBObj.Open();
AdoDBObj.Position=0;
AdoDBObj.Write(data);
AdoDBObj.SaveToFile(fileName,2);
AdoDBObj.Close();
}
function download( url,file){
if (force && existsItem(file)){
if(!deleteItem(file)){
WScript.Echo("Unable to delete "+ file);
WScript.Quit(8);
}
}else if (existsItem(file)){
WScript.Echo("Item " + file + " already exist");
WScript.Quit(9);
}
if (proxy!=0 && bypass !="") {
//https://msdn.microsoft.com/en-us/library/ms760236(v=vs.85).aspx
XMLHTTPObj.setProxy(SXH_PROXY_SET_DIRECT,proxy,bypass);
} else if (proxy!=0) {
XMLHTTPObj.setProxy(SXH_PROXY_SET_DIRECT,proxy,"");
}
if (proxy_user!=0 && proxy_pass!=0 ) {
//https://msdn.microsoft.com/en-us/library/ms763680(v=vs.85).aspx
XMLHTTPObj.setProxyCredentials(proxy_user,proxy_pass);
}
if(certificate!=0) {
//https://msdn.microsoft.com/en-us/library/ms763811(v=vs.85).aspx
WinHTTPObj.setOption(3,certificate);
}
if (user!=0 && pass!=0){
//https://msdn.microsoft.com/en-us/library/ms757849(v=vs.85).aspx
XMLHTTPObj.Open('GET',url,false,user,pass);
} else {
XMLHTTPObj.Open('GET',url,false);
}
XMLHTTPObj.Send();
var status=XMLHTTPObj.Status;
switch(status){
case 200:
WScript.Echo("Status: 200 OK");
break;
case 401:
WScript.Echo("Status: 401 Unauthorized");
WScript.Echo("Check if correct user and password were provided");
WScript.Quit(401);
break;
case 407:
WScript.Echo("Status:407 Proxy Authentication Required");
WScript.Echo("Check if correct proxy user and password were provided");
WScript.Quit(407);
break;
default:
WScript.Echo("Status: "+status);
WScript.Echo("Try to help yourself -> https://en.wikipedia.org/wiki/List_of_HTTP_status_codes");
WScript.Quit(status);
}
writeFile(file,XMLHTTPObj.ResponseBody);
}
function main(){
url="https://download.splashtop.com/sos/SplashtopSOS.exe"
saveTo="sos.exe";
download(url,saveTo);
}

Uncaught ReferenceError: web3 is not defined at window.onload

I'm trying to get my first dapp working; I know I'm close, but keep running into a problem with web3.
I am working on Windows 10, running a testrpc node via PowerShell. I used truffle to set up my folders & sample files, then compile and migrate.
I don't think I changed anything from the app.js file built by truffle... here is that code:
var accounts;
var account;
function setStatus(message) {
var status = document.getElementById("status");
status.innerHTML = message;
};
function refreshBalance() {
var meta = MetaCoin.deployed();
meta.getBalance.call(account, {from: account}).then(function(value) {
var balance_element = document.getElementById("balance");
balance_element.innerHTML = value.valueOf();
}).catch(function(e) {
console.log(e);
setStatus("Error getting balance; see log.");
});
};
function calcPremium() {
var premium = parseInt(document.getElementById("benefit").value)/10000;
document.getElementById("monthlyPremium").innerHTML = " Monthly Premium: $"+premium.toFixed(2);
};
function sendCoin() {
var meta = MetaCoin.deployed();
var amount = parseInt(document.getElementById("monthlyPremium").value);
var receiver = document.getElementById("receiver").value;
setStatus("Initiating transaction... (please wait)");
meta.sendCoin(receiver, amount, {from: account}).then(function() {
setStatus("Transaction complete!");
refreshBalance();
}).catch(function(e) {
console.log(e);
setStatus("Error sending coin; see log.");
});
};
window.onload = function() {
web3.eth.getAccounts(function(err, accs) {
if (err != null) {
alert("There was an error fetching your accounts.");
return;
}
if (accs.length == 0) {
alert("Couldn't get any accounts! Make sure your Ethereum client is configured correctly.");
return;
}
accounts = accs;
account = accounts[0];
refreshBalance();
});
}
I'm able to open the html file in a Chrome browser, with the MetaMask plugin enabled. However, it seems I'm unable to interact with the contracts in any way, due to the web3 error issue. The exact message is this post's subject line.
Thanks in advance for any help or guidance!
Could you please try it and see . I think the onload is giving the issue.
$(window).load function() {
web3.eth.getAccounts(function(err,accs) {
if (err != null) {
alert("There was an error fetching your accounts.");
return;
}
if (accs.length == 0) {
alert("Couldn't get any accounts! Make sure your Ethereum client is configured correctly.");
return;
}
accounts = accs;
account = accounts[0];
refreshBalance();
});
}

Reusable code at checking status respose with Javascript

I'm using Angular in Javascript to connect to the server, What I want to do is make reusable code.
The problem if that for each service that have to obtain data from server I have to know status response and if was 200 I have to know if the success was 1 or 0.
So... This is my code at today (using promise):
function obtenerUltimasOperacionesComplejo() {
return $http
.get(ultimasOperacionesUrl,
{params: {idComplejo: 11}})
.then(obtenerDatosUltimasOperaciones)
.catch(generarError);
}
function obtenerDatosUltimasOperaciones(data) {
var mensaje = '';
var status = data.status;
if(status == 401){
mensaje = 'Acceso no autorizado.';
return $q.reject(mensaje);
}
else if (status <> 200){
mensaje = 'Ups! Hubo un problema al conectarse al servidor. Intente nuevamente.';
return $q.reject(mensaje);
}
else if(status == 200){
var exito = data.data.success;
if(exito == 0){
mensaje = data.data.mensaje;
return $q.reject(mensaje);
}
else if(exito == 1){
ultimasOperaciones = data.data.ultimasOperaciones;
return ultimasOperaciones;
}
}
}
function generarError(e){
var newMessage = 'XHR error! :';
if (e.data && e.data.description) {
newMessage = newMessage + '\n' + e.data.description;
}
e.data.description = newMessage;
logger.error(newMessage);
return $q.reject('Ups! Hubo un problema al conectarse al servidor. Intente nuevamente');
}
This part of code:
if(status == 401){
mensaje = 'Acceso no autorizado.';
return $q.reject(mensaje);
}
else if (status <> 200){
mensaje = 'Ups! Hubo un problema al conectarse al servidor. Intente nuevamente.';
return $q.reject(mensaje);
}
else if(status == 200){
var exito = data.data.success;
if(exito == 0){
mensaje = data.data.mensaje;
return $q.reject(mensaje);
}
...
I have to use it for each service that I have...
The problem that I have is that I can't put in a function the code above, because I don't know how to set the variable with the corresponding service, I mean:
else if(exito == 1){
ultimasOperaciones = data.data.ultimasOperaciones;
return ultimasOperaciones;
}
This part of code changes for each service because "ultimasOperaciones" var is for this service in particular, for another service I have to use another variable and so on...
So... There is a way to disjoin this two part of code so I can reuse and don't have to copy and paste the most of the code?
Thanks!
please create a interceptor for checking every time the status of your response
http://thecodebarbarian.com/2015/01/24/angularjs-interceptors

How can I return the path of a screenshot capture to a function and return via JSON to javascript?

I have a PHP script that invokes a casperjs script via exec function and this is working fine.
Is it possible to return the path where I saved a screenshot via exec as JSON?
My scripts are below:
PHP code:
// Execute to CasperJS via asynchronous process
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$target = $_POST['target'];
$filename = $_POST['file'];
$retorno = array()
try {
exec("{$casperjs_run} {$script} {$username} {$password} {$filename} 2>&1", $output);
} catch (Exception $e) {
$retorno['error404'] = "Desculpe! Não foi possivel acessar a página solicitada.";
}
// Return Data if success
// Retorna para front-end
if (empty($output)){
$retorno['success'] = $output;
echo json_encode($retorno);
return false;
} else {
$retorno['error'] = $output;
echo json_encode($retorno);
return false;
}
?>
CasperJS code:
casper.thenOpen(minhaoi, function myaccount() {
this.capture('pic2.png');
this.log('Acessando informações da conta, aguarde...');
if (!this.exists(('div.panel-horizontal'))) {
this.log(JSON.stringify("Não foi encontrado um plano colaborador, aguarde..."));
noDetails = this.captureSelector(filename + '.png', 'div.panel-horizontal', {quality: 100});
} else {
casper.waitForResource("Análise de Conta", function orderDetails(details) {
return details;
}, function onReceive() {
this.log('ScreenShot Begin');
myDetails = this.captureSelector(path_images + filename + '.png', '#content', { quality: 100 } );
this.log(' ScreenShot Done'); });
});
}
});
// Logout & Exit
casper.eachThen(oi_out, function () {
this.capture('pic3.png');
if (noDetails != "") {
return noDetails;
} else {
return myDetails;
}).run();
Here my JS code that receive the information from casperjs via JSON.
Javascript Code:
success: function(data) {
if (data.success) {
$('#retorno').html(data.success);
$('#imagem').attr('src', '/details/' + filename);
$('#resultado').show();
}
},
error: function(data) {
// check error
$('#retorno').attr("class='alert alert-danger' role='alert'");
$('#retorno').html(data.error);
}
In my mind filename should be the whole name of the screenshot like this, pi9rxw2fqlh.png plus the complete path too. And display the image in the browser.
What's wrong in my approach?
For this.log to actually print something, you need to set the logLevel to at least debug as it is the default log level. So either increase the log level casper.options.logLevel = 'debug'; or use this.echo instead of this.log.
It looks like you're using waitForResource wrong. Since there can't be resources with spaces in them, you might want to checkout waitForText under the assumption that the loaded resource adds that string to the DOM:
casper.waitForText("Análise de Conta", function onReceive() {
this.log('ScreenShot Begin');
myDetails = this.captureSelector(path_images + filename + '.png', '#content', { quality: 100 } );
this.log(' ScreenShot Done'); });
});
capture as well as captureSelector return the casper instance and not the image details. So you need to pass the filename.
Since you use php's exec with the output array, you can casper.echo the filename in question with a unique beginning string (here #noDetails#):
this.captureSelector(filename + '.png', 'div.panel-horizontal', {quality: 100});
this.echo("#noDetails#" + filename + ".png");
In the client javascript you can then iterate over the data.success or data.error arrays and extract the filename from the match line:
data.success.forEach(function(line){
if (line.indexOf("#noDetails#") === 0) {
var filename = line.split("#noDetails#")[1];
$('#imagem').attr('src', '/details/' + filename);
}
});
With this, you can completely remove the if block from the eachThen callback.
The other option is to set the specific screenshot variable and write the JSON object in the last line.
this.captureSelector(filename + '.png', 'div.panel-horizontal', {quality: 100});
noDetails = filename + ".png";
and at the end:
casper.eachThen(oi_out, function () {
this.capture('pic3.png');
if (noDetails != "") {
this.echo(JSON.stringify({filename:noDetails}));
} else {
this.echo(JSON.stringify({filename:myDetails}));
}
});
On the client side, you would need to only look in the last line of the array:
var obj = JSON.parse(data.success[data.success.length-1]);
$('#imagem').attr('src', '/details/' + obj.filename);

XEP-0077 In-band registration with Strophe.js and openfire usage

I'm trying to register a new user on openfire server with the strophe plugin but it doesn't connect for the registration. The description here https://github.com/metajack/strophejs-plugins/tree/master/register doesn't bring me any further :( Do I have to establish a connection before? This is what I try when clicking a button to register:
$("#RegButton").click(function () {
var callback = function (status) {
if (status === Strophe.Status.REGISTER) {
connection.register.fields.username = "juliet";
connection.register.fields.password = "R0m30";
connection.register.submit();
} else if (status === Strophe.Status.REGISTERED) {
console.log("registered!");
connection.authenticate();
} else if (status === Strophe.Status.CONNECTED) {
console.log("logged in!");
} else {
// every other status a connection.connect would receive
}
};
connection.register.connect("http://localhost:7070/http-bind/", callback);
});
On this line:
connection.register.connect("http://localhost:7070/http-bind/", callback);
connection should be a Strophe.Connection object already created with your service URL ("http://localhost:7070/http-bind/").
The first parameter to connection.register.connect() is the host that you want to register an account on. That is, for a JID of user#example.com you would set it to "example.com", not "http://localhost:7070/http-bind/" as in your code.
in my case I modified the plugin, because in line 215
"if(register.length === 0)", always end my intent for register, so I commented these lines and removed a tag "x" than brings in my stanza and the register was posible.
I hope this help you.
/*
if (register.length === 0) {
console.log('En tra if de linea 220');
//that._changeConnectStatus(Strophe.Status.REGIFAIL, null);
//return;
} else */
this.enabled = true;

Categories

Resources