use kiiObject to save user data - javascript

In my app, every KiiUser has one hash table of data. But I have some problems using KiiObject to save data and get it next time.
I want to create an KiiObject with a specific URI when user registers so every time he logins I can import it with
KiiObject.objectWithURI(<URI>)
Alternatively, how to use objectWithJSON().
I don't want to use kiiQuery if I can avoid, as there is only one object for each user.
Can anyone give me an example of code how to create this Kiiobject when user registers and how to edit it every time he logins ; or every time he edits it and saves.
that's some of my current code but i don't get always the saved data back (the saved hash table "data" undefined on the object)
function performRegistration() {
try {
var user = KiiUser.userWithUsername(<username>, <password>);
user.register({
success: function(Auser) {
var bucket = Auser.bucketWithName("data");
data = bucket.createObject();
data.set("data", {});
data.saveAllFields({
success: function(theObject) {
console.log("Object saved!");
theObject.refresh({success:function(obj){
data=obj;
[....
...Some Code here to edit the...
...data object and save it....
...]
Kii.logger("User registered: " + Auser);
}});
},
failure: function(theObject, errorString) {
console.log("Error saving object: " + errorString);
}
});
},
failure: function(theUser, anErrorString) {
alert("Unable to register: " + anErrorString);
Kii.logger("Unable to register user: " + anErrorString);
}
});
} catch (e) {
alert("Unable to register: " + e.message);
Kii.logger("Unable to register user: " + e.message);
}
}
// the user clicked the 'sign in' button
function performLogin() {
KiiUser.authenticate(<username>, <password>, {
success: function(Auser) {
user = Auser;
var bucket = user.bucketWithName("data"); // a KiiBucket
var query = KiiQuery.queryWithClause();
var queryCallbacks = {
success: function(queryPerformed, r, nextQuery) {
console.log(r.constructor.name,r);
r[0].refresh({success:function(obj){
data=obj;
if(data.get("data")==undefined){
data.set("data",{});
}
data.save({success:function(Sobj){
data=Sobj;
[...
...some data object manipilation then save it
...]
}});
}});
},
failure: function(queryPerformed, anErrorString) {
}
};
bucket.executeQuery(query, queryCallbacks);
},
// callback for failed registration
failure: function(theUser, anErrorString) {
alert("Unable to register: " + anErrorString);
Kii.logger("Unable to register user: " + anErrorString);
}
});
};
Kii.initializeWithSite(<...>, <...>, KiiSite.US);
[...
other code
...]

How about using KiiUser's custom fields?
It is described as "Manipulating the custom fields" in this page.
http://documentation.kii.com/en/guides/javascript/managing-users/user-attributes/
Check these links for detail of API:
http://documentation.kii.com/references/js/storage/latest/symbols/KiiUser.html#set
http://documentation.kii.com/references/js/storage/latest/symbols/KiiUser.html#get

Related

Change the output_mode when making saved search request using Splunk JS SDK

I use the following code to make a saved search request. I get the output as JSON_ROWS format. I would like to get the result in JSON or XML format. Where i can specify the expected output format in the request ?
// The saved search created earlier
var searchName = "test";
// Retrieve the saved search collection
var mySavedSearches = service.savedSearches();
mySavedSearches.init(service, {app:"-"});
mySavedSearches.fetch(function(err, mySavedSearches) {
// Retrieve the saved search that was created earlier
var mySavedSearch = mySavedSearches.item(searchName);
// Run the saved search and poll for completion
mySavedSearch.dispatch({"args.splunkCMD": searchCommand}, function(err, job) {
// Display the job's search ID
sails.log("SplunkController::executeGenericSplunkRequest() Job SID: ", job.sid);
// Poll the status of the search job
job.track({
period: 200
}, {
done: function(job) {
sails.log("SplunkController::executeGenericSplunkRequest() Splunk request completed!");
// Get 10 results and print them
job.results({
count: 10
}, function(err, results, job) {
sails.log("SplunkController::executeGenericSplunkRequest() results = " +JSON.stringify(results, null, 2));
callback(results);
});
},
failed: function(job) {
console.log("Job failed")
},
error: function(err) {
done(err);
}
});
});
});

Moxtra invite users to existing binder SSO

