Can't Post facebook URL using facebook SDK - facebook

I have a webapplication that I use to reshare existing post as follow
1)get the post details using https://graph.facebook.com/UserID_postID?access_token=AAA (works fine)
2)fill the a data of the new post from the old one and try to resend it but there is some strange behviour
if I use
oldpost.link = newpost.link it doesnt nothing appear on the wall but if I used
oldpost.link="\""newpost.link+"\"" works and the post appear on facebook wall but the link appears corputted as invalid.invalid/
function getPost(userID, postID, token) {
jQuery.getJSON("https://graph.facebook.com/" + userID + "_" + postID + "?access_token=" + token, function (post) {
here is the code any idea please
var newPost = {};
newPost.message = "hi";
if (post.link != "" && post.link != null && post.link != "undefined") {
newPost.link = "\"" + post.link + "\"";
}
if (post.name != "" && post.name != null && post.name != "undefined") {
newPost.name = "\"" + post.name + "\"";
}
if (post.picture != "" && post.picture != null && post.picture != "undefined") {
newPost.picture = "\"" + post.picture + "\"";
}
if (post.description != "" && post.description != null && post.description != "undefined") {
newPost.description = "\"" + post.description + "\"";
}
doPost(newPost);
});
}
function doPost(newPost) {
FB.api('/me/feed', 'post',
newPost, function (response) {
if (!response || response.error) {
alert(' Denied Access');
} else {
alert('Success');
}
});
}

Related

Canvas not updating after camera used (Android / Ionic)

I am trying to draw a scaled photo onto a canvas. However, the canvas will not update after I use the camera object to take the photo. Here's my camera code:
public openCamera() {
// do we have permission to access the camera?
this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.CAMERA).then(
result => console.log('openCamera > has camera permission: ', result.hasPermission),
err => this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.CAMERA)
);
this.androidPermissions.requestPermissions([this.androidPermissions.PERMISSION.CAMERA, this.androidPermissions.PERMISSION.GET_ACCOUNTS]);
const options: CameraOptions = {
quality: 100,
correctOrientation: true,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
let file_ext: string = null;
if (options.encodingType == EncodingType.JPEG) {
file_ext = "jpg";
console.log("openCamera > file_ext: ", file_ext);
}
else if (options.encodingType == EncodingType.PNG) {
file_ext = "png";
console.log("openCamera > file_ext: ", file_ext);
}
else {
this.presentAlert("Warning", "Unsupported image encoding type.");
return;
}
// photo already taken?
if (this.photo == null) {
this.photo = new Photo();
this.photo.id = Guid.create().toString();
this.photo.file_extension = file_ext;
}
// image filename: image_id.jpg
const dt: Date = new Date();
let dt_day: string = dt.getDate().toString();
dt_day = dt_day.length == 1 ? "0" + dt_day : dt_day;
let dt_month: string = (dt.getMonth() + 1).toString();
dt_month = dt_month.length == 1 ? "0" + dt_month : dt_month;
const dt_string: string = dt_day + "/" +
dt_month + "/" +
dt.getFullYear() + ", " +
dt.getHours() + ":" +
dt.getMinutes() + ":" +
dt.getSeconds() + "." +
dt.getMilliseconds();
if (this.photo.id == null || this.photo.id == '' || this.photo.id.length == 0) {
this.presentAlert("Error", "image id not set");
return;
}
else if (this.user.id == null || this.user.id == Guid.EMPTY || this.user.id == '' || this.user.id.length == 0) {
this.presentAlert("Error", "user.id not set");
return;
}
else if (dt_string == null || dt_string == '' || dt_string.length == 0) {
this.presentAlert("Error", "dt_string not set");
return;
}
this.photo.taken = dt_string;
const fileName: string = this.photo.id + ".jpg";
this.camera.getPicture(options).then((imageData) => {
// delete previous image
this.filePath.resolveNativePath(imageData)
.then((path) => {
let imagePath = path.substr(0, path.lastIndexOf("/") + 1);
let imageName = path.substring(path.lastIndexOf("/") + 1, path.length);
this.file.moveFile(imagePath, imageName, this.file.dataDirectory, fileName)
.then(newFile => {
this.ngZone.run(() => this.info = "Tap 'Upload' to upload photo");
this.db.addOrUpdatePhoto(this.photo)
.then(() => this.updateCanvas());
})
.catch(err => {
console.log("openCamera: ", err);
})
})
.catch((err) => {
console.log("openCamera: ", err);
})
})
.catch((err) => {
console.log("openCamera: ", err);
});
}
In the process of debugging this, I wrote a method to check that the photo actually exists after the camera has saved the image:
public exists() {
try {
this.file.listDir(this.file.dataDirectory, '')
.then(files => {
for (let i = 0; i < files.length; i++) {
if (files[i].name.includes(this.photo.id)) {
files[i].getMetadata((metadata) => {
this.presentAlert("image found", "filename: " + files[i].name + ", size: " + metadata.size + " bytes")
.then(() => this.updateCanvas());
});
}
}
});
}
catch { }
}
And I noticed that displaying an ionic alert before calling updateCanvas causes the photo to be correctly displayed onto the canvas. Does anyone know what the issue might be here?
Also, not sure if relevant, but I am using cordova-plugin-ionic-webview 4.1.1
I managed to solve this - the problem was the device itself. I tested on another phone and my canvas code worked perfectly. Uninstalling my app and reinstalling it did not resolve the issue, but a factory reset did. The device in question is an Honor 10 Lite. Not sure how this could have happened, maybe the device's WebView became corrupt somehow?

