how to get signal strength of sim network using Nativescript? - nativescript

import * as application from 'application';
const TnsOneSignal = require('nativescript-onesignal').TnsOneSignal
if (application.android) {
application.on(application.launchEvent, function(args: application.ApplicationEventData) {
try {
console.log('TnsOneSignal', TnsOneSignal)
TnsOneSignal.startInit(application.android.context).init()
} catch (error) {
console.log('error', error)
}
})
}
I tried using above code and plugin but it does not work..
Can anyone help please with my code or provide better solution!

TO get the signal strength of the current mobile phone you could use the native APIs on Android and iOS and convert the code to JavaScript based on the NativeScript's marshaling rules.
For example, let's take this native solution. Here is how it would look like in NativeScript
let telephonyManager = application.android.context.getSystemService(android.content.Context.TELEPHONY_SERVICE);
let cellinfogsm = telephonyManager.getAllCellInfo().get(0);
let cellSignalStrengthGsm = cellinfogsm.getCellSignalStrength();
cellSignalStrengthGsm.getDbm();
Of course, in Android to be able to get this information you would need an explicit permission for ACCESS_COARSE_LOCATION so you could use nativescript-permissions plugin to grant them.
Here you can find a test project demonstrating the above technique. based on the same principle you could find an iOS example and convert the code to JS using the marshaling from Objective-C to JS.

Related

How to allow clients to hook into preconfigured hooks in application

I have a pretty standard application with a frontend, a backend and some options in the frontend for modifying data. My backend fires events when data is modified (eg. record created, record updated, user logged in, etc.).
Now what I want to do is for my customers to be able to code their own functions and "hook" them into these events.
So far the approaches I have thought of are:
Allowing users in the frontend to write some code in a codeeditor like codemirror, but this whole storing code and executing it with some eval() seems kind of risky and unstable.
My second approach is illustrated below (to the best of my ability at least). The point is that the CRUD API calls a different "hook" web service that has these (recordUpdated, recordCreated, userLoggedIn,...) hook methods exposed. Then the client library needs to extend some predefined interfaces for the different hooks I expose. This still seems doable, but my issue is I can't figure out how my customers would deploy their library into the running "hook" service.
So it's kind of like webhooks, except I already know the exact hooks to be created which I figured could allow for an easier setup than customers having to create their own web services from scratch, but instead just create a library that is then deployed into an existing API (or something like that...). Preferably the infrastructure details should be hidden from the customers so they can focus solely on making business logic inside their custom hooks.
It's kind of hard to explain, but hopefully someone will get and can tell me if I'm on the right track or if there is a more standard way of doing hooks like these?
Currently the entire backend is written in C# but that is not a requirement.
I'll just draft out the main framework, then wait for your feedback to fill in anything unclear.
Disclaimer: I don't really have expertise with security and sandboxing. I just know it's an important thing, but really, it's beyond me. You go figure it out 😂
Suppose we're now in a safe sandbox where all malicious behaviors are magically taken care, let's write some Node.js code for that "hook engine".
How users deploy their plugin code.
Let's assume we use file-base deployment. The interface you need to implement is a PluginRegistry.
class PluginRegistry {
constructor() {
/**
The plugin registry holds records of plugin info:
type IPluginInfo = {
userId: string,
hash: string,
filePath: string,
module: null | object,
}
*/
this.records = new Map()
}
register(userId, info) {
this.records.set(userId, info)
}
query(userId) {
return this.records.get(userId)
}
}
// plugin registry should be a singleton in your app.
const pluginRegistrySingleton = new PluginRegistry()
// app opens a http endpoint
// that accepts plugin registration
// this is how you receive user provided code
server.listen(port, (req, res) => {
if (isPluginRegistration(req)) {
let { userId, fileBytes, hash } = processRequest(req)
let filePath = pluginDir + '/' + hash + '.js'
let pluginInfo = {
userId,
// you should use some kind of hash
// to uniquely identify plugin
hash,
filePath,
// "module" field is left empty
// it will be lazy-loaded when
// plugin code is actually needed
module: null,
}
let existingPluginInfo = pluginRegistrySingleton.query(userId)
if (existingPluginInfo.hash === hash) {
// already exist, skip
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('ok');
} else {
// plugin code written down somewhere
fs.writeFile(filePath, fileBytes, (err) => {
pluginRegistrySingleton.register(userId, pluginInfo)
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('ok');
})
}
}
})
From the perspective of hook engine, it simply opens a HTTP endpoint to accept plugin registration, agnostic to the source.
Whether it's from CI/CD pipeline, or plain web interface upload, it doesn't matter. If you have CI/CD setup for your user, it is just a dedicated build machine that runs bash scripts isn't it? So just fire a curl call to this endpoint to upload whatever you need. Same applies to web interface.
How we would execute plugin code
User plugin code is just normal Node.js module code. You might instruct them to expose certain API and conform to your protocol.
class HookEngine {
constructor(pluginRegistry) {
// dependency injection
this.pluginRegistry = pluginRegistry
}
// hook
oncreate(payload) {
// hook call payload should identify the user
const pluginInfo = this.pluginRegistry.query(payload.user.id)
// lazy-load the plugin module when needed
if (pluginInfo && !pluginInfo.module) {
pluginInfo.module = require(pluginInfo.filePath)
}
// user plugin module is just normal Node.js module
// you load it with `require`, and you call what ever function you need.
pluginInfo.module.oncreate(payload)
}
}

