//============================================================================================== // Getters / Setters //============================================================================================== /** * Gets or creates a LayerClient, using a default set of LayerClient.Options and flavor-specific * App ID and Options from the `generateLayerClient` method. Returns `null` if the flavor was * unable to create a LayerClient (due to no App ID, etc.). * * @return New or existing LayerClient, or `null` if a LayerClient could not be constructed. * @see Flavor#generateLayerClient(Context, LayerClient.Options) */ public static LayerClient GetLayerClient() { if (sLayerClient == null) { // Custom options for constructing a LayerClient LayerClient.Options options = new LayerClient.Options() /* Fetch the minimum amount per conversation when first authenticated */ .InvokeHistoricSyncPolicy(LayerClient.Options.HistoricSyncPolicy.FromLastMessage) /* Automatically download text and ThreePartImage info/preview */ .InvokeAutoDownloadMimeTypes(new List <string> { TextCellFactory.MimeType, ThreePartImageUtils.MimeTypeInfo, ThreePartImageUtils.MimeTypePreview }); // Allow flavor to specify Layer App ID and customize Options. sLayerClient = sFlavor.GenerateLayerClient(sInstance, options); // Flavor was unable to generate Layer Client (no App ID, etc.) if (sLayerClient == null) { return(null); } /* Register AuthenticationProvider for handling authentication challenges */ sLayerClient.RegisterAuthenticationListener(GetAuthenticationProvider()); } return(sLayerClient); }
//Captures any errors with syncing public void OnSyncError(LayerClient layerClient, IList <LayerException> layerExceptions) { foreach (LayerException e in layerExceptions) { Log.Verbose(TAG, "onSyncError: " + e.ToString()); } }
public void OnDeauthenticated(LayerClient layerClient) { if (Log.IsLoggable(Log.VERBOSE)) { Log.v("Deauthenticated with Layer"); } }
public void OnContentFailed(LayerClient client, Uri objectId, string reason) { if (Util.Log.IsLoggable(Util.Log.ERROR)) { Util.Log.e("Failed to fetch notification content"); } }
public override void OnCreate() { base.OnCreate(); LayerClient.ApplicationCreated(this); LayerClient layerClient = this.LayerClient; }
public void OnAuthenticationChallenge(LayerClient layerClient, string nonce) { if (Log.IsLoggable(Log.VERBOSE)) { Log.v("Received challenge: " + nonce); } RespondToChallenge(layerClient, nonce); }
//Called when the user has successfully authenticated public void OnAuthenticated(LayerClient client, string userID) { //Start the conversation view after a successful authentication Log.Verbose(TAG, "Authentication successful"); if (main_activity != null) { main_activity.OnUserAuthenticated(); } }
//Called after layerClient.authenticate() executes //You will need to set up an Authentication Service to take a Layer App ID, User ID, and the //nonce to create a Identity Token to pass back to Layer //NOTES: // - The method will be called when you call "layerClient.authenticate()" or after // Authentication // when the Identity Token generated by your Web Services expires (you explicitly need to set // the expiration date in the Token) // - The Nonce returned in this function will expire after 10 minutes, after which you will need // to call public void OnAuthenticationChallenge(LayerClient client, string nonce) { string userId = MainActivity.GetUserID(); //Note: This Layer Authentication Service is for TESTING PURPOSES ONLY //When going into production, you will need to create your own web service //Check out https://developer.layer.com/docs/guides#authentication for guidance new IdentityAsyncTask(client, userId, nonce).Execute(); }
public void OnContentAvailable(LayerClient client, IQueryable obj) { if (Util.Log.IsLoggable(Util.Log.VERBOSE)) { Util.Log.v("Pre-fetched notification content"); } var message = obj.JavaCast <IMessage>(); GetNotifications(_context).Add(_context, message, _text); }
public void OnDeauthenticationSuccess(LayerClient client) { if (Util.Log.IsLoggable(Util.Log.VERBOSE)) { Util.Log.v("Successfully deauthenticated"); } _progressDialog.Dismiss(); _activity.SetEnabled(true); App.RouteLogin(_activity); }
public void OnDeauthenticationFailed(LayerClient client, string reason) { if (Util.Log.IsLoggable(Util.Log.ERROR)) { Util.Log.e("Failed to deauthenticate: " + reason); } _progressDialog.Dismiss(); _activity.SetEnabled(true); Toast.MakeText(_activity, _activity.GetString(Resource.String.toast_failed_to_deauthenticate, reason), ToastLength.Short).Show(); }
//Checks to see if the SDK is connected to Layer and whether a user is authenticated //The respective callbacks are executed in MyConnectionListener and MyAuthenticationListener private void _LoadLayerClient() { // Check if Sample App is using a valid app ID. if (_IsValidAppID()) { if (layerClient == null) { //Used for debugging purposes ONLY. DO NOT include this option in Production Builds. LayerClient.SetLoggingEnabled(this.ApplicationContext, true); // Initializes a LayerClient object with the Google Project Number LayerClient.Options options = new LayerClient.Options(); //Sets the GCM sender id allowing for push notifications options.InvokeGoogleCloudMessagingSenderId(GCM_PROJECT_NUMBER); //By default, only unread messages are synced after a user is authenticated, but you // can change that behavior to all messages or just the last message in a conversation options.InvokeHistoricSyncPolicy(LayerClient.Options.HistoricSyncPolicy.AllMessages); layerClient = LayerClient.NewInstance(this, LAYER_APP_ID, options); //Register the connection and authentication listeners layerClient.RegisterConnectionListener(connectionListener); layerClient.RegisterAuthenticationListener(authenticationListener); } //Check the current state of the SDK. The client must be CONNECTED and the user must // be AUTHENTICATED in order to send and receive messages. Note: it is possible to be // authenticated, but not connected, and vice versa, so it is a best practice to check // both states when your app launches or comes to the foreground. if (!layerClient.IsConnected) { //If Layer is not connected, make sure we connect in order to send/receive messages. // MyConnectionListener.java handles the callbacks associated with Connection, and // will start the Authentication process once the connection is established layerClient.Connect(); } else if (!layerClient.IsAuthenticated) { //If the client is already connected, try to authenticate a user on this device. // MyAuthenticationListener.java handles the callbacks associated with Authentication // and will start the Conversation View once the user is authenticated layerClient.Authenticate(); } else { // If the client is to Layer and the user is authenticated, start the Conversation // View. This will be called when the app moves from the background to the foreground, // for example. OnUserAuthenticated(); } } }
/* * 1. Implement `onAuthenticationChallenge` in your Authentication Listener to acquire a nonce */ public void OnAuthenticationChallenge(LayerClient client, string nonce) { //You can use any identifier you wish to track users, as long as the value is unique //This identifier will be used to add a user to a conversation in order to send them messages string userId = GetUserId(); /* * 2. Acquire an identity token from the Layer Identity Service */ new AcquireIdentityTokenAsyncTask(client, userId, nonce).Execute(); }
public void OnAuthenticated(LayerClient layerClient, string userId) { if (Log.IsLoggable(Log.VERBOSE)) { Log.v("Authenticated with Layer, user ID: " + userId); } layerClient.Connect(); if (mCallback != null) { mCallback.OnSuccess(this, userId); } }
//============================================================================================== // Generators //============================================================================================== public LayerClient GenerateLayerClient(Context context, LayerClient.Options options) { // If no App ID is set yet, return `null`; we'll launch the AppIdScanner to get one. string appId = GetLayerAppId(); if (appId == null) { return(null); } options.InvokeGoogleCloudMessagingSenderId(GCM_SENDER_ID); return(LayerClient.NewInstance(context, appId, options)); }
public void OnAuthenticationError(LayerClient layerClient, LayerException e) { string error = "Failed to authenticate with Layer: " + e.Message; if (Log.IsLoggable(Log.ERROR)) { Log.e(error, e); } if (mCallback != null) { mCallback.OnError(this, error); } }
//================================================================================ // ILayerTypingIndicatorListener methods //================================================================================ public void OnTypingIndicator(LayerClient layerClient, Conversation conversation, string userID, LayerTypingIndicatorListenerTypingIndicator indicator) { //Only show the typing indicator for the active (displayed) converation if (conversation != activeConversation) { return; } if (LayerTypingIndicatorListenerTypingIndicator.Started == indicator) { // This user started typing, so add them to the typing list if they are not // already on it. if (!typingUsers.Contains(userID)) { typingUsers.Add(userID); } } else if (LayerTypingIndicatorListenerTypingIndicator.Finished == indicator) { // This user isn't typing anymore, so remove them from the list. typingUsers.Remove(userID); } //Format the text to display in the conversation view if (typingUsers.Count == 0) { //No one is typing, so clear the text typingIndicator.Text = ""; } else if (typingUsers.Count == 1) { //Name the one user that is typing (and make sure the text is grammatically correct) typingIndicator.Text = typingUsers[0] + " is typing"; } else if (typingUsers.Count > 1) { //Name all the users that are typing (and make sure the text is grammatically correct) string users = ""; for (int i = 0; i < typingUsers.Count; i++) { users += typingUsers[i]; if (i < typingUsers.Count - 1) { users += ", "; } } typingIndicator.Text = users + " are typing"; } }
public static IAuthenticationProvider GetAuthenticationProvider() { if (sAuthProvider == null) { sAuthProvider = sFlavor.GenerateAuthenticationProvider(sInstance); // If we have cached credentials, try authenticating with Layer LayerClient layerClient = GetLayerClient(); if (layerClient != null && sAuthProvider.HasCredentials()) { layerClient.Authenticate(); } } return(sAuthProvider); }
public override bool OnOptionsItemSelected(IMenuItem item) { switch (item.ItemId) { case Resource.Id.action_settings: StartActivity(new Intent(this, typeof(AppSettingsActivity))); return(true); case Resource.Id.action_sendlogs: LayerClient.SendLogs(GetLayerClient(), this); return(true); } return(base.OnOptionsItemSelected(item)); }
//Called on connection success. The Quick Start App immediately tries to //authenticate a user (or, if a user is already authenticated, return to the conversation //screen). public void OnConnectionConnected(LayerClient client) { Log.Verbose(TAG, "Connected to Layer"); //If the user is already authenticated (and this connection was being established after // the app was disconnected from the network), then start the conversation view. //Otherwise, start the authentication process, which effectively "logs in" a user if (client.IsAuthenticated) { main_activity.OnUserAuthenticated(); } else { client.Authenticate(); } }
private void ListenIncommingLayerConnections(IAsyncResult ar) { lock (this.LayerListenerLock) { if (this._layerListener != null) { try { TcpClient tcpClient = this._layerListener.EndAcceptTcpClient(ar); ILayerClient client = new LayerClient(this, new LayerConnection(tcpClient), this._application, this._client); // Issue #24. Somewhere the end port connection+port isn't being removed. if (this.Clients.ContainsKey(client.IPPort) == true) { this.Clients[client.IPPort].Shutdown(); // If, for some reason, the client wasn't removed during shutdown.. if (this.Clients.ContainsKey(client.IPPort) == true) { this.Clients.Remove(client.IPPort); } } this.Clients.Add(client.IPPort, client); this.OnClientConnected(client); this._layerListener.BeginAcceptTcpClient(this.ListenIncommingLayerConnections, this); } catch (SocketException exception) { this.OnSocketError(exception); this.Shutdown(); //cbfAccountsPanel.OnLayerServerSocketError(skeError); } catch (Exception e) { FrostbiteConnection.LogError("ListenIncommingLayerConnections", "catch (Exception e)", e); } } } }
//============================================================================================== // Application Overrides //============================================================================================== public override void OnCreate() { base.OnCreate(); // Enable verbose logging in debug builds if (BuildConfig.DEBUG) { Com.Layer.Atlas.Util.Log.SetAlwaysLoggable(true); Messenger.Util.Log.SetAlwaysLoggable(true); LayerClient.SetLoggingEnabled(this, true); } // Allow the LayerClient to track app state LayerClient.ApplicationCreated(this); sInstance = this; }
protected override void OnResume() { base.OnResume(); LayerClient client = App.GetLayerClient(); if (client == null) { return; } if (client.IsAuthenticated) { client.Connect(); } else { client.Authenticate(); } }
public bool RouteLogin(LayerClient layerClient, string layerAppId, Activity from) { if (layerAppId == null) { // No App ID: must scan from QR code. if (Log.IsLoggable(Log.VERBOSE)) { Log.v("Routing to QR Code scanning Activity"); } Intent intent = new Intent(from, typeof(DemoAtlasIdScannerActivity)); intent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.ClearTask | ActivityFlags.NewTask); from.StartActivity(intent); return(true); } if (layerClient != null && !layerClient.IsAuthenticated) { if (HasCredentials()) { // Use the cached AuthenticationProvider credentials to authenticate with Layer. if (Log.IsLoggable(Log.VERBOSE)) { Log.v("Using cached credentials to authenticate"); } layerClient.Authenticate(); } else { // App ID, but no user: must authenticate. if (Log.IsLoggable(Log.VERBOSE)) { Log.v("Routing to login Activity"); } Intent intent = new Intent(from, typeof(DemoLoginActivity)); intent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.ClearTask | ActivityFlags.NewTask); from.StartActivity(intent); return(true); } } if (Log.IsLoggable(Log.VERBOSE)) { Log.v("No authentication routing needed"); } return(false); }
/** * Authenticates with the AuthenticationProvider and Layer, returning asynchronous results to * the provided callback. * * @param credentials Credentials associated with the current AuthenticationProvider. * @param callback Callback to receive authentication results. */ public static void Authenticate(Object credentials, IAuthenticationProviderCallback callback) { LayerClient client = GetLayerClient(); if (client == null) { return; } String layerAppId = GetLayerAppId(); if (layerAppId == null) { return; } GetAuthenticationProvider() .SetCredentials(credentials) .SetCallback(callback); client.Authenticate(); }
public override bool OnOptionsItemSelected(IMenuItem item) { switch (item.ItemId) { case Resource.Id.action_details: if (mConversation == null) { return(true); } Intent intent = new Intent(this, typeof(ConversationSettingsActivity)); intent.PutExtra(PushNotificationReceiver.LAYER_CONVERSATION_KEY, mConversation.Id); StartActivity(intent); return(true); case Resource.Id.action_sendlogs: LayerClient.SendLogs(GetLayerClient(), this); return(true); } return(base.OnOptionsItemSelected(item)); }
public ConversationViewController(MainActivity ma, LayerClient client) { //Cache off LayerClient layerClient = client; //When conversations/messages change, capture them layerClient.RegisterEventListener(this); //List of users that are typing which is used with ILayerTypingIndicatorListener typingUsers = new List <string>(); //Change the layout ma.SetContentView(Resource.Layout.activity_main); //Cache off gui objects sendButton = ma.FindViewById <Button>(Resource.Id.send); topBar = ma.FindViewById <LinearLayout>(Resource.Id.topbar); userInput = ma.FindViewById <EditText>(Resource.Id.input); conversationScroll = ma.FindViewById <ScrollView>(Resource.Id.scrollView); conversationView = ma.FindViewById <LinearLayout>(Resource.Id.conversation); typingIndicator = ma.FindViewById <TextView>(Resource.Id.typingIndicator); //Capture user input sendButton.SetOnClickListener(this); topBar.SetOnClickListener(this); userInput.Text = _GetInitialMessage(); userInput.AddTextChangedListener(this); //If there is an active conversation between the Device, Simulator, and Dashboard (web // client), cache it activeConversation = _GetConversation(); //If there is an active conversation, draw it _DrawConversation(); if (activeConversation != null) { _GetTopBarMetaData(); } }
/** * Returns the current maximum Message position within the given Conversation, or * Long.MIN_VALUE if no messages are found. * * @param conversationId Conversation whose maximum Message position to return. * @return the current maximum Message position or Long.MIN_VALUE. */ private long GetMaxPosition(Uri conversationId) { LayerClient layerClient = App.GetLayerClient(); LayerQuery query = LayerQuery.InvokeBuilder(Java.Lang.Class.FromType(typeof(IMessage))) .Predicate(new Predicate(MessageProperty.Conversation, Predicate.Operator.EqualTo, conversationId)) .SortDescriptor(new SortDescriptor(MessageProperty.Position, SortDescriptor.Order.Descending)) .Limit(1) .Build(); IList <IQueryable> results = layerClient.ExecuteQueryForObjects(query); if (results.Count == 0) { return(long.MinValue); } var message = results[0] as IMessage; if (message == null) { return(long.MinValue); } return(message.Position); }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); // Get our button from the layout resource, // and attach an event to it Button button = FindViewById <Button>(Resource.Id.MyButton); button.Click += delegate { LayerClient layerClient = MyApp.Instance.LayerClient; // Creates and returns a new conversation object with sample participant identifiers Conversation conversation; if (layerClient.Conversations.Count == 0) { conversation = layerClient.NewConversation("948374839"); } else { conversation = layerClient.Conversations[0]; } // Create a message part with a string of text MessagePart messagePart = layerClient.NewMessagePart("text/plain", Encoding.UTF8.GetBytes("Hi, how are you?")); // Creates and returns a new message object with the given conversation and array of message parts IMessage message = layerClient.NewMessage(messagePart); // Sends the specified message to the conversation conversation.Send(message); }; }
public IdentityAsyncTask(LayerClient client, string userId, string nonce) { mClient = client; mUserId = userId; mNonce = nonce; }