Facebook follow button does not display error message?

I'm using this https://developers.facebook.com/docs/plugins/follow-button and it's working fine. But what if I enter a facebook url that doesn't exist? It doesn't display any error message and just disappears. I want to display an error message when the user enters a wrong URL. Following is my code:
function wpfollow_func() {
var checkURL = jQuery("#profileCheck").hasClass("has-error");
if (!checkURL) {
var faces = jQuery('#facey').is(':checked');
var layout = jQuery('input[name=layout]:checked').val();
var url = jQuery('#profile').val();
if (url == '' || url == null) {
url = 'https://www.facebook.com/zuck';
}
var token = url.indexOf('http://');
if (token == -1) {
token = url.indexOf('https://');
}
if (token == -1) {
url = 'http://' + url;
}
var data = '<div class="fb-follow" data-href="' + url + '" data-layout="' + layout + '" data-show-faces="' + faces + '"></div>';
console.log(data);
jQuery('.fb-button').html(data);
FB.XFBML.parse();
return false;
}
I hope this is what you are looking for:
FB.XFBML.parse(document.getElementById('some_element'), function() {
alert('I rendered');
});
Following url may help you:
https://developers.facebook.com/docs/reference/javascript/FB.XFBML.parse

How to pass parameters to a MobileFirst HTTP adapter

I need to run an HTTP adapter to access a SOAP WSDL service. It has 2 fields userid and password.
I have auto generated the adapter by discover backend services. Can anyone guide me to how to pass values from adapter initially to access the service?
function userlogin_ep_process(params, headers){
var soapEnvNS = '';
soapEnvNS = 'http://schemas.xmlsoap.org/soap/envelope/';
var mappings = {
roots: {
'process': { nsPrefix: 'client', type: 'client:process' }
},
types: {
'client:process': {
children: [
{'username': { nsPrefix: 'client' }},
{'userpwd': { nsPrefix: 'client' }}
]
}
}
};
var namespaces = 'xmlns:client="http://xmlns.oracle.com/InternetMobile/AbsManagement/BPELProcessUserLogin" xmlns:plnk="http://docs.oasis-open.org/wsbpel/2.0/plnktype" ';
var request = buildBody(params, namespaces, mappings, soapEnvNS);
var soapAction = 'process';
return invokeWebService(request, headers, soapAction);
}
function buildBody(params, namespaces, mappings, soapEnvNS){
var body =
'<soap:Envelope xmlns:soap="' + soapEnvNS + '">\n' +
'<soap:Body>\n';
var fixedParams = {};
for (var paramName in params) {
if (mappings['roots'][paramName]) { //There is mapping for this param
var root = mappings['roots'][paramName];
var name = paramName;
if (root['nsPrefix'])
name = root['nsPrefix'] + ':' + paramName;
fixedParams[name] = handleMappings(params[paramName], root['type'], mappings['types']);
}
else {
fixedParams[paramName] = params[paramName];
}
}
body = jsonToXml(fixedParams, body, namespaces);
body +=
'</soap:Body>\n' +
'</soap:Envelope>\n';
return body;
}
function handleMappings(jsonObj, type, mappings) {
var fixedObj = {};
var typeMap = mappings[type]['children']; //Get the object that defines the mappings for the specific type
// loop through the types and see if there is an input param defined
for(var i = 0; i < typeMap.length; i++) {
var childType = typeMap[i];
for(var key in childType) {
if(jsonObj[key] !== null) { // input param exists
var childName = key;
if (childType[key]['nsPrefix'])
childName = childType[key]['nsPrefix'] + ':' + key;
if (!childType[key]['type']) //Simple type element
fixedObj[childName] = jsonObj[key];
else if (typeof jsonObj[key] === 'object' && jsonObj[key].length != undefined) { //Array of complex type elements
fixedObj[childName] = [];
for (var i=0; i<jsonObj[key].length; i++)
fixedObj[childName][i] = handleMappings(jsonObj[key][i], childType[key]['type'], mappings);
}
else if (typeof jsonObj[key] === 'object') //Complex type element
fixedObj[childName] = handleMappings(jsonObj[key], childType[key]['type'], mappings);
else if (childType[key]['type'] == '#') //Attribute
fixedObj['#' + childName] = jsonObj[key];
}
}
}
return fixedObj;
}
function getAttributes(jsonObj) {
var attrStr = '';
for(var attr in jsonObj) {
if (attr.charAt(0) == '#') {
var val = jsonObj[attr];
attrStr += ' ' + attr.substring(1);
attrStr += '="' + xmlEscape(val) + '"';
}
}
return attrStr;
}
function jsonToXml(jsonObj, xmlStr, namespaces) {
var toAppend = '';
for(var attr in jsonObj) {
if (attr.charAt(0) != '#') {
var val = jsonObj[attr];
if (typeof val === 'object' && val.length != undefined) {
for(var i=0; i<val.length; i++) {
toAppend += "<" + attr + getAttributes(val[i]);
if (namespaces != null)
toAppend += ' ' + namespaces;
toAppend += ">\n";
toAppend = jsonToXml(val[i], toAppend);
toAppend += "</" + attr + ">\n";
}
}
else {
toAppend += "<" + attr;
if (typeof val === 'object') {
toAppend += getAttributes(val);
if (namespaces != null)
toAppend += ' ' + namespaces;
toAppend += ">\n";
toAppend = jsonToXml(val, toAppend);
}
else {
toAppend += ">" + xmlEscape(val);
}
toAppend += "</" + attr + ">\n";
}
}
}
return xmlStr += toAppend;
}
function invokeWebService(body, headers, soapAction){
var input = {
method : 'post',
returnedContentType : 'xml',
path : '/soa-infra/services/Mobile/AbsManagement/userlogin_ep',
body: {
content : body.toString(),
contentType : 'text/xml; charset=utf-8'
}
};
//Adding custom HTTP headers if they were provided as parameter to the procedure call
//Always add header for SOAP action
headers = headers || {};
if (soapAction != 'null')
headers.SOAPAction = soapAction;
input['headers'] = headers;
return WL.Server.invokeHttp(input);
}
function xmlEscape(obj) {
if(typeof obj !== 'string') {
return obj;
}
return obj.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, '&apos;')
.replace(/</g, '<')
.replace(/>/g, '>');
}
To invoke the adapter and pass the parameters you need to call WL.Client.invokeProcedure in your particular case you can use
var invocationData = {
adapter: 'YOUR_ADAPTER_NAME',
procedure: 'userlogin_ep_process',
parameters: {
process: {
username: 'YOUR_USERNAME',
userpwd: 'YOUR_PASSWORD'
}
}
};
WL.Client.invokeProcedure(invocationData, {
onSuccess: yourSuccessFunction,
onFailure: yourFailureFunction
});