Using `createMockClient` for testing non react code?

I have mixed application that uses Apollo for both React and non-react code.
However, I can’t find documentation or code examples around testing non-react code with the apollo client,not using MockedProvider. I did, however, notice that apollo exports a mock client from the testing directory.
import { createMockClient } from '#apollo/client/testing';
I haven’t found any documentation about this API and am wondering if it’s intended to be used publicly and, if not, what the supported approach is for this.
The reason I need this is simple: When using Next.js’ SSR and/or SSG features data fetching and actual data rendering are split into separate functions.
So the fetching code is not using React, but Node.js to fetch data.
Therefore I use apolloClient.query to fetch the data I need.
When trying to wrap a react component around that fetching code in a test an wrap MockedProvider around that the apolloClient’s query method always returns undefined for mocked queries - so it seems this only works for the useQuery hook?
Do you have any idea how to mock the client in non-react code?
Thank you for your support in advance. If you need any further information from me feel free to ask.
Regards,
Horstcredible
I was in a similar position where I wanted to use a MockedProvider and mock the client class, rather than use useQuery as documented here: https://www.apollographql.com/docs/react/development-testing/testing/
Though it doesn't seem to be documented, createMockClient from '#apollo/client/testing' can be passed the same mocks as MockedProvider to mock without useQuery. These examples assume you have a MockedProvider:
export const mockGetAssetById = async (id: Number): Promise<any> => {
const client = createMockClient(mocks, GetAsset)
const data = await client.query({
query: GetAsset,
variables: id,
})
return data
}
Accomplishes the same as:
const { data } = useQuery(
GetAsset,
{ variables: { id } }
)

LiveQuery does not work, if there is no ParseConnectivityProvider provided

