implementation of Agora signalling to communicate when app is closed - java

I am currently working on Agora.io services which give us
audio,video,one-to-one and broadcast communication
I have successfully implemented these with the help of there given samples, and successfully add signalling module.
Problem is that signalling call must be active to access all features of it now I want to access all features of signalling at the time when app is closed like whatsapp and other these type of application one solution is make a service of signalling class but this is not professional solution.
I want efficient one solution

This cannot be done with any 3rd party APIs. This is a system level functionality offered by Apple & Google. You will have to use CallKit (for iOS) or ConnectionService (for Android) to achieve this functionality.

I have done exactly the same thing a few days ago.
For iOS, you have use PushKit and CallKit in the following ways:-
.1. Enable background mode and also check voip.
Import Pushkit and implement PKPushRegistryDelegate functions.
Register pushkit like this :-
func registerPushkitToken() -> Void {
pushRegistry = PKPushRegistry.init(queue: DispatchQueue.main)
pushRegistry?.delegate = self
pushRegistry?.desiredPushTypes = [.voIP]
}
3.Implement the token fuction
func pushRegistry(_ registry: PKPushRegistry, didUpdate pushCredentials:
PKPushCredentials, for type: PKPushType) {
let tokenChars = pushCredentials.token.hexString()
}
Implement the following function for parsing notification
func pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload, for type: PKPushType) {
if let userInfo = payload.dictionaryPayload["userInfo"] as? [AnyHashable:Any]{
}
}
Implement provider delegate functions:
let providerConfiguration = CXProviderConfiguration(localizedName: appName)
providerConfiguration.supportsVideo = true
providerConfiguration.maximumCallsPerCallGroup = 1
providerConfiguration.maximumCallGroups = 1
providerConfiguration.supportedHandleTypes = [.generic]
Implement CXProviderDelegate functions
func providerDidReset(_ provider: CXProvider) {
print("Function: \(#function), line: \(#line)")
sessionPool.removeAll()
}
func provider(_ provider: CXProvider, perform action: CXStartCallAction) {
print("Function: \(#function), line: \(#line)")
guard let session = pairedSession(of:action.callUUID) else {
action.fail()
return
}
let callUpdate = CXCallUpdate()
callUpdate.remoteHandle = action.handle
callUpdate.hasVideo = true
callUpdate.localizedCallerName = callDetails.dispalyName;
callUpdate.supportsDTMF = false
provider.reportCall(with: action.callUUID, updated: callUpdate)
delegate?.callCenter(self, startCall: session)
action.fulfill()
}
You can also refer to my post here. how to integrate Callkit with Agora VOiP in swift 4 iOS?

Related

Java Custom Google Analytics 4 Server-Side Event User-IP

In my current Java project, it's easy to track server-side user events in the "old" Google Analytics Universal Project with simple REST calls to Google Analytics. So that location tracking was working, i could override the server ip with the user ip, according to the parameter "&uip=1.2.3.4" (https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters?hl=de#uip).
As upgrading to GA4 is recommended, I was able to change all the REST parameters in my project and show my events in the new dashboard, except for the user location. I can't find any information about such a parameter. I tried using still "uip" but now all my requests are located to the country of my server.
Unfortunately it's not possible to track the event client side, because my project is a simple REST API, returning only JSON data.
Does anyone have an idea, if there's such a parameter like "uip" for ga4 or if this isn't possible anymore?
In the following way I setup my parameters:
private String getQueryParameters(MeasurementEvent event) {
StringBuilder body = new StringBuilder();
body.append("?v=").append(version);
body.append("&tid=").append(trackingId);
body.append("&cid=").append(event.getClientId());
body.append("&en=").append(eventName);
body.append("&aip=1");
if (StringUtils.hasText(event.getAction())) {
body.append("&ep.useraction=").append(event.getAction());
}
if (StringUtils.hasText(event.getCategory())) {
body.append("&ep.awsregion=").append(event.getCategory());
}
if (StringUtils.hasText(event.getLabel())) {
body.append("&ep.softwarename=").append(event.getLabel());
}
if (StringUtils.hasText(event.getRemoteAddress())) {
body.append("&uip=").append(event.getRemoteAddress());
}
if (StringUtils.hasText(event.getUrl())) {
body.append("&dl=").append(event.getUrl());
}
return body.toString();
}