I am using the Moxtra JavaScript SDK to implement the timeline functionality in my app.
I want to create a central binder for my user groups and got everything working except the inviting of another of my users to a existing binder.
function getTimeline(access_token, binderID) {
var options = {
access_token: access_token,
binder_id: binderID,
iframe: true,
tagid4iframe: "container",
iframewidth: "920px",
iframeheight: "650px",
autostart_meet: true,
autostart_note: true,
extension: {"show_dialogs": {"meet_invite": true}},
start_timeline: function (event) {
alert("Timeline started session Id: " + event.session_id + " binder id: " + event.binder_id);
},
view_binder: function (event) {
alert("Binder switched session Id: " + event.session_id + " binder id: " + event.binder_id);
},
invite_member: function (event) {
var userID = UNIQUEUSERID
alert("Invite member into binder Id: " + event.binder_id);
console.log(Moxtra.baseUrl + "/" + event.binder_id + "/inviteuser");
var postData = {
"users": [
{
"user": {
"unique_id": userID
}
}
],
"message": "Custom message to join this conversation..."
};
$.ajax("https://api.moxtra.com/v1/" + event.binder_id + "/inviteuser", {
type: 'POST',
data: postData,
contentType: 'application/json',
crossDomain: true,
success: function (data) {
console.log(data);
}
});
},
start_meet: function (event) {
alert("Meet started session key: " + event.session_key + " session id: " + event.session_id);
},
end_meet: function (event) {
alert("Meet end event");
},
save_meet: function (event) {
alert("Meet saved on binder: " + event.binder_id);
},
start_note: function (event) {
alert("session key: " + event.session_key + " session id: " + event.session_id);
},
save_note: function (event) {
alert("Note saved on binder: " + event.destination_binder_id);
},
cancel_note: function (event) {
alert("Note cancelled");
},
error: function (event) {
alert("Timeline error code: " + event.error_code + " error message: " + event.error_message);
}
};
Moxtra.timeline(options);
}
as you can see the getTimeline request handles the invite_member event, there is no build in invite user to chat/binder so I can't use that.
Seeming that the SDK calls the REST API I am using that myself to add the invite user functionality. But when I test the request with their API console I get a error saying that the group is not found.
I assign the users to the same group so that shouldn't be the issue and tried to add a user via my unique-id and the moxtra unique-id. What am I doing wrong? Or what other options do I have?
I assume the binder that you are trying to add users (using their unique id) was also created by an user who got created in Moxtra using unique_id method. In that case using the REST API to add team member is the right approach to add additional users to the binder.
When you use the API console, you will be using the access token generated through your moxtra email account. It cannot be used with the binder that you created through the unique_id method.
Based on the error that you mentioned above it looks like either the user who you are trying to add or the user who created the binder are not in the same group. Please make sure both the users are provisioned using the same SSO method.

Going crazy with async calls in Titanium

After spend 6 hours trying different approaches to my problem, I always get the same error and can't figure out why.
The problem is simple to understand: I have 10 users saved in Appcelerator Titanium ACS and I want to create 10 records, one for each user.
The stuff must be easy: all users have the same pass, so I only need to login with each one, create the object as the user and, thats all!! (In ACS, the objects are owned (and have user_id assigned automatically) by the user who creates them).
To manage async, I use functions with callback to wait till the end.
var Cloud = require('ti.cloud');
function createObject(value, onComplete) {
Cloud.Objects.create({
classname: 'MyObj',
session_id: Cloud.sessionId,
fields: {
value: value
}
}, function(data) {
if (data.success) {
Ti.API.info('New value: user [' + data.Scores[0].user_id + '] - value: ' + data.Scores[0].value);
onComplete(true);
} else {
Ti.API.info('Error: ' + data.message);
onComplete(false);
}
});
}
function login(user, onComplete) {
Cloud.Users.login({
login: user.username,
password: '1234'
}, function(e) {
if (e.success) {
createObject(20, function(cb) {
onComplete(true);
});
} else {
Ti.API.warn('Error login user: ' + e.message);
onComplete(false);
}
});
}
// Get target users
Cloud.Users.query({
response_json_depth: 1
}, function(data) {
if (data.success) {
_.each(data.users, function(user) {
login(user, function(cb) {
Ti.API.warn("user: " + user.username);
});
});
}
});
Well, my results are always the same:
Ti.API.warn('user: ' + user.username); shows the right users name (one by one), but Ti.API.info('New value: user [' + data.Scores[0].user_id + '] - value: ' + data.Scores[0].value); shows always the same user, meaning that all the values are saved for the same user (checked in DB, are all the same user), instead of 1 value per user.
I also tried to use async in the _.each command, but with the same results.
Where is the problem? I think I'm waiting in _.each user for the login, and the login must wait to finish the createObject, but seems I'm doing something wrong.
And here the exit. No sense for me...:
New value: user [54cb62cf18beba0935422a35] - value: 20
user: krusty
New value: user [54cb62cf18beba0935422a35] - value: 20
user: apu
New value: user [54cb62cf18beba0935422a35] - value: 20
user: ned
Note: the user_id saved for all calls correspond to user NED (the last)
It was a bug in ACS. Anyway, it doesn't matters currently, because was fixed 5 years ago.