Racking my brains over this.
I cannot get past this issue, my code is producing this error:
LiveQuery does not work, if there is no ParseConnectivityProvider provided.
I tried playing around with the liveQueryURL and no luck. The flutter docs have no concrete example on how to implement this url from the server. I assume from the javaScript video and docs that it's my custom subdomain I created such as customdomain.b4a.io which makes the final url 'wss://customdomain.b4a.io'.
I looked into "connectivityProvider:" arg for the Parse().initialize but found nothing concrete on implementing this.
This is a dart demo project only. Any help or ideas much appreciated!
EDIT: This post does not solve my problem at all. It's also very old.
Is it possible this isn't working because this is a dart program rather than flutter? Wouldn't imagine this being the case...
Code:
import 'package:parse_server_sdk/parse_server_sdk.dart';
Future<void> main(List<String> arguments) async {
final keyApplicationId = 'XXX';
final keyClientKey = 'XXX';
final keyParseServerUrl = 'https://parseapi.back4app.com';
final liveQueryURL = 'wss://XXX.b4a.io';
await Parse().initialize(
keyApplicationId,
keyParseServerUrl,
clientKey: keyClientKey,
liveQueryUrl: liveQueryURL,
autoSendSessionId: true,
debug: true,
);
final LiveQuery liveQuery = LiveQuery();
QueryBuilder<ParseObject> query = QueryBuilder<ParseObject>(ParseObject('Color'));
Subscription subscription = await liveQuery.client.subscribe(query);
subscription.on(LiveQueryEvent.create, (value) {
print('Object: ' + value['color']);
print((value as ParseObject).get('color'));
});
}
From https://github.com/parse-community/Parse-SDK-Flutter/issues/543#issuecomment-912783019
please provide a custom ParseConnectivityProvider (connectivityProvider in Parse().initialize).
In case you can assume your device has always internet access, the implementation should be as simple as this:
class CustomParseConnectivityProvider extends ParseConnectivityProvider{
Future<ParseConnectivityResult> checkConnectivity() => ParseConnectivityResult.wifi;
Stream<ParseConnectivityResult> get connectivityStream => Stream<ParseConnectivityResult>.empty();
}
(Not tested and typed on a smartphone.)
Unfortunately parse live query in flutter dose not work with https server url. I faced this problem before and it mades me crazy! What I did was in the backend side of parse server, provide both http and https servers. And In client side in flutter just connect to the http server for live queries!
And that works fine 😉

How to access RadSideDrawer from page?

In Nativescript 5.x (TypeScript) I have successfully used the following code to access a RadSideDrawer:
import * as app from "#nativescript/core/application";
import { EventData } from "#nativescript/core/data/observable";
import { RadSideDrawer } from "nativescript-ui-sidedrawer";
export function drawerLoaded(args: EventData) {
let sideDrawer = <RadSideDrawer>args.object; <--- error
}
Now,with Nativescript 6.4 (and after migrating my app with "tns migrate") I am getting a compiler error on "tns build android":
TS2352: Conversion of type 'View' to type 'RadSideDrawer' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
I have no idea how to fix this. Could anybody tell me what i need to change? That would be super nice. Thank you!
I'm unable to reproduce the issue on my end, it may be something to do with your TS version or configurations.
An easy fix is to cast the object to unknown type as the error description suggests.
let sideDrawer = <RadSideDrawer>(<any>args.object);

How to get isHealthDataAvailable from angular2 nativescript using api

Since that is no nativescript support with ios HealthKit..I am trying to work with the api.
To start I am trying to get a simple bool for isHealthDataAvailable():
How?
declare var NSBundle: any;
constructor() {
if (Platform.isIOS){
let healthStore = NSBundle.mainBundle.HKHealthStore();
let is_avail = healthStore.isHealthDataAvailable();
}
}
(in promise): TypeError: NSBundle.mainBundle.HKHealthStore is not a function. (In 'NSBundle.mainBundle.HKHealthStore()', 'NSBundle.mainBundle.HKHealthStore' is undefined)
This is a quote from NativeScript:
https://www.nativescript.org/blog/how-to-enable-healthkit-in-your-nativescript-application
var healthStore = HKHealthStore.new();
And this is how to use HealthKit API in NativeScript. Yes, it is THAT simple.
I beg differ...
That's not where HKHealthStore lives, please see my answer to your other question where I suggest you install the platform declarations (npm i tns-platform-declarations --save-dev). It will help you tremendously: nativescript, angular2 and heaththkit - HKHealthStore not found;
To answer this question: it should be HKHealthStore.isHealthDataAvailable() as can be seen in the screenshot below (which is a snippet of those aforementioned TypeScript declarations for iOS:
You will need to use the proper syntax for data conversion (between the Objective-C Apple API and JavaScript) as described here
e.g.
var healthStore = HKHealthStore.new();
Great detailed step by step explanation can be found in this blog post

Resources