Get Javascript object stored in file, into php variable - javascript

I have a Switches.js javascript file, like this:
//GLOBAL switches
//Change the values accordingly
var SWITCHES = {
uber: true, //Uber
social: true, //Social media pulgins
g_charts: true, //Google Charts
g_captcha: true, //Google Captcha
g_analytics: true, //Google Analytics
data_base: true, //Inserts user input data into DataBase
print: true, //Print option
pdf: true, //Download PDF report option
https: true //true for https, false for http
};
This JS file is stored in my server.
Is there a way to get that object and one of those properties into a php variable? I think that should be around the php functions file_get_contents and json_decode, but how do I take into account the comments in the JS file and that variable SWITCHES in particular?
$file_content = file_get_contents("Switches.js");
//some stuff
$http_switch = $SWITCHES[https];
AJAX nor jQuery are an option because this is to be run purely server side.

Since the Switches.js is JavaScript and not JSON, you can't use json_decode(). Instead you should convert it to JSON and decode/parse it both client-side and server-side:
In PHP, you'd do:
$data = file_get_contents("Switches.json");
$switches = json_decode($data);
And then client-side you fetch it via AJAX and parse:
$.get("/Switches.json", function (data) {
var switches = JSON.parse(data)
})
Your Switches.json file would then be (JSON files must not have comments):
{
"uber": true,
"social": true,
"g_charts": true,
"g_captcha": true,
"g_analytics": true,
"data_base": true,
"print": true,
"pdf": true,
"https": true
}

Related

How to make loop function using multiple input value to JSL in Groovy

I'm using the below function in Jenkins Shared Library.
/* The below function delete uploads that exist in the server. */
def delete_upload(server_url,each_upload_id,authentication){
def delete_upload_url = server_url + "/api/v1/uploads/" + each_upload_id
def response = httpRequest consoleLogResponseBody: true,
contentType: 'APPLICATION_JSON',
customHeaders: [[maskValue: false, name: 'id ', value: each_upload_id],
[maskValue: false, name: 'Authorization', value: authentication]],
httpMode: 'DELETE', ignoreSslErrors: true, responseHandle: 'NONE', url: delete_upload_url,
validResponseCodes: '100:599'
if(response.status == 202){
def result = readJSON text: """${response.content}"""
return result['message'].toString()
}
else {
throw new Exception("Incorrect upload id! Please give the correct upload id.")
}
}
====================================================================================================
I'm getting below response,
Response Code: HTTP/1.1 202 Accepted
Response:
{"code":202,"message":"Delete Job for file with id 2","type":"INFO"}
Success: Status code 202 is in the accepted range: 100:599
====================================================================================================
Purpose: I'm using the above JSL function to delete a uploads in the web server using upload id.
Requirement:
I need to delete multiple uploads by using multiple upload id's (like each_upload_id in 1,2,3 etc) using this JSL delete function.
Need to pass the upload id's in loops and delete the uploads in the web server.
Any suggestions, please ?
Are you looking for something like this?
def idList = ["1", "2", "3"]
try {
idList.each{ id =>
delete_upload(server_url,id,authentication)
}
} catch(e) {
println "Error occurred!"
}

How to upload data like images, PDFs and excel files in DevExtreme File Manager?

I have an app in which I want to show the replica of the google drive folder structure in my app. I can get data from google drive via its API. But I do struggle in uploading that data to the FileManager library of DevExtreme. Also how to send the data obtained from backend via an AJAX request (POST|GET).
The file obtained from the API:
from pydrive2.auth import GoogleAuth
from pydrive2.drive import GoogleDrive
gauth = GoogleAuth()
gauth.LoadCredentialsFile("mycreds.txt")
if gauth.credentials is None:
# Authenticate if they're not there
gauth.LocalWebserverAuth()
elif gauth.access_token_expired:
# Refresh them if expired
gauth.Refresh()
else:
# Initialize the saved creds
gauth.Authorize()
# Save the current credentials to a file
gauth.SaveCredentialsFile("mycreds.txt")
img = drive.CreateFile({'id': file_id})
img.GetContentFile('sample.jpg')
Code for creating the file manager from Javascript:
data = [
{
name: "MyFile.jpg",
size: 1024,
dateModified: "2019/05/08",
thumbnail: "/thumbnails/images/jpeg.ico",
isDirectory: true,
items: [
// ...
// Nested data objects with the same structure
// ...
]
}
]
new DevExpress.ui.dxFileManager(document.getElementById("file-manager"), {
"fileSystemProvider": data,
"itemView": {
"mode": "thumbnails"
},
"permissions": {
"copy": true,
"create": true,
"delete": true,
"download": true,
"move": true,
"rename": true,
"upload": true
},
"rootFolderName": "PayUP",
"rtlEnabled": false,
"currentPath": path,
onSelectionChanged: function (e) {
console.log(e)
}
});
The thing I want is how to add the downloaded image in data above from Django backend via ajax to client side.
This is the DevExtreme File Manager

