How can I access a mirror service with userid? - java

I want to receive XMPP message with app engine, and then use a look up table to find the corresponding glass's userid and push timeline cards. I saw the service was created in OAuth. Do I need to create a new service each time? Or I can get the service with userid? Is there any references on service?
Thanks
This is the code I'm using. Currently I'm creating a new mirror service each time I got a message. Will that cause any trouble or there is a better way to do that? Is there and reference to "util.create_service"?
class XmppHandler(xmpp_handlers.CommandHandler):
def push_command(self, message=None):
if message.arg:
id=XMPP_addr_access.get_id_from_addr(bare_jid(message.sender))
if id is not None:
creds=StorageByKeyName(Credentials, id, 'credentials').get()
mirror_service = util.create_service('mirror', 'v1', creds)
body = {'notification': {'level': 'DEFAULT'}}
body['text'] = message.arg
mirror_service.timeline().insert(body=body).execute()

In my Glassware, notification responses (what I believe you are calling a service) run similar code to what you have, I generate a new Credential using the java helper method AuthUtil.getCredential(String userId) every time I need to make another Mirror API request based on an incoming notification in App Engine.
This credential is used in a MirrorClient object that uses the same userId and does the insert back into the timeline.
I get the userId by looking it up in a persisted store referenced by the userToken that the notification provides.

Related

Android/Java: how to send notifications to user, even when app is not "actively" being used?

I want to be able to send a notification to a user IF something changes.
For example, my application is crime-related. So users can submit reports of crimes that have happened in their neighborhoods.
When a new crime is reported, I want to be able to send ALL users in that specific neighbourhood a notification, even if they are not actively using the app.
How can this be done? I'm quite new at this but to my understanding services like Firebase Messaging require you to type out a message manually and select users to send the message to manually. I'm wondering if there's a way this can be done without someone having to manually do work?
Similar to how snapchat/instagram and stuff will send you notifications that someone has sent you a message even when you are not using your phone.
In my case, I just want the same standard notification "New crime in your area" to be displayed...
How can I do this? (Currently for notifications I'm just using Notification Channels), thank you so much!
You can easily do this using Parse Server through FCM integration.
First, you need to setup your Android app to be able to receive push notifications
Just follow this Quickstart: https://docs.parseplatform.org/parse-server/guide/#push-notifications-quick-start
Second, you need to create a cloud code function
I suggest you to create a cloud code function that will receive the neighborhood as parameter, will query for the user installations in that neighborhood and send the push notification to all of them.
It would be something like this:
Parse.Cloud.define('notifyCrime', async req => {
const query = new Parse.Query(Parse.Installation);
query.equalTo('neighborhood', req.params.neighborhood); // I'm supposing you have a field called neighborhood in your installation class - if not, you can save this field there when the user sign up
await Parse.Push.send({
where: query,
data: {
alert: 'There is a crime in your neighborhood'
},
useMasterKey: true
});
});
Reference: https://docs.parseplatform.org/js/guide/#sending-pushes-to-queries
Third, you need to call the cloud function from your Android app
Once some user has reported a crime, you can call the cloud code function that you created in step 2 to notify all other users in the same neighborhood.
It would be something like this:
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("neighborhood", "The neighborhood goes here");
ParseCloud.callFunctionInBackground("notifyCrime", params, new FunctionCallback<Object>() {
void done(Object response, ParseException e) {
if (e == null) {
// The users were successfully notified
}
}
});
Reference: https://docs.parseplatform.org/cloudcode/guide/#cloud-functions
"my understanding services like Firebase Messaging require you to type out a message manually and select users to send the message to manually".
This is not completely true. There is a method name Firebase Topic Messaging, that lets you send notifications to specific user segments only. You have to register from the app for that topic and then, you can send customized message to your user groups based on topics they subscribed to.

Can we send notifications in android using Firebase's UID instead of registration token?

I have two android applications in my single firebase project. That project belongs to the connection of vehicles. One app is for the driver and other app is for the passenger. So whenever passenger requests for a ride the driver needs to be notified of that request. So is there any way to send notification to the driver using firebase UID instead of FCM registration token.
I want to know whether registration token will be fix for a particular user or it will refresh/change over time.
Yes you can, use this to register the UID as a topic:
FirebaseMessaging.getInstance()
.subscribeToTopic(appUser.getUid());
Now, when sending the notification, you can use this topic to send the notif. to the particular user.
Tokens keep on refreshing at instances, topics defined by you will not change. Every device for which the topic is defined will be notified.
NOTE:
Registering too many topics will raise
messaging/too-many-topics error. Details here. Hence, token
registration in the preferred way.
Fetching and keeping track of tokens:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onNewToken(String s) {
super.onNewToken(s);
// Save the new token here in a place from where you want to fetch it and send notification
Log.e("NEW_TOKEN",s);
}
}
The answer is No. The FCM tokens are device generated tokens which is generated when,
App is installed
App Data is cleared
and UID is a unique identification generated from a particular user account. Both are not related to each other.
As per your problem, you need to store your tokens wrt to UID and then use it to send notification. Or you can use subscribe tokens for seperate user group. Thats the only option I see.

