Ionic3 Opentok session.connect doesn;t work - android

I'm using ionic3 with cordova-plugin-opentok#3.2.2
My session is created by node.js back end and that returns session ID and token without any issues.
When I use that token to connect to a session, the call never returns (in error hander code) and on my mobile, I see a window on android phone but without any streaming from my camera.
Tried upgrading to 3.4.2 plugin, but then that gives errors on gradle. Looked at many exchanges on stack overflow and the Q&A's on the plugin documentation.
startCall() {
// Get the session ID and Token from the server
this.discussionService.initiateVideoCall({userId:this.selUser._id.toString(),slot:this.slotDetails}).subscribe(callDetails => {
this.callDetails = callDetails;
this.token = this.callDetails.token;
this.sessionId = this.callDetails.sessionId;
//this.startVideoCall();
});
}
startVideoCall() {
this.session = OT.initSession(this.apiKey, this.sessionId);
this.publisher = OT.initPublisher('publisher');
this.session.on({
streamCreated: (event: any) => {
this.session.subscribe(event.stream, 'subscriber');
OT.updateViews();
},
streamDestroyed: (event: any) => {
console.log(`Stream ${event.stream.name} ended because ${event.reason}`);
OT.updateViews();
},
sessionConnected: (event: any) => {
this.session.publish(this.publisher);
}
});
this.session.connect(this.token, (error: any) => {
<<< The line below never gets executed>>>>
if (error) {
console.log(`There was an error connecting to the session ${error}`);
}
});
this.session.publish(this.publisher);
}

TokBox Developer Evangelist here.
Previously, there was an issue with the Cordova OpenTok Plugin because it did not support the error handler for the session.connect method. This was fixed with Release v3.4.3.
If you're unable to upgrade, you can remove the error handler from your implementation and call connect and publish like so:
this.session.on({
sessionConnected: (event: any) => {
this.session.publish(this.publisher);
},
});
this.session.connect(this.token);
However, I highly recommend upgrading so you can verify if there was an error before attempting to publish. If you're unable to upgrade because there is an issue with the plugin, please file it here.

Related

Pasre server on AWS EC2 giving 141 error on cloud code

I am now using the below cloud code to only update "downloads" column on my parse server running on AWS EC2 instance. But I am getting the error code 141(invalid function)
Parse.Cloud.define("updateDownloads", async (request) => {
const query = new Parse.Query(request.params.className);
query.get(request.params.objectId)
.then((watchFace) => {
downloads = watchFace.get("downloads")
watchFace.set("downloads", downloads + 1);
await watchFace.save(null, { useMasterKey: true });
return "download updated";
}, (error) => {
return "something went wrong";
});
});
I have place my code in /opt/bitnami/cloud/main.js.
I even tried adding “cloud”: “/opt/bitnami/cloud/main.js” in config.json file but then the parse server gives 503 Service Unavailable error. So I removed it.
If you don't add the cloud code main.js file to your parse server configuration, parse server will never find your function, and that's why you get the invalid function error.
If you get error when adding the file, you are either adding it in a wrong way (you need to check your parse server initialization code) or the config.json is in wrong format or the cloud code has a problem.
The best way to figure it out is by checking your logs.
At a first glance, a problem that I see (may have others) is the usage of await in a function that is not async. You are also using a combination of async and then, which is little strange.
I'd recommend you to change the code to something like:
Parse.Cloud.define("updateDownloads", async (request) => {
const query = new Parse.Query(request.params.className);
const watchFace = await query.get(request.params.objectId);
const downloads = watchFace.get("downloads");
watchFace.set("downloads", downloads + 1); // You can use inc function to avoid concurrency problem
await watchFace.save(null, { useMasterKey: true });
return "download updated";
});

Google sign in "Choose an account to continue" loop

I'm trying to implement the following packages with my Flutter app:
https://pub.dev/packages/permission_handler
https://pub.dev/packages/fit_kit
and I've done so by writing the following two functions:
Future<void> checkPermissions() async {
var status = await Permission.activityRecognition.status;
if (status.isUndetermined || status.isDenied) {
Permission.activityRecognition.request();
} else if (status.isPermanentlyDenied) {
openAppSettings();
}
}
Future<void> read() async {
results.clear();
await checkPermissions();
for (DataType type in [DataType.STEP_COUNT, DataType.DISTANCE]) {
try {
results[type] = await FitKit.read(
type,
dateFrom: _weekBeginning,
dateTo: _now,
);
} on UnsupportedException catch (e) {
results[e.dataType] = [];
}
}
dailyStepBuffer = 0;
dailyDistanceBuffer = 0;
for(FitData dataPoint in results[DataType.STEP_COUNT]){
print(dataPoint);
dailyStepBuffer += dataPoint.value.round();
}
for(FitData dataPoint in results[DataType.DISTANCE]){
print(dataPoint);
dailyDistanceBuffer += dataPoint.value.round();
}
setState(() {
dailySteps = dailyStepBuffer;
dailyDistance = dailyDistanceBuffer;
});
}
The functions and packages work as intended on iOS, but for some reason, whenever I call read() on an Android device, it shows me this sign in screen, and when I click on my account, it does nothing and I get the error:
E/flutter ( 8211): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: PlatformException(FitKit, User denied permission access, null)
I've gotten the OAuth 2.0 client ID using my SHA-1 fingerprint, added <uses-permission android:name="android.permission.ACTIVITY_RECOGNITION"/> to my AndroidManifest.xml file and added the following to my build.gradle:
implementation 'com.google.android.gms:play-services-fitness:19.0.0'
implementation 'com.google.android.gms:play-services-auth:18.1.0'
Unfortunately though, none of these appear to have solved the issue. I'd be extremely grateful if anyone could help me solve this, thanks!
Can you try flutter clean and check if this persist?
It seems that the FitKit class has a requestPermissions method. Use that along with FitKit.hasPermissions to ensure that the necessary permissions are granted.
It turned out that for some reason, my package name and application id were different, and so entering the application id instead of the package name when getting my OAuth 2.0 Client ID solved it.

