I'm trying to listen to a Google Calendar event I created using a watch request but I have no clue how to get the event details once I get the push notification.
So this is what I have so far, I create the Calendar event using JavaScript (it prompts the user for authorization):
function createEvent(data) {
var request = gapi.client.calendar.events.insert({
'calendarId': 'primary',
'resource': data
});
request.execute(function(event) {
if (!event.code) {
openToast('The event was added to your Google Calendar')
watchEvent(data.id);
}
});
}
And then I create a watch request to get the PUSH notifications:
function watchEvent(eventId) {
gapi.client.calendar.events.watch({
auth: gapi.auth2.getAuthInstance(),
resource: {
id: eventId,
type: 'web_hook',
address: webhookUrl
},
calendarId: 'primary'
}).execute(function onWatchCalendarEvent(event) {
if (event.error) {
console.error('Error creating event watch webhook', event.error);
}
});
}
So far so good, this is working OK and I receive a PUSH notification with the channelID from which I can get my own internal meetingId.
#PostMapping
public void onCalendarEventUpdate(#RequestHeader(name = "x-goog-channel-id") String channelId,
#RequestHeader(name = "x-goog-resource-state") String resourceState) {
log.info("Received Google Calendar event update notification: " + resourceState);
// only when the event is modified google posts the resource state as "exists"
// (what kind of name is that anyway?)
if (resourceState.equals("exists")) {
// get the meeting ID from the channel ID
Long meetingId = findMeetingIdFromChannelId(channelId);
calendarService.updateMeeting(meetingsService.findById(meetingId));
}
}
I've read the docs for Authorizing Requests, PUSH Notifications and Java API Getting Started but they all prompt for the user authorization. Since this PUSH notification is happening asynchronously how am I supposed to get the updated event details? Thanks
if you have the calendar and event id (e.g. from the notification you get from Google that you receive and parse at your webhookUrl location), you can make calendar api calls to get all the event details: https://developers.google.com/calendar/api/v3/reference/events/get
Related
I am currently working on delivering 1:1 messages to the users in Teams.
Problem Statement: I am having trouble trying to get the member details to populate the Channel Account to set the ConverstationParameters object to create conversation if the user is not part of a team. Is there a way I could get the details of the user without having the user part of a Team. I wasn't able to find any reference documentation to how to get this information for Java.
Below is my code snippet:
Setup credentials and initialize a connection using Connector Client.
Populate Channel account with recipient details for set members on Conversation Parameters Object.
Activity message = MessageFactory.text("Hello World");
MicrosoftAppCredentials credentials = new MicrosoftAppCredentials(appClientID, appClientSecret);
try (ConnectorClient client = new RestConnectorClient(serviceUrl, credentials)) {
logger.info("** Connector Client Set: {} **", client);
ConversationParameters conversationParameters = new ConversationParameters();
conversationParameters.setIsGroup(false);
CompletableFuture<ChannelAccount> user = ((Conversations) client.getConversations())
.getConversationMember(recipient, teamsInternalId); // Don't want to use this because the user has to be part of the same team which is not true in our case.
logger.info("** Aysnc get User details call **");
logger.info("** AAID: {} **", user.get().getAadObjectId());
try {
conversationParameters.setMembers(Collections.singletonList(user.get()));
} catch (ErrorResponseException e) {
logger.error("** User Error : {}**", e.getMessage());
}
conversationParameters.setTenantId(tenantId);
TenantInfo tenantInfo = new TenantInfo(tenantId);
TeamsChannelData channelData = new TeamsChannelData();
channelData.setTenant(tenantInfo);
conversationParameters.setChannelData(channelData);
CompletableFuture<ConversationResourceResponse> conversationResourceResponse = new CompletableFuture<ConversationResourceResponse>();
try {
conversationResourceResponse = client.getConversations()
.createConversation(conversationParameters);
logger.info("** Create Conversation: {} **", conversationResourceResponse.get().getId());
} catch (ErrorResponseException e) {
logger.error("** Create Conversation : {} **", e.getMessage());
}
CompletableFuture<ResourceResponse> response = client.getConversations()
.sendToConversation(conversationResourceResponse.get().getId(), message);
logger.info("** Send Conversation **", response.get().getId());
I solved the above requirement following these steps:
Check if my app is installed for the user using Graph API.
If not installed, force install the app for the user using Graph API.
Then retrieve the conversation chat id.
Use this chat id to send the message to the user.
There steps are outline here on the MSFT reference page:
https://learn.microsoft.com/en-us/microsoftteams/platform/graph-api/proactive-bots-and-messages/graph-proactive-bots-and-messages?tabs=dotnet
I hope this answer helps anyone in the same boat who would like to send messages directly 1:1 from an app to a Teams user without any mutual Team condition.
Unable to send firebase fcm push notiication to android device.
When I send test message from firebase console, it goes to device. So Android side code is working fine.
For Backend Java server, I am using firebase sdk
public void sendNotification2(String notification, String title, String to) {
String registrationToken = to;
Message message = Message.builder().putData("score", "850").putData("time", "2:45")
.setToken(registrationToken).build();
String response;
response = FirebaseMessaging.getInstance().send(message);
System.out.println("Successfully sent message: " + response);
}
Code outputs: Successfully sent message: projects/myappname/messages/0:1590590793114288%9cceaf10deffd7abc
But the device doesn't receive notification.
It would be important to clarify if your app is in background or foreground while sending the message from backend, in fcm this is important to consider.
In this case, you send a data message, not a notification message.
The difference is explained in the doc:
https://firebase.google.com/docs/cloud-messaging/android/receive
That means, you should receive this message in the overriden onMessageReceived(...)-method when the app is in the foreground and in the background.
(You can control this with a debug log command.)
If you use data messages, you can define custom key-value pairs and implement the notification process on your own, when the app is in the foreground and background. With firebase console in contrast, you send notification messages, they are processed in the background of your app automaticly, in the foreground the overriden onMessageReceived(...) is triggered.
Here is an example of building a notification message (with different priorities which should not confuse you):
private Message createFCMMessageWithNormalPriority(String notificationMessage) {
return Message.builder().setNotification(createFCMNotification(notificationMessage)).setToken(registrationToken)
.setAndroidConfig(createAndroidConfigWithNormalMessagePriority()).build();
}
private Message createFCMMessageWithHighPriority(String notificationMessage) {
return Message.builder().setNotification(createFCMNotification(notificationMessage)).setToken(registrationToken)
.setAndroidConfig(createAndroidConfigWithHighMessagePriority()).build();
}
private AndroidConfig createAndroidConfigWithHighMessagePriority() {
return createAndroidConfigWithPriority(Priority.HIGH);
}
private AndroidConfig createAndroidConfigWithNormalMessagePriority() {
return createAndroidConfigWithPriority(Priority.NORMAL);
}
private AndroidConfig createAndroidConfigWithPriority(Priority priority) {
return AndroidConfig.builder().setPriority(priority).build();
}
private Notification createFCMNotification(String notificationMessage) {
return Notification.builder().setBody(notificationMessage).setTitle(NOTIFICATION_CONTENT_TITLE).build();
}
I am currently working on an Android app and I added Firebase so I could get notifications.
Looking into this I bumped into onMessageReceived().
Does anyone know any real life examples of how this can be used? or what's the purpose?
Thanks for any help :)
whenever an app is in foreground/active the incoming notification goes into app which you can get from onMessageReceived() method, the notification will not be shown automatically, you will have to do it manually.
If the app is in background/inactive the incoming notification goes into the systems notification service which will show the notification automatically.
If you want to do both the task manually you have to send data while sending a fcm message.
or in in firebase functions you can do it like this
const payload = {
data: {
title: "title",
body: `body`,
icon: "default",
sound: "default"
}
};
const options = {
priority: "high",
timeToLive: 60 * 10
};
return admin.messaging().sendToTopic("notifyAll", payload, options)
.then((response) => {
console.log("Successfully sent message:", response);
return response;
})
.catch((error) => {
console.log("Error sending message:", error);
return error;
});
I am trying to use telegram database library for java (tdlib or tdapi) but when i get chatId of a channel by SearchPublicChat and try to get messages or view messages i get an error.
Error{code=6 message= Chat not found}
I can not understand why the chatId i receive above why when i pass it to another method i get that error
Please help me about that problem and that library.
Thank you.
example for getting last 15 messages from chat
String username = "any_chat_public_link";
TdApi.SearchPublicChat searchPublicChat=new TdApi.SearchPublicChat(username);
TG.getClientInstance().send(searchPublicChat, new Client.ResultHandler() {
#Override
public void onResult(TdApi.TLObject object) {
TdApi.Chat chat = (TdApi.Chat) object;
TdApi.Message topMessage = chat.topMessage;
long chatId = chat.id;
TdApi.GetChatHistory getChatHistory = new TdApi.GetChatHistory(chatId, topMessage.id, 0, 15);
TG.getClientInstance().send(getChatHistory, new Client.ResultHandler() {
#Override
public void onResult(TdApi.TLObject object) {
TdApi.Messages messages = (TdApi.Messages) object;
}
});
}
});
Before requesting chat by id the TdLib must know about this chat in current session. You need search this chat by #mention_link if it public, or getting whole your chat list. Also, the library will be know about chat if some action happens with this chat (like new message from chat, chat updated...)
And this applies also to messages, users and etc. You can request it by id only when TdLib know about this entity.
Before receiving the message history, you need to subscribe to the chat by sending TdApi.JoinChat. The procedure is as follows:
1) TdApi.SearchPublicChat
2) TdApi.JoinChat
3) TdApi.GetChatHistory
TdApi.GetChatHistory requires the id of the last chat message. It can be obtained using the TdApi.GetChat method.
I used tdlib/example. Information about chats is updated automatically by the getMainChatList method, then it can be obtained from chats.get(chatId)
I am sending push notifications using UrbanAirship API using java.
Here is the doc: http://docs.urbanairship.com/api/
I want to send a push notifications with custom key/value. For example, I want send to following to Android/iOS device
name: "Jack"
String appKey = "appKey";
String appSecret = "appSecret";
// Setup an authenticated APIClient with your application key and
// application master secret.
APIClient apiClient = APIClient.newBuilder()
.setKey(appKey)
.setSecret(appSecret)
.build();
// Setup a push payload to send to the API with our handy builders
PushPayload payload = PushPayload.newBuilder()
.setAudience(Selectors.all())
.setNotification(Notifications.notification("UA Push"))
.setDeviceTypes(DeviceTypeData.of(DeviceType.IOS))
.build();
// Try and send, handle anything that comes up
try {
APIClientResponse<APIPushResponse> response = apiClient.push(payload);
logger.info("Sent a push message!");
}
// Non 200 responses throw an APIRequestException. Check the documentation
// to debug your request.
catch (APIRequestException ex){
logger.error("Non 200 request, checking error details and taking action");
}
// An underlying error occurred, most likely outside of the scope of the
// UA library, do some HTTP debugging
catch (IOException e){
logger.error("Broken pipe what?");
}
Here is the code reference for android - https://github.com/urbanairship/java-library/blob/master/src/test/java/com/urbanairship/api/push/model/notification/android/AndroidDevicePayloadTest.java
How can i do send push notification with custom key/value using AndroidDevicePayload ?
You can create your notification like this:
public PushPayload createPushPayloadCustom(String namedUser, String message) {
Notification notification = Notification.newBuilder()
.addDeviceTypeOverride(DeviceType.IOS, IOSDevicePayload.newBuilder()
.setAlert(message)
.build())
.addDeviceTypeOverride(DeviceType.ANDROID, AndroidDevicePayload.newBuilder()
.setAlert(message)
.build())
.build();
return PushPayload.newBuilder()
.setAudience(Selectors.namedUser(namedUser))
.setNotification(notification)
.setDeviceTypes(DeviceTypeData.of(DeviceType.ANDROID, DeviceType.IOS))
.build();
}
You can add to the "extras" object any key/value:
DeviceTypeData deviceTypeData = DeviceTypeData.of(DeviceType.IOS, DeviceType.ANDROID);
IOSDevicePayload iosPayload = IOSDevicePayload.newBuilder()
.setAlert(message)
.addExtraEntry("custom_ios_key", "custom value for IOS")
.build();
AndroidDevicePayload androidPayload = AndroidDevicePayload.newBuilder()
.setAlert(message)
.addExtraEntry("custom_android_key", "custom value for Android")
.build();
PushPayload payload = PushPayload.newBuilder()
.setAudience(Selectors.namedUser(email))
.setNotification(Notifications.notification(iosPayload,androidPayload))
.setDeviceTypes(deviceTypeData)
.build();
Then in the received push, you will find the object:
For more details go to urbanairship official documentation