How to set parent id and operation id of the telemetry in Azure Application Insights for Azure function using Java

I have an function app: funct1(HttpTrigger) -> blob storage -> func2(BlobTrigger). In Application Insights, there will be two separate request telemetry generated with different operation id. Each has its own end-to-end transaction trace.
In order to get the end-to-end trace for the whole app, I would like to correlate two functions by setting the parent id and operation id of func2 with request id and operation id of func1 so both can be shown in application insights as one end-to-end trace.
I have tried following code but it didn't take any effect and there is a lack of documentation about how to use application insights Java SDK in general for customizing telemetry.
#FunctionName("Create-Thumbnail")
#StorageAccount(Config.STORAGE_ACCOUNT_NAME)
#BlobOutput(name = "$return", path = "output/{name}")
public byte[] generateThumbnail(
#BlobTrigger(name = "blob", path = "input/{name}")
byte[] content,
final ExecutionContext context
) {
try {
TelemetryConfiguration configuration = TelemetryConfiguration.getActive();
TelemetryClient client = new TelemetryClient(configuration);
client.getContext().getOperation().setParentId("MY_CUSTOM_PARENT_ID");
client.flush();
return Converter.createThumbnail(content);
} catch (Exception e) {
e.printStackTrace();
return content;
}
}
Anyone with knowledge in this area can provide some tips?
I'm afraid it can't be achieved as the official doc said :
In C# and JavaScript, you can use an Application Insights SDK to write
custom telemetry data.
If you need to set custom telemetry, you need to add app insights java SDK to your function, but I haven't found any SDK... If there's any progress, I'll update here.

Firebase access Hackernews