Alfresco: how to call share webscript from client js and extract JSON data

From client-side javascript I want to call a share-webscript which returns JSON data.
The response from getTicket.json.ftl looks like:
{
"ticket" : "TICKET_faf851d4a993b62c98908268af07876f09fa86c9"
}
So how can I call this share-webscript from my client-side javascript and extract the value of "ticket" ?
see answer below
Answer:
Alfresco.util.Ajax.jsonGet(
{
url: Alfresco.constants.PROXY_URI + "/auth/getTicket.json",
successCallback:
{
fn: function(response)
{
try {
var json = JSON.parse(response.serverResponse.responseText);
var ticket = json["ticket"];
if (ticket.substring(0, 6) == "TICKET") {
clipboardData.setData("Text", ticket + "&" + file.nodeRef);
location.href = Alfresco.constants.URL_RESCONTEXT + "components/javawebstart/AEF_JNLP.jnlp";
} else {
// handle unknown format
}
} catch (e) {
// handle error
}
},
scope: this
},
failureCallback:
{
fn: function(response)
{
// handle failure case
},
scope: this
}
});
This calles the share tier webscript. So you also need a share tier webscript which calls a repository web script which returns the actual ticket ...

How to pass initial arguments to javascript functions

I have some simple javascript functions to interact with an API like this one to login:
login: function(username, password) {
var calledUrl = baseapi + "user/login/" + credentials;
calledUrl.post(
function (content) {
/*console.log("success" + JSON.stringify(content, null, 4));*/
},
function (e) {
console.log("it failed! -> " + e);
},
{
"username": username,
"password": password
},
{"Accept" : "application/json"}
);
},
The problem is, in the URL I must pass some credentials and they look like that:
var credentials = "?api_username=" + api_username + "&api_key=" + api_key;
Right now this variable is hardcoded to make some tests but of course it should change for each person using the function. I don't want to ask for it with each request, in this case I only want to ask for username and password. I would like to ask for it once and for all during an initializing process or whatever it is called and then remember it when executing the various functions.
If .login() is the first method that typically needs the credentials, then you can just make it a required argument for that method and then store the credentials in the object:
login: function(username, password, credentials) {
// save credentials for use in other methods
this.credentials = credentials;
var calledUrl = baseapi + "user/login/" + credentials;
calledUrl.post(
function (content) {
/*console.log("success" + JSON.stringify(content, null, 4));*/
},
function (e) {
console.log("it failed! -> " + e);
},
{
"username": username,
"password": password
},
{"Accept" : "application/json"}
);
},
Then, in other methods, you can access the credentials for this user with this.credentials.
If there are other methods that could also be called first and need the credentials for them, then you can either make the credentials an argument for those also or you can create a .init() method that just establishes the credentials or you can make it an argument in the constructor for this object.
You will probably also have to fix this line:
calledUrl.post(...)
because calledUrl is a string and strings don't have a .post() method unless you're using some sort of 3rd party library that adds one.
I recommend that you read about scope in JavaScript. Without more explanation of what you are trying to do, I would try something like this pattern...
var app = {
baseapi: 'http://some.url.com'
/* assuming the api user/pass are different form the account trying to log in */
,api_username: ''
,api_key: ''
,username: ''
,userpass: ''
,get_creditialString: function() {
return '?api_username=' + this.api_username + '&api_key=' + this.api_key;
}
,init: function(){
// do something to prompt for username and password
this.username = 'myUserName';
this.userpass = 'supersecretpassword';
this.login();
}
,login: function() {
var calledUrl = this.baseapi + "user/login/" + this.get_credentialString();
calledUrl.post(
function (content) {
/*console.log("success" + JSON.stringify(content, null, 4));*/
},
function (e) {
console.log("it failed! -> " + e);
},
{
"username": this.username,
"password": this.userpass
},
{"Accept" : "application/json"}
);
}
}
app.init();

Categories