How do you append text in CodeMirror

I know you use
editor.setValue("");
to set one value but how do you append in CodeMirror?
IE:
editor.appendText();?
Use replaceRange. For example editor.replaceRange(myString, CodeMirror.Pos(editor.lastLine())). Re-setting the entire editor is needlessly expensive.
Here is a little script I wrote to add code to any editor (in Joomla):
function addCodeToEditor(code_string, editor_id, merge, merge_target){
if (Joomla.editors.instances.hasOwnProperty(editor_id)) {
var old_code_string = Joomla.editors.instances[editor_id].getValue();
if (merge && old_code_string.length > 0) {
// make sure not to load the same string twice
if (old_code_string.indexOf(code_string) == -1) {
if ('prepend' === merge_target) {
var _string = code_string + "\n\n" + old_code_string;
} else if (merge_target && 'append' !== merge_target) {
var old_code_array = old_code_string.split(merge_target);
if (old_code_array.length > 1) {
var _string = old_code_array.shift() + "\n\n" + code_string + "\n\n" + merge_target + old_code_array.join(merge_target);
} else {
var _string = code_string + "\n\n" + merge_target + old_code_array.join('');
}
} else {
var _string = old_code_string + "\n\n" + code_string;
}
Joomla.editors.instances[editor_id].setValue(_string.trim());
return true;
}
} else {
Joomla.editors.instances[editor_id].setValue(code_string.trim());
return true;
}
} else {
var old_code_string = jQuery('textarea#'+editor_id).val();
if (merge && old_code_string.length > 0) {
// make sure not to load the same string twice
if (old_code_string.indexOf(code_string) == -1) {
if ('prepend' === merge_target) {
var _string = code_string + "\n\n" + old_code_string;
} else if (merge_target && 'append' !== merge_target) {
var old_code_array = old_code_string.split(merge_target);
if (old_code_array.length > 1) {
var _string = old_code_array.shift() + "\n\n" + code_string + "\n\n" + merge_target + old_code_array.join(merge_target);
} else {
var _string = code_string + "\n\n" + merge_target + old_code_array.join('');
}
} else {
var _string = old_code_string + "\n\n" + code_string;
}
jQuery('textarea#'+editor_id).val(_string.trim());
return true;
}
} else {
jQuery('textarea#'+editor_id).val(code_string.trim());
return true;
}
}
return false;
}
The advantage it this script is you can work with multiple editors on the page.