So i wanted to check out Firebase and try connecting to Hackernews Firebase database.
I'm using the com.google.firebase:firebase-server-sdk:3.0.3 sdk.
But I am not sure why i am forced to enter a service account.
#Bean
fun firebase(): DatabaseReference {
val options = FirebaseOptions.Builder()
.setDatabaseUrl("https://hacker-news.firebaseio.com/")
.setServiceAccount(this.javaClass.getResourceAsStream("/account.json"))
.build()
val app = FirebaseApp.initializeApp(options)
val instance = FirebaseDatabase.getInstance(app)
return instance.reference
}
Why is setServiceAccount required in this case ? If i leave it out i get following exception:
Caused by: java.lang.IllegalStateException: Service Account must be provided.
at com.google.firebase.internal.Preconditions.checkState(Preconditions.java:173) ~[firebase-server-sdk-3.0.3.jar:na]
at com.google.firebase.FirebaseOptions.<init>(FirebaseOptions.java:129) ~[firebase-server-sdk-3.0.3.jar:na]
Is there a way to connect to Firebase anonymously with a Java client?
This JsFiddle works without a service account:
http://jsfiddle.net/firebase/cm8ne9nh/
If i connect to my own project, this work perfectly nice. I do have a proper service account for my own projects thought...
Thought i might be able to connect with Java the same way.
Any ideas ? Is there a way to connect to Hackernews with the Firebase Java API?
Unfortunately, the Java SDK is only available in two flavors. Java-Client-Android, and Java-Server. Which means, if you want pure client code, you can only really use it on android. This has always been a strange limitation of the available client libraries.
However, what you can do, is wrap the REST API that firebase provides with Java, using HTTP requests to perform everything like you would in any client library.
An example of a repository that has already implemented this is here: https://github.com/j-fischer/rest-on-fire
You could use that one, or you could use your own. But in order to use firebase without a service account, you will have to either use the REST Api or the official Client Libraries which are only writen for Android, iOS, and Web.
Although in the docs here it is not obvious
https://github.com/HackerNews/API
I found this REST API that does not need authentication:
https://hn.algolia.com/api
It can be used in many ways, including with Retrofit & Moshi and no authentication.
Just one example in Kotlin:
interface HackerNewsService {
#GET("search?tags=(story,show_hn,front_page)&hitsPerPage=500")
fun searchStories(#Query("query") q: String, #Query("numericFilters") filters: String, #Query("page") page: Int): Call<SearchResult>
}
val response = hackerNewsService.searchStories(keyword, "created_at_i>$after", 0).execute()
if (response.isSuccessful) {
val searchResult: SearchResult = response.body()!!
println("results! (${searchResult.hits.size}) $searchResult")
} else {
println("uh oh")
}

Facebook Messenger bot object structure for java

Has anyone created an open source project that exposes the facebook messenger bot API in java? (or another language I could convert?)
Essentially an object hierarchy for the stack found in:
https://developers.facebook.com/docs/messenger-platform/send-api-reference
I'd rather not just use JsonObjects, etc. nor Maps to extract the incoming JSON chat messages or to build the outgoing structured chat replies. If an open source project for this exists -- I have not found it.
Take a look at FaceBot. The goal of FaceBot is making the Facebook's Messenger Platform easier: with FaceBot, you only need less than 5 lines of code to set up your own Messenger bot.
Here's an example:
public class MyFaceBotBehavior extends AbstractFaceBot {
public void defineBehavior() {
// Setting my tokens from Facebook (page token and validation token for webhook).
FaceBotContext.getInstance().setup("myFacebookPageToken", "myFacebookWebhookValidationToken");
// Defining a bot which will reply with "Hello World!" as soon as I write "Hi"
addActionFrame(new MessageEvent("Hi"),
new MessageAutoReply("Hello World!"));
}
}
If you have questions or need help, feel free to contact me (I'm the developer).
With the open source project messenger4j you will get all you need.
It's an easy to use Java library for building chatbots on the Messenger Platform.
It provides a rich builder API to construct the outgoing messages.
Furthermore it parses the inbound messages to specific java objects and automatically detects their type. For each message type or event you can register corresponding event handlers.
Receiving:
String payload = ... // callback request body
String signature = ... // 'X-Hub-Signature' request header
// JDK 8 version
MessengerReceiveClient receiveClient = MessengerPlatform.newReceiveClientBuilder("APP_SECRET", "VERIFICATION_TOKEN")
.onTextMessageEvent(event -> System.out.printf("%s: %s", event.getSender().getId(), event.getText()))
.build();
// JDK 7 version
MessengerReceiveClient receiveClient = MessengerPlatform.newReceiveClientBuilder("APP_SECRET", "VERIFICATION_TOKEN")
.onTextMessageEvent(new TextMessageEventHandler() {
#Override
public void handle(TextMessageEvent event) {
System.out.printf("%s: %s", event.getSender().getId(), event.getText());
}
})
.build();
receiveClient.processCallbackPayload(payload, signature);
Sending (simple):
MessengerSendClient sendClient = MessengerPlatform.newSendClientBuilder("PAGE_ACCESS_TOKEN").build();
sendClient.sendTextMessage("RECIPIENT_ID", "Hi there, how are you today?");
Sending (complex):
ReceiptTemplate receipt = ReceiptTemplate.newBuilder("Stephane Crozatier", "12345678902", "USD", "Visa 2345")
.orderUrl("http://petersapparel.parseapp.com/order?order_id=123456")
.timestamp(1428444852L)
.addElements()
.addElement("Classic White T-Shirt", 50F)
.subtitle("100% Soft and Luxurious Cotton")
.quantity(2)
.currency("USD")
.imageUrl("http://petersapparel.parseapp.com/img/whiteshirt.png")
.toList()
.addElement("Classic Gray T-Shirt", 25F)
.subtitle("100% Soft and Luxurious Cotton")
.quantity(1)
.currency("USD")
.imageUrl("http://petersapparel.parseapp.com/img/grayshirt.png")
.toList()
.done()
.addAddress("1 Hacker Way", "Menlo Park", "94025", "CA", "US").street2("").done()
.addSummary(56.14F).subtotal(75.00F).shippingCost(4.95F).totalTax(6.19F).done()
.addAdjustments()
.addAdjustment()
.name("New Customer Discount")
.amount(20.00F)
.toList()
.addAdjustment()
.name("$10 Off Coupon")
.amount(10.00F)
.toList()
.done()
.build();
sendClient.sendTemplate("RECIPIENT_ID", receipt);
BTW: I've built it.
I am currently working on a bot framework in java called JBot and the fb portion is currently under development but the Slack part is done and is used by several developers already.

grails app, using java-apns

I have a grails app, and I am using the java-apns 0.1.5 jar! I have a device key, which already uninstall my app from it, so my question is, should I receive same feedback from the API saying that device is not enable anymore?
My code is the following:
apnsService = APNS.newService()
.withCert(pathToCertificate, password)
.withFeedbackDestination("feedback.sandbox.push.apple.com",2196)
.withSandboxDestination()
.build();
apnsService.start();
Map<String, Date> inactiveDevices = apnsService.getInactiveDevices();
log.debug inactiveDevices
.....
the think is that, the variable inactiveDevices is always empty! why? if I uninstall the app from the device?! am I missing some think in the client(device) side?
If you are using the Sandbox destination, the feedback service may not
report info correctly. This is a known bug with a known workaround,
check the mailing list thread
The problem comes from the "Sandbox" APNs Feedback server, probably a
bug. Here is the solution if anyone has the same problem:
Create a dummy app id in the program portal, enable development push
notifications on it Create and download the associated provisioning
profile Create a new xcode project, and invoke the
registerForRemoteNotificationTypes method on start. Install the dummy
app on your device. At this point, you should have two DEVELOPMENT
apps running on your device: the original app and the dummy app. Both
should be registered to receive push notifications. Uninstall the
original app, and try to send a push notification to that app. Invoke
the feedback service, and you should receive data back.
To resume, the Sandbox Feedbacks server needs TWO DEVELOPMENT Apps
registered on the SAME iPhone to work. This manipulation is not
necessary for the production phase as the "Production" APNs Feedback
server works fine.
I would recommend just switching to test feedback with the production servers.
Please either test with the production servers or use the workaround.
Hello Guys i have done push using grails APNS also with simple java lib.
1. With Grails : here is code snippet for APNS using grails
Hello Guys i have done push using grails APNS.
there are one Important point to remember
1. Proper apple certificate, Apple approved.: Apple approve certificate after 24 hours.
here is my code
1. in config.groovy
environments {
development {
apns {
pathToCertificate = "/Users/sarbogast/Desktop/APNs_development_certificates.p12"
password = "password"
environment = "sandbox"
}
} test {
apns {
pathToCertificate = "/usr/local/myapp/APNs_development_certificates.p12"
password = "password"
environment = "sandbox"
}
} production {
apns {
pathToCertificate = "/usr/local/myapp/APNs_production_certificates.p12"
password = "password"
environment = "production"
}
}
}2. i create a service and here is my service class code def sendMessageToDevices() { List<string> aa = new ArrayList<string>() aa.add("Testing") def payload = APNS.newPayload() .badge(1) .localizedKey("key") .localizedArguments(aa) .sound("default") log.error(payload.length()) if (payload.isTooLong()){ log.info("Message is too long: " + payload.length()) } try { apnsService.testConnection() apnsService.push("Device token here", payload.build() ) } catch (Exception e) { log.error("Could not connect to APNs to send the notification"+e.getMessage()) } }
here "key" is any message which will popup on device push
3. i called this method by controller method..

Categories

Resources