How to call google calendar api service using appcelerator - titanium

I am looking for google calendar api services implementations using appcelerator. How to i will start calling google apis,not getting idea any one please help me.Advance thanks

Declare the network calls using the standard network process http://docs.appcelerator.com/platform/latest/#!/api/Titanium.Network.HTTPClient and use the google calendar API https://developers.google.com/google-apps/calendar/v3/reference/
e.g. Get Users calendars
var url = " https://www.googleapis.com/calendar/v3/users/me/calendarList";
var client = Ti.Network.createHTTPClient({
// function called when the response data is available
onload : function(e) {
Ti.API.info("users calendars: " + JSON.stringify(this.responseText));
alert('success');
},
// function called when an error occurs, including a timeout
onerror : function(e) {
Ti.API.debug(e.error);
alert('error');
},
timeout : 5000 // in milliseconds
});
// Prepare the connection.
client.open("GET", url);
// Send the request.
client.send();

Related

Anyone have a solution for generating server-side tokens for the ESRI JSAPI SDK?

There are a number of solutions to this:
use the build-in dialog provided by esri/IdentityManager (https://developers.arcgis.com/javascript/3/jsapi/identitymanagerbase-amd.html)
use a server-side proxy (https://github.com/Esri/resource-proxy)
use the identity manager initialize() method (https://developers.arcgis.com/javascript/3/jsapi/identitymanagerbase-amd.html#initialize)
But there what is missing is the ability to hook into the request for a token. I am working with ArcGISDynamicMapServiceLayer and there is no way to know if the server return a 498/499, and no way to update the url to update the token.
I started hacking around in the API to try to hook into various events with no real promise of success. What seems to be missing:
a way to detect when a token is needed
a way to update the token
Closes I came up with is listening for "dialog-create" but there is no way to disable the dialog apart from throwing an exception, which disables the layer.
I tried replacing the "_createLoginDialog" method and returning {open: true} as a trick to pause the layers until I had a token ready but since there is no way to update the layer endpoint I did not pursue this hack. It seems the only way this might work is to use the initialize() method on the identity manager.
Does anyone have knowledge of options beyond what I have outlined?
EDIT: The goal is to provide a single-sign-on experience to users of our product.
"User" is already signed in to our application
"User" wishes to access a secure ESRI ArcGIS Server MapServer or FeatureServer services from the ESRI JSAPI
"User" is prompted for user name and password
The desired flow is to acquire a token on the users behalf using a RESTful services in our product and return the appropriate token that will allow the "User" to access the secure services without being prompted.
I do not wish to use a proxy because I do not want all that traffic routed through the proxy.
I do not wish to use initialize() because it is complicated and not clear how that works apart for re-hydrating the credentials.
I do wish for an API that simply allows me to set the token on any layer services that report a 499 (missing token) or 498 (invalid token), but I cannot find any such API. The solution I am focusing on hinges on being able to update the url of an ArcGISImageServiceLayer instance with a new token.
This answer lacks in satisfaction but delivers on my requirements. I will start with the code (client-side typescript):
class TokenProxy {
private tokenAssuranceHash = {} as Dictionary<Promise<{ token: string, expiration: string }>>;
private service = new TokenService();
private timeoutHandle = 0;
watchLayer(esriLayer: ArcGISDynamicMapServiceLayer) {
setInterval(async () => {
const key = esriLayer._url.path;
const token = await this.tokenAssurance(key);
esriLayer._url.query.token = token;
}, 5000);
}
updateRefreshInterval(ticks: number) {
clearTimeout(this.timeoutHandle);
this.timeoutHandle = setTimeout(() => {
Object.keys(this.tokenAssuranceHash).forEach(url => {
this.tokenAssuranceHash[url] = this.service.getMapToken({serviceUrl: url});
});
this.updateRefreshInterval(ticks);
}, ticks);
}
async tokenAssurance(url: string) {
if (!this.tokenAssuranceHash[url]) {
this.tokenAssuranceHash[url] = this.service.getMapToken({serviceUrl: url});
}
try {
const response = await this.tokenAssuranceHash[url];
await this.recomputeRefreshInterval();
return response.token;
} catch (ex) {
console.error(ex, "could not acquire token");
return null;
}
}
async recomputeRefreshInterval() {
const keys = Object.keys(this.tokenAssuranceHash);
if (!keys.length) return;
const values = keys.map(k => this.tokenAssuranceHash[k]);
const tokens = await Promise.all(values);
const min = Math.min(...tokens.map(t => new Date(t.expiration).getTime()));
if (Number.isNaN(min)) return; // error occured, do not update the refresh interval
const nextRefreshInTicks = min - new Date().getTime();
this.updateRefreshInterval(0.90 * nextRefreshInTicks);
}
}
And highlight the hack that makes it work:
const key = esriLayer._url.path;
const token = await this.tokenAssurance(key);
esriLayer._url.query.token = token;
The "_url" is a hidden/private model that I should not be using to update the token but it works.

OpenTok - Subscriber failed to subscribe to a stream in a reasonable amount of time

I am implementing a Network Test for my Web-application using OpenTok's js library.
To do that, I create a publisher, connect to session, then make a subscriber connect to the publisher's stream.
The Test is working on other browsers (I have tested Chrome and Internet Explorer) but on Firefox version 57.0.1 I get an error - 'The stream was unable to connect due to a network error. Make sure you have a stable network connection and that it isn't blocked by a firewall.'
Make sure when you create the OpenTok Session you are using a 'routed' Session, not a 'relayed' one. Also make sure you are passing the 'testNetwork' property to the subscribe method. Here is a working sample:
// Sample code
var session = OT.initSession(APIKEY, SESSIONID);
session.connect(TOKEN, function(err) {
if (err) {
alert(err.message);
return;
}
var publisher = session.publish();
publisher.on('streamCreated', function(event) {
session.subscribe(event.stream, null, {
testNetwork: true
}, function(err) {
if (err) alert(err.message);
});
});
});
https://jsbin.com/quruzac/edit

Check if user is already logged in or or not in MFP V8.0

I have written an adapter procedure in MFP V8.0. This procedure is secured bu a security check. I want to check that user is already logged-in before calling this adapter procedure:
Procedure is mapped to scope as below:
<procedure name="searchData" scope="restrictedResource"/>
Security Check is defined as below:
<securityCheckDefinition name="UserValidationSecurityCheck" class="com.sample.UserValidationSecurityCheck">
I have done the the Scope Element mapping the server also.
I have written below method which calls the adapter method:
function callAdapterProcedure(invocationData){
var procedureName = invocationData.procedure;
var successHandler = invocationData.successHandler;
var failureHandler = invocationData.failureHandler;
var parameters = invocationData.parameters;
var isuserLoggedIn = checkForLoggedInUser();
alert('is logged in' + isuserLoggedIn);
if(isuserLoggedIn){
var dataRequest = new WLResourceRequest(getAdapterPath(procedureName), WLResourceRequest.GET);
dataRequest.setQueryParameter("params", [JSON.stringify(parameters)]);
dataRequest.send().then(successHandler,failureHandler);
}else{
hideProgressBar();
showAlert(Messages.ALERT_SESSION_TIME_OUT);
logoutWithoutConfirmation();
openLogin();
}
}
Below is the implementation of checkForLoggedInUser() method:
function checkForLoggedInUser(){
var userAlreadyLoggedIn = undefined;//WL.Client.isUserAuthenticated(mrmGlobal.realms.authenticationRealm,null);
WLAuthorizationManager.obtainAccessToken("restrictedResource").then(
function (accessToken) {
alert("obtainAccessToken onSuccess");
userAlreadyLoggedIn = true;
},
function (response) {
alert("obtainAccessToken onFailure: " + JSON.stringify(response));
userAlreadyLoggedIn = false;
});
return userAlreadyLoggedIn;
}
I know that WLAuthorizationManager.obtainAccessToken sends the asynchronous call to the server that's why userAlreadyLoggedIn is always coming as undefined. Is there any way through which I can check that the user session is not timed out before making the adapter call? Basically I want to implement something like WL.Client.isUserAuthenticated (which was there in earlier versions).
--Update--
Plus I have observed one more thing that the handlers method of WLAuthorizationManager.obtainAccessToken are also not getting called.
From your code:
WLAuthorizationManager.obtainAccessToken("restrictedResource").then(
function (accessToken) {
alert("obtainAccessToken onSuccess");
userAlreadyLoggedIn = true;
},
function (response) {
alert("obtainAccessToken onFailure: " + JSON.stringify(response));
userAlreadyLoggedIn = false;
});
It is a common misconception to think that obtainAccessToken's onFailure means the user is not logged in. But that's not exactly how it works.
When you call obtainAccessToken, there are 3 possible outcomes:
Success: The user is logged in, and obtainAccessToken onSuccess is called (along with the challenge handler's success method).
Challenge: The user is not logged in, the security check sent a challenge to the client. This challenge will be received by your challenge handler. obtain will remain on hold until you answer the challenge. This is probably what happens in your case, this would not explain why none of the obtain's handlers are being called.
Failure: Something went wrong during the authentication. It could be that the server is down, networking issue, the scope does not exist, or the user is blocked, etc. In this case, obtainAccessToken's onFailure will be called.
There currently is no API to check if a scope is granted without triggering a challenge. I have opened an internal feature request, feel free to submit your own (https://www.ibm.com/developerworks/rfe ).
In the meantime you could add your own internal boolean flag, that you set to true whenever you login and false whenever you logout.

AWS Cognito - Encountering Error Converting Circular Structure to JSON

I am trying to setup Cognito UnAuthenticated creds for users coming to my site. However, I am encountering "Error Converting Circular Structure to JSON" after the user id is assigned from Cognito and I am calling the synchronize method on the Sync Manager... please see the code below..
Any help in resolving this is greatly appreciated
// Initialize the Amazon Cognito credentials provider
AWS.config.region = 'us-east-1'; // Region
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: 'us-east-1:my-id-pool-id'
});
function getMeACognito() {
AWS.config.credentials.get(function(){
var syncClient = new AWS.CognitoSyncManager();
syncClient.openOrCreateDataset('yaHeardPrefs', function(err, dataset) {
dataset.put('userPrefs', 'samplePrefs', function(err, record){
if(err)
{
console.log('(Sync error)Received error while saving prefs = ' + err);
}
dataset.synchronize({
onSuccess: function(data, newRecords) {
console.log('success');
},
onFailure: function(err){
console.log('Error while sync = ' + err);
},
onConflict: function(err) {
console.log('error / conflict = ' + err);
}
});
});
});
});
}
and the error i am getting is -
aws-sdk-2.3.15.min.js:25 Uncaught TypeError: Converting circular structure to JSON
Note that I do understand what a circular structure conversion error in JSON is based on few google searches... However, I am not in control of the JSON object being created by Cognito library here... and hence, need help in figuring out a path to resolution. If any of you have faced this before and had a solution for this, please reply.
In my application above, for every new Cognito user created at the browser client, I was creating a new dataset and adding some info to it.
I had also setup Cognito to trigger a Lambda function for user creates.
Hence, during new user creations, Cognito was triggering the Lambda function and was synchronously waiting for the function to return successfully before marking the user dataset update operation as "complete" / "successful".
Within the Lambda function, I was also trying to update the same dataset for the user that was created at the browser with some additional information. This seems to have triggered a update back to the Cognito browser client. Afterall the prime functionality of Cognito is to keep its various clients at sync as user's info changes.
As stated in the SO answer here, this went away when I stopped trying to update the same dataset at client and the lambda function at the same time.

Login module in Titanium

Any one has experience in development of Login module with ProviderService.Src.
I need to develop a login module with the webservice using Titanium Appcelerator. It needs to take two strings (Username & Password) and return true/false. I need to send entered login and password via web service and receive true/false. The webservice is
http://46.18.8.42/FareBids.Service/FareBids.ServiceLayer.ProviderService.svc
Please some one guide me how to create a Login module with it? I got information which says me to use SUDS. Can some one help me on this with code(if possible)
Help would really be appreciated. Thanks.
Use a webservice http client. This should do it, you will have to tune this to your specific webservice and obviously collect data from the user, but how to do that is well documented in the most basic Titanium tutorials.
var loginSrv = Ti.Network.createHTTPClient({
onload : function(e) {
// If the service returns successfully : true, or false
var isUserAllowed = this.responseText;
},
onerror : function(e) {
// Web service failed for some reason
Ti.API.info(this.responseText);
Ti.API.info('webservice failed with message : ' + e.error);
}
});
loginSrv.open('POST', 'http://46.18.8.42/FareBids.Service/FareBids.ServiceLayer.ProviderService.svc');
// you may have to change the content type depending on your service
loginSrv.setRequestHeader("Content-Type", "application/json");
var sendObj = {loginid : 'someid', pwd : 'somepassword'};
loginSrv.send(obj);