Copy MongoDb indexes between databases

I am trying to copy mongo indexes between two environments. Checked the API and found no direct method of doing it. So I started writing a script that connects to one db, iterates over the collections, grabs indexes, mutates them (because getIndexes() and ensureIndex()) have different format), connects to the other db, wipes the indexes and copies the new ones in.
This all feels slightly over the top so I think that I must be missing something.
Any suggestions/good practices? Apart from having an index creation strategy.
Cheers!
Please run it on the database that you want to copy indexes.
db.getCollectionNames().forEach(function(collection) {
indexes = db[collection].getIndexes();
indexes.forEach(function (c) {
opt = ''
ixkey = JSON.stringify(c.key, null, 1).replace(/(\r\n|\n|\r)/gm,"")
ns = c.ns.substr(c.ns.indexOf(".") + 1, c.ns.length)
for (var key in c) {
if (key != 'key' && key != 'ns' && key != 'v') {
if (opt != '') { opt+= ','}
if (c.hasOwnProperty(key)) {
if (typeof(c[key]) == "string") {
opt += (key + ': "' + c[key] + '"')
} else {
opt+= (key + ": " + c[key])
}
}
}
}
if (opt != '') { opt = '{' + opt + '}'}
print ('db.' + ns + '.ensureIndex(' + ixkey + ','+ opt + ')')
})});
I've updated script of Adamo Tonete
db.getCollectionNames().forEach(function(col) {
var indexes = db[col].getIndexes();
indexes.forEach(function (c) {
var fields = '', result = '', options = {};
for (var i in c) {
if (i == 'key') {
fields = c[i];
} else if (i == 'name' && c[i] == '_id_') {
return;
} else if (i != 'name' && i != 'v' && i != 'ns') {
options[i] = c[i];
}
}
var fields = JSON.stringify(fields);
var options = JSON.stringify(options);
if (options == '{}') {
result = "db." + col + ".createIndex(" + fields + "); ";
} else {
result = "db." + col + ".createIndex(" + fields + ", " + options + "); ";
}
result = result
.replace(/{"floatApprox":-1,"top":-1,"bottom":-1}/ig, '-1')
.replace(/{"floatApprox":(-?\d+)}/ig, '$1')
.replace(/\{"\$numberLong":"(-?\d+)"\}/ig, '$1');
print(result);
});
});
Try with this script:
var i, c,
co_name, co_new,
co_old, co_old_i,
_db = db.getSiblingDB('logs'),
_colls = ['activity.games', 'activity.session', 'activity.social', 'activity.store'];
for (i in _colls){
co_name = _colls[i];
co_old = _db[co_name];
co_old_i = co_old.getIndexes();
if(co_old.count() > 0){
co_old.renameCollection(co_name + '.old');
_db.createCollection(co_name);
co_new = _db[co_name];
for(c in co_old_i){
co_new.ensureIndex(co_old_i[c].key);
}
}
}
https://gist.github.com/alejandrobernardis/8261327
Regards,
A
Here is a version to recreate them all with options, and with the new createIndex command instead of ensureIndex (since mongoDB 3.0). With that, it's very easy to copy (recreate) all indexes from one DB to another.
function createIndex2( coll, keys, options ) {
var ret = db[coll].createIndex(keys, options)
if (ret.createdCollectionAutomatically) print( "Collection " + coll + " was created")
if (ret.errmsg || (ret.note != "all indexes already exist" && ret.ok != 1)) {
ret.coll = coll
ret.keys = keys
ret.options = options
print(tojson(ret))
} else {
//print( "Everything normal", JSON.stringify(ret))
}
}
db.getCollectionInfos().forEach(function(coll) {
//print( JSON.stringify( coll ))
if (coll.type === "collection" ) {
db[coll.name].getIndexes().forEach(function(index) {
if ("_id_" !== index.name) {
//print( JSON.stringify( index ))
var indexKey = index.key // save the key, and transform index into the "options"
delete index.key
delete index.ns // namespace - not necessary
delete index.v // not necessary
index.background = true // optional: force background to be true
//native version: print("db." + coll.name + ".createIndex(" + JSON.stringify(indexKey) + ", " + JSON.stringify(index) + ")");
// this gives much more debug info
print("createIndex2(\"" + coll.name + "\", " + JSON.stringify(indexKey) + ", " + JSON.stringify(index) + ")");
}
});
}
});
The result looks like that if using the "native" version, otherwise, it will display only errors:
db.dishes.createIndex({"submenu":1},
{"name":"submenu_1","ns":"dishly.dishes","background":true})
db.dishes.createIndex({"loc":"2dsphere"},
{"name":"loc_2dsphere","ns":"dishly.dishes","2dsphereIndexVersion":3,"background":true})
db.dishes.createIndex({"rs":-1},
{"name":"rs_-1","ns":"dishly.dishes","partialFilterExpression":{"rs":{"$gte":3}},"background":true})
db.dishes.createIndex({"loc":"2d","type":1,"status":1,"FSid":1,"rs":-1},
{"name":"loc_2d_type_1_status_1_rs_-1","ns":"dishly.dishes","background":true,"partialFilterExpression":{"rs":{"$gte":2}}})
db.dishes.createIndex({"_fts":"text","_ftsx":1,"loc.0":1,"loc.1":1,"rs":-1},
{"name":"d2_menu_submenu_text__loc__rs","ns":"dishly.dishes","background":true,"weights":{"d2":1,"menu":1,"submenu":1},"default_language":"english","language_override":"language","textIndexVersion":3})