Unable to save Ms Teams connnector

I am unable to save a really simple connector in Ms Teams.
The connector I made is a part of an app, which only wraps this connector.
As Ms suggests, I use ngrok for my endpoints (config page). (I also tried it with a real URL too with the same result.)
I can successfully include the configuration page while adding the connector to my team, but when I press the save button, it almost always fails. (55 failed, once was OK. But why !!??!!)
The script I am using:
microsoftTeams.initialize();
microsoftTeams.settings.setSettings({
entityId: "sampleConfig24",
configName: "sampleConfig3",
contentUrl: "https://35e61433.ngrok.io/motivosity/msteams/config.xhtml"
});
microsoftTeams.settings.setValidityState(true);
microsoftTeams.settings.registerOnSaveHandler(function(saveEvent) {
console.log("saving....");
// microsoftTeams.settings.getSettings( function(s) {
// console.log(s);
// });
console.log("saved");
saveEvent.notifySuccess();
});
The browser console contains:
saving....
saved
{
"seq": 1587628706303,
"timestamp": 1587631139034,
"flightSettings": {
"Name": "ConnectorFrontEndSettings",
"AriaSDKToken": "d127f72a3abd41c9b9dd94faca947689-d58285e6-3a68-4cab-a458-37b9d9761d35-7033",
"SPAEnabled": true,
"ClassificationFilterEnabled": true,
"ClientRoutingEnabled": true,
"EnableYammerGroupOption": true,
"EnableFadeMessage": false,
"EnableDomainBasedOwaConnectorList": false,
"EnableDomainBasedTeamsConnectorList": false,
"DevPortalSPAEnabled": true,
"ShowHomeNavigationButtonOnConfigurationPage": false,
"DisableConnectToO365InlineDeleteFeedbackPage": true
},
"status": 500,
"clientType": "SkypeSpaces",
"connectorType": "b87e49ce-e49a-4b42-895d-faf86b21d74a",
"name": "handleMessageError"
}
This error message has no understandable part. Anyone knows what is this?
I also noticed, that when opening the connector page, I also see this message in the console (before pressing the save button:)
"AppsService: getInstalledAppForTeam - Invalid teamId and/or appId specified"

Using the node.js google cloud speech to text, how can I get the status of a current job?

I managed to trigger a job with:
const config = {
languageCode: 'en-US',
enableSpeakerDiarization: true,
audioChannelCount: 2,
enableSeparateRecognitionPerChannel: true,
useEnhanced: true,
profanityFilter: false,
enableAutomaticPunctuation: true,
};
const audio = {
uri: `gs://${filePath}`
}
const requestObj = {
config: config,
audio: audio
}
return speechClient.longRunningRecognize(requestObj)
I get back an object with a name. I want to use that with https://cloud.google.com/speech-to-text/docs/reference/rest/v1/LongRunningRecognizeMetadata (via the node.js package) to get the current status.
How do I do it?
return speechClient.longrunning.Operation()
Seems not to exist
Looks like you can do it with:
return speechClient.operationsClient.getOperation({ name: googleName })
This is not super well documented

Jquery : Post Request is breaking while uploading multiple images