Android - PWA does not open in standalone mode with service worker

While developing a Progressive-Web-App the following Problem occurred:
Standalone mode works perfectly without including the service worker - but does NOT work with.
Without Service-Worker a2hs (added to Homescreen) PWA gets correctly started in "standalone"-Mode.
After adding the Service-Worker (a2hs + installed / Web-APK) PWA opens new Tab in new Chrome-Window.
Chrome-PWA-Audit:
login_mobile_tablet.jsf / include service worker:
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('../serviceWorker.js', {scope: "/application/"})
/* also tried ".", "/", "./" as scope value */
.then(function(registration) {
console.log('Service worker registration successful, scope is: ', registration.scope);
})
.catch(function(error) {
console.log('Service worker registration failed, error: ', error);
});
}
</script>
serviceWorker.js:
var cacheName = 'pwa-cache';
// A list of local resources we always want to be cached.
var filesToCache = [
'QS1.xhtml',
'pdf.xhtml',
'QS1.jsf',
'pdf.jsf',
'login_pages/login_mobile_tablet.jsf',
'login_pages/login_mobile_tablet.xhtml'
];
// The install handler takes care of precaching the resources we always need.
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(cacheName).then(function(cache) {
return cache.addAll(filesToCache);
})
);
})
// The activate handler takes care of cleaning up old caches.
self.addEventListener('activate', event => {
event.waitUntil(self.clients.claim());
});
// The fetch handler serves responses for same-origin resources from a cache.
self.addEventListener('fetch', event => {
// Workaround for error:
// TypeError: Failed to execute 'fetch' on 'ServiceWorkerGlobalScope': 'only-if-cached' can be set only with 'same-origin' mode
// see: https://stackoverflow.com/questions/48463483/what-causes-a-failed-to-execute-fetch-on-serviceworkerglobalscope-only-if
if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin')
return;
event.respondWith(
caches.match(event.request, {ignoreSearch: true})
.then(response => {
return response || fetch(event.request);
})
);
});
manifest.json:
{
"name":"[Hidden]",
"short_name":"[Hidden]",
"start_url":"/application/login_pages/login_mobile_tablet.jsf",
"scope":".",
"display":"standalone",
"background_color":"#4688B8",
"theme_color":"#4688B8",
"orientation":"landscape",
"icons":[
{
"src":"javax.faces.resource/images/icons/qsc_128.png.jsf",
"sizes":"128x128",
"type":"image/png"
},
{
"src":"javax.faces.resource/images/icons/qsc_144.png.jsf",
"sizes":"144x144",
"type":"image/png"
},
{
"src":"javax.faces.resource/images/icons/qsc_152.png.jsf",
"sizes":"152x152",
"type":"image/png"
},
{
"src":"javax.faces.resource/images/icons/qsc_192.png.jsf",
"sizes":"192x192",
"type":"image/png"
},
{
"src":"javax.faces.resource/images/icons/qsc_256.png.jsf",
"sizes":"256x256",
"type":"image/png"
},
{
"src":"javax.faces.resource/images/icons/qsc_512.png.jsf",
"sizes":"512x512",
"type":"image/png"
}
]
}
The following questions / answers were considered - but no solution was found:
PWA wont open in standalone mode on android
WebAPK ignores display:standalone flag for PWA running on local network
PWA deployed in node.js running in Standalone mode on Android and iOS
Technical Background
The Moment you add your Service-Worker (along all other PWA-Requirements) your App gets created as an Real PWA - with Web-APK getting installed.
Therefore you also need to use Default-HTTPS-Port 443 - make sure you use a valid HTTPS-Certificate.
Before adding the Service-Worker, this mandatory requirement was missing so your PWA was NOT installed and therefore needed less other requirements to be displayed in "standalone-mode".
It's just a shame that this is nowhere documented... and we had to "find out" for ourselves.
Short-List of Mandatory Requirements for "Installable Web-APK":
(As we could not find a full List, i try to include all Points)
Registered Service-Worker (default-implementation like yours is enough)
manifest.json (yours is valid)
https with valid certificate
https default-port (443, eg. https://yourdomain.com/test/)
... for the rest just check chrome audit tool (HINT: you don't need to pass all requirements - your web-apk should work when switching to https-default-port)

Opening market from ionic fails

I have this ionic app where I put code to open the browser and go to app store or google play, depending on OS.
The call to App Store works. The string for app store is:
market = 'https://itunes.apple.com/us/app/my_app_name/id12345';
while for android is:
market = 'market://details?id=<package_name>';
The code to open the browser is:
cordova.InAppBrowser.open(market, '_blank', 'location=yes');
When I try to open in android, some kind of browser opens and displays the message:
"Web page not available. The webpage at market://details?id=my_app_id might be temporarly down ..."
Before this, the string for google play was the one you normally use in a browser, which is:
http://play.google.com/store/apps/details?id=<package_name>
In that case the message was about the broser not supporting the call to google play. It asked if I wanted to download google play app.
I guess the right way is to use the "market"-prefix? But still dont understand why its not showing the app.
Ok, so I looked into 'cordova-plugin-market' source code for ios. This is how the url to appstore is built:
NSString *url = [NSString stringWithFormat:#"itms-apps://itunes.apple.com/app/%#", appId];
And this is how url looks if you want to navigate from PC browser:
https://itunes.apple.com/app/id333903271 (twitter for example)
So if you use this plugin for Ios, consider adding 'id' prefix, and instead of using bundle Id (package name) use Apple ID of your app. For android of course com.example.package will be enough
let appId;
if (this.platform.is("android")) {
appId = "com.example.package"
} else {
appId = "id1234567"
}
this.market.open(appId).then(response => {
console.debug(response);
}).catch(error => {
console.warn(error);
});
}
I added
cordova plugin add https://github.com/xmartlabs/cordova-plugin-market
And then it worked.
import { InAppBrowserOptions, InAppBrowser } from '#ionic-native/in-app-browser';
import { Market } from "#ionic-native/market";
import { Platform } from "ionic-angular";
constructor(private market:Market, private inappBrowswer:InAppBrowser,
private platform:Platform)
{
this.onUpdateNow();//Call the update function
}
onUpdateNow() {
this.platform.ready().then(() => {
if (this.platform.is("ios")) {
//replace '310633997' with your iOS App ID
this.openInAppStore('itms-apps://itunes.apple.com/app/310633997'); //call the openInAppStore
} else if (this.platform.is("android")) {
//replace 'com.whatsapp.saint' with your Android App ID
this.market.open("com.whatsapp.saint").then(response => {
console.log(response);
}).catch(error => {
console.log(error);
});
}
});
}
openInAppStore(link) {
let options: InAppBrowserOptions = {
location: 'yes',//Or 'no'
};
let target = "_blank";
this.inappBrowswer.create(link, target, options);
}
I tried the plugin with capacitor and its working like a charm using the package name and the app id (for android and ios accordingly):
public goToStore() {
const appId = 1234512345;
const packageName = 'com.test.app';
Capacitor.getPlatform() === 'android' ? this.market.open(packageName) : this.market.open(appId);
}
The plugins:
"#ionic-native/market": "5.36.0",
"cordova-plugin-market": "1.2.0",

Facebook Phonegap plugin - Able to log in (it seems) but cannot get access token

I am having trouble getting the phonegap facebook plugin to work. Did the following steps:
I followed the automatic installation on https://github.com/phonegap/phonegap-facebook-plugin,
added facebook-js-jdk and cdv-plugin-fb-connect to my platforms/android/assets/www folder
replaced a line in the config.xml < feature name="FacebookConnectPlugin" > to < feature name="org.apache.cordova.facebook.Connect" > (otherwise it never worked)
On startup, I get a "Cordova Facebook Connect plugin failed on init". Along with this, when I run my (copied and pasted) login function, in the logcat, a login object is returned with all of my information (name, correct userID, email, education and so on...), it says "User cancelled login or did not fully authorize". What's strange is that my getLoginStatus function seems to work properly, but doesn't return an access token. When it runs, it says that I am connected to Facebook, but in the logcat I see "cannot read property 'userID' of undefined".
I tried what was suggested by java.lang.RuntimeException: Failure delivering result ResultInfo while logging using Facebook (Don't keep activities on) but that didn't work. Any help would be appreciated, I have been trying to get this to work for an embarrassingly long time now... My functions are below:
function testLogin(){
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
FB.logout(function(response) {
console.log('Logged out.');
});
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: 'email'});
}
function getLoginStatus() {
FB.getLoginStatus(function(response) {
if (response.status == 'connected') {
alert('You are connected to Fb');
var fbid = response.authResponse.userID;
var token = response.authResponse.accessToken;
//console.log(response.authResponse.userID);
//console.log(response.authResponse.accessToken);
alert(response);
} else {
alert('not connected to FB');
}
});
}
function logout() {
FB.logout(function(response) {
alert('logged out');
});
}
The namespace has changed. Instead of using:
FB.login(...
You should use:
facebookConnectPlugin.login(...
And replace FB with facebookConnectPlugin elsewhere.
Read the read me.md at https://github.com/phonegap/phonegap-facebook-plugin, it might help you to keep everything up-to-date ;)

Categories

Resources