Azure notification hub: Send notification - Getting the impacted users

I'm using azure-notificationhubs-java-backend to send notifications to Azure hub. I have Azure tags created per application user. Business require me to send notification to multiple users (this part is achieved), and report back the execution status, i.e. whom Azure was able to deliver the notification, and who all were missed (so that other communication can be made with those users). We've this scenario that not all users are yet registered with Azure. Below is the call I am making:
SyncCallback<NotificationOutcome> callback = new SyncCallback<>();
notificationHub.sendNotificationAsync(templateNotification, recipientTags, callback);
NotificationOutcome outcome = callback.getResult();
// outcome has just the notificationId, and trackingId
Any suggestion how can I get success and failed tags. Or there's some other call I can make using the notificationId or trackingId to meet the desired. Thanks!
You can get this data from per message telemetry. Please see below blog for more information.
https://azure.microsoft.com/en-us/blog/retrieve-platform-notification-system-error-details-with-azure-notification-hubs/

Send data to another server when it's updated

I am writing a service which would store picture associated with registered email. So, other domains would have a possibility to get image of the user by email. The main goal is not to upload it each time as nowadays we have to register almost everywhere and that process is quite annoying.
My application is written on Java and I am using REST API.
For example, user's account information is available by login:
#RequestMapping(value = "/get/{login}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public ResponseEntity<User> getByEmail(#PathVariable String login) {
User user = userDao.getUserByLogin(login);
return Optional.ofNullable(user)
.map(result -> new ResponseEntity<>(
result, HttpStatus.OK))
.orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
And now, what i want is to send just updated data to the domains which gonna use my service. How could I figure that out? I think I could ask "domain" to provide some information in order to use my service (some king of registration), but what exactly should I ask for to be able to send data udpdates?
In my thoughts they should also provide some REST path where I could send some kind of request that something has changed.
Any help would be appreciated a lot, thanks.
This is essentially a pub-sub model . You publish some information , on various defined events , to whoever has subscribed to it . Look at this as a subset of state syncronisation of the user information across various endpoints.
In your case , the 'domains' you are referring to would be subscribers of your service and the events could be 'itemAdded' , 'itemAdded' etc. You would want to 'push' out the updates ( or whole info) to the subscribers when the event they have subscribed for occurs , instead of them trying to pull this at some frequency ( that would be a lot of waste calls to your server - you dont want that ! )
There are various solutions available that could achieve this . The one I am going to point you to is called Twilio Sync . This would obviously mean that the 'domains' would have to do some changes at their end to subscribe and consume the updates , but I dont see how else could they be regularly updated if they want information pushed.
Send last update date to the endpoint from the domain which
use it. Then check which data was updated after that date and return
appropriate response.
Talking about image, you can always return URL for download but add last update field. The service which use REST service will determine to download it or not.
Also you may need event driven messaging, publish–subscribe pattern (https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern). Related threads:
How would I create an asynchronous notification system using RESTful web services?
Event Based interaction style in REST
Firebase for mobile apps: https://firebase.google.com/docs/notifications/

Java Google datastore async calls

I do not want to block threads in my application and so I am wondering are calls to the the Google Datastore async? For example the docs show something like this to retrieve an entity:
// Key employeeKey = ...;
LookupRequest request = LookupRequest.newBuilder().addKey(employeeKey).build();
LookupResponse response = datastore.lookup(request);
if (response.getMissingCount() == 1) {
throw new RuntimeException("entity not found");
}
Entity employee = response.getFound(0).getEntity();
This does not look like an async call to me, so it is possible to make aysnc calls to the database in Java? I noticed App engine has some libraries for async calls in its Java API, but I am not using appengine, I will be calling the datastore from my own instances. As well, if there is an async library can I test it on my local server (for example app engine's async library I could not find a way to set it up to use my local server for example I this library can't get my environment variables).
In your shoes, I'd give a try to Spotify's open-source Asynchronous Google Datastore Client -- I have not personally tried it, but it appears to meet all of your requirements, including being able to test on your local server. Please give it a try and let us all know how well it meets your needs, so we can all benefit and learn -- thanks!

Categories