I am using Plupload js plugin to upload multiple images in one request. This plugin is working like if someone adding 5 images at a time then post request will go 5 times to upload each of images separately. As we know Post request require unique csrf token but in my case due to same token after one time, post request is failing.
Here is my code ...
<c:set var="csrfTokenVal"><csrf:token-value uri="<%=request.getRequestURI()%>"/></c:set>
<script>
var csrftokenV="${csrfTokenVal}";
$("#uploader").plupload({
// General settings
runtimes : 'html5,flash,silverlight,html4',
url:'/view/SurgeryNotesComponentController?uploadSurgeryImage=true&'+csrftokenN+'='+csrftokenV,
// User can upload no more then 20 files in one go (sets multiple_queues to false)
max_file_count: 10,
chunk_size: '1mb',
// Resize images on clientside if we can
resize : {
width : 600,
height : 610,
quality : 90,
//crop: true // crop to exact dimensions
},
filters : {
// Maximum file size
max_file_size : '1mb',
// Specify what files to browse for
mime_types: [
{title : "Image files", extensions : "jpg,gif,png"},
{title : "Zip files", extensions : "zip"}
]
},
// Rename files by clicking on their titles
rename: true,
// Sort files
sortable: true,
// Enable ability to drag'n'drop files onto the widget (currently only HTML5 supports that)
dragdrop: true,
// Views to activate
views: {
list: true,
thumbs: false, // Show thumbs
active: 'thumbs'
},
init: {
FilesAdded: function(up, files) {
$("#uploader_filelist").show();
},
FileUploaded: function(up, file, info, res) {
var imageObjectArray=$.parseJSON(info.response);
for(i=0;i<imageObjectArray.objectList.length; i++){
$('#showfilelist ul').append("<li><a class='delIcon-image' href='#delete' id='delSurgeryImageIcon'></a><a id=" + imageObjectArray.objectList[i].uid + " class='cboxElement imguid' href='${contextPath}/view/SurgeryNotesComponentController?surgeryImage=true&"+csrftokenN+ "="+ csrftokenV+"&attachmentLocation="+imageObjectArray.objectList[i].attachmentLocation+"' target='_blank'><img src='${contextPath}/view/SurgeryNotesComponentController?surgeryImage=true&"+csrftokenN+ "="+ csrftokenV+"&attachmentLocation="+imageObjectArray.objectList[i].attachmentLocation+"' border='0'>"+"</a> <strong>"+noteAddedMsg+"</strong><span class='image-created'>"+imageObjectArray.objectList[i].formattedDate+" "+byMsg+" "+imageObjectArray.objectList[i].userName+" </span></li>");
}
$("#uploader_filelist").empty().hide();
_SPINE.colorboxOverlay.coloboxPopup();
_SPINE.surgeryNotes.deleteImages();
$(".plupload_done .plupload_file_thumb").removeClass("hide")
},
ChunkUploaded: function (up, file, response) {
response = $.parseJSON(response.response || "null");
if (response.chunk == 3) {
up.stop();
up.start();
}
console.log(file.loaded);
}
},
// Flash settings
flash_swf_url : '${siteAssetsUrl}/assets/spine/js/external/Moxie.swf',
// Silverlight settings../assets/js
silverlight_xap_url : '${siteAssetsUrl}/assets/spine/js/external/Moxie.xap'
});
</script>
Here you can see I am generating scrf token (csrftokenV) and sending it in url to make it post supported.
Now the problem is if I am uploading more than 1 images (lets say 3), then 3 time post request will go. Each time i will get same csrf token and after uploaing first image, furthure images will not work and i will get this exception ....
WARNING: potential cross-site request forgery (CSRF) attack thwarted (user:<anonymous>, ip:127.0.0.1, uri:/**/image, error:request token does not match session token)
Please help me to solve this problem. Thanks
Finally One of my friend had solved the issue. It can't be possible to handle this issue through client side script so we leverage the power of Java. We had updated the csrfToken based on new request and sent it out with response.
Here is a solution ..
private String updateToken(HttpServletRequest request)
{
final HttpSession session = request.getSession(false);
CsrfGuard csrfGuard = CsrfGuard.getInstance();
csrfGuard.updateTokens(request);
String newToken=(String) session.getAttribute(REQUEST_TOKEN);
return newToken;
}
Setting newToken in response ...
response.setResult(this.updateToken(request));
return response;
Now we can change the url in beforeUpload event and set new token in the url.
BeforeUpload: function(up, file)
{
up.settings.url='/view/SurgeryNotesComponentController?uploadSurgeryImage=true&'+csrftokenN+'='+tokenRefresh
}
FileUploaded: function(up, file, info, res)
{
var imageObjectArray=$.parseJSON(info.response);
tokenRefresh=imageObjectArray.result;
}

Categories