Expo react native push notifications webview move - javascript

Nice to meet you.
I'm junior developer.
I made hybrid app(webview) by react natvie expo + php + mysql
this application have a push notification.
When I click on this, I want to go to a specific page. This page should go to a specific page, not the main page, not open browser by chrome, Safari... when the app opens.
how to make it?? please, help me.
Below is the code I made.
useEffect(() => {
registerForPushNotificationsAsync().then((token) => {
let url = "myUrl";
fetch(url, {
method: "POST",
headers: {
"Content-Type": "multipart/form-data",
},
body: JSON.stringify({ token: token }),
})
.then()
.catch((err) => console.log(err));
setExpoPushToken(token);
});
notificationListener.current =
Notifications.addNotificationReceivedListener((notification) => {
setNotification(notification);
});
responseListener.current =
Notifications.addNotificationResponseReceivedListener((response) => {
const url = response.notification.request.content.data.url;
// console.log(url); i can see specific url.
Linking.openURL(url);
// IntentLauncher.startActivityAsync("android.intent.action.View", {data: url});
});
return () => {
if (
typeof notificationListener.current !== "undefined" &&
typeof responseListener.current !== "undefined"
) {
Notifications.removeNotificationSubscription(
notificationListener.current
);
Notifications.removeNotificationSubscription(responseListener.current);
}
};
}, []);

Related

Get Device Id Using Angular 10 Cordova

I am Creating A Mobile application With Angular 10 + Cordova + Node. Here I have to send some push notification... I have done push notification with Ionic Angular && I have did in this project (web version) Thats working Perfectly with Firebase.. But no idea how to with native (Cordova) .
Asking help For:
How to retrieve device id for Push notification ? (I guess the Back End Part Will Be Same Just Have To Provide The Device Id For Mobile Device)
Here is The code in Backend (For Clearing Confusion)
exports.everyDayDueDate = () => {
task
.find()
.populate([
{
path: "project_id",
model: project,
select: ["project_name"],
},
])
.sort({ status: 1 })
.then((result) => {
result.data.forEach((element) => {
const a = new Date(new Date().toISOString());
const b = new Date(element.taskCompletedate);
if (b.getDate() - a.getDate() == 1) {
User.findById(element.user_id).then((result) => {
if (result) {
let deviceId = result.deviceId;
const payload = {
notification: {
title: element.task_name,
body: "Working!",
},
to: deviceId,
};
const options = {
method: "POST",
uri: "https://fcm.googleapis.com/fcm/send",
body: payload,
json: true,
headers: {
"Content-Type": "application/json",
Authorization:
"key=AAAAL0qgxio:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
},
};
request(options);
}
});
}
});
});
};
I just need to provide the device id to my backend, How Can I get That
*** Not Ionic ***
cordova plugin add cordova-plugin-device
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(device.uuid);
}
https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-device/index.html

Why isn't this 'if' statement working to call my function only if the condition is met?

I'm not the author of this code originally, so apologies for gaps in my knowledge.
I have this function, getRecommendations, which determines whether a user's current domain (parsed from url), matches any within an array called 'domains.' If so, we want to call fetchRecommendations. If no match, we should return without calling the function. Right now, fetchRecommendations is being called regardless of the user's current domain. I'm a bit stumped. Is it a misplaced return? Are we not calling fetchRecommendations correctly? Grateful for any insight.
As a side note, it was suggested to me that the issue was the 'return.' But I tried different placements and it appeared to break the code.
export const getRecommendations = url =>
browser.storage.local.get("domains").then(({ domains }) => {
const domain = parseDomain(url);
if (domains.includes(domain)) {
return fetchRecommendations(url);
}
else {
return;
}
});
export const fetchRecommendations = url =>
browser.storage.local.get("user").then(({ user }) =>
fetch(trestle.api.recommendations, {
method: "POST",
body: JSON.stringify({ currentUrl: url, emailAddress: user.username }),
headers: {
Authorization: `Bearer ${user.token}`,
Accept: "application/json",
"Content-Type": "application/json"
}
})
.then(response => response.json())
.then(recommendation => recommendation)
.catch(e => new Error("Unable to return recommendations for company"))
);
I think this is where we set the domains to storage:
export const getAnalyzedDomains = () =>
fetch(trestle.api.domains)
.then(response => response.json())
.then(domains =>
browser.storage.local.set({ domains }).then(() => domains)
);
Also, here is the parseDomain function, imported from a different file (This file imported parse from psl):
export const parseDomain = url => {
if (url === undefined || url === null) {
return "";
}
const protocol = url.indexOf("://");
url = url.substr(protocol + 3, url.length);
const pos = url.indexOf("/") === -1 ? url.length - 1 : url.indexOf("/");
const domain = url.substr(0, pos);
return parse(domain).domain || "";
};

Unable to get fetch response on react native app

I am stuck on one of the mysterious issue. The problem goes like this:
What I Do??
Simply do login api call and if login success then I have to fetch amount of data from 5-6 api calls and store them in local database (Realm). Here is my code.
login(email, password) {
this.toggleLoadingFunction(true);
fetch(LoginURL, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: email,
password: password,
request_from: 'mobile'
}),
})
.then(async res => {
if (res.ok) {
let data = await res.json();
global.user = data['user']
global.token = data['token']
getAllMasterDataAndSaveInRealm().then(() => {
this.toggleLoadingFunction(false);
global.storage.save({ key: 'LoggedInData', data: data });
this.props.navigation.navigate('Project', data);
}).catch(() => {
this.toggleLoadingFunction(false);
Alert.alert("Master Data Failed !!!");
})
} else {
this.toggleLoadingFunction(false);
let data = await res.json();
Alert.alert("Login Failed!!!", data.message)
}
})
.catch(error => {
this.toggleLoadingFunction(false);
Alert.alert("Network Error. Please try again.")
})
Here getAllMasterDataAndSaveInRealm() is lies on helper function which calls 5-6 apis and response back if all work is done. Here is how it looks like:
export const getAllMasterDataAndSaveInRealm = () => {
const token = global.token;
return new Promise.all([
getMaterials(token),
getEquipments(token),
getObjective(token),
getCategories(token),
getNcData(token),
getPlans(token)]
);
}
Each function inside getAllMasterDataAndSaveInRealm() returns Promise after successfully stored data in local realm db. Here is one of the above function.
export const getActivityPlan = (token) => {
return new Promise((resolve, reject) => {
return fetch(FetchActivityPlanDataURL, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'access_token': `${token}`
}
}).then((response) => {
console.log("Activity Plans Api response", response);
return response.json()
})
.then((responseJson) => {
const { data } = responseJson
console.warn("Activity Plans Api", data);
global.realm.write(() => {
for (var item of data) {
item.id = item.id ? item.id : 0;
item.activity_id = item.activity_id ? item.activity_id.toString() : "";
item.activity_name = item.activity_name ? item.activity_name.toString() : "";
item.activity_cost = item.activity_cost ? item.activity_cost.toString() : "";
item.project_id = item.project_id ? item.project_id : 0;
global.realm.create("ActivityPlan", item, true);
}
})
resolve(data);
})
.catch((error) => {
reject(`Activity Plan Failed ${error}`)
});
})
}
All remaining functions are same as above ( what they do is simply fetch data from api and store it in realm and resolve or reject)
What I Expect:
getAllMasterDataAndSaveInRealm() function Just store all the required data in db and let me know all done and then navigate to the another screen, as Login and fetching data is done.
Problem:
When I do run the app and process for login, Sometimes it works fine but most of the time App stuck on showing loader since some of the api call among 6 api from above do not get response from the request ( I do log the response) on wifi. But when I use mobile data and VPN it always works.
When I log request on server console, response is sent with code 200, but app is unable to get response for the request.
I am new on react native. I do lots of searches over internet but unable to find the solution. I don't have any idea whats going wrong with the code. Please help me out.
Project Configurations:
"react": "16.8.6",
"react-native": "0.60.4",
"realm": "^2.29.2",
Node version: v9.0.0

Global state in React Native in first load of the App

so im trying to make a App that loads all the thing in the loading screen/splash/auth screen.
So I in the basic I have a Welcome, Login and Home screen for now.
Welcome will be showing if the App is open for first time, Login if the user is opening the App without login or is logged out before closing the App and Home will be open if the user is logged in.
Here is the simply check:
componentDidMount() {
AsyncStorage.getItem("alreadyLaunched").then(value => {
if (value == null) {
AsyncStorage.setItem('alreadyLaunched', 'true'); // No need to wait for `setItem` to finish, although you might want to handle errors
this.setState({ firstLaunch: 'true' });
}
else {
this.setState({ firstLaunch: 'false' });
}
})
}
loadApp = async () => {
const userToken = await AsyncStorage.getItem('userToken')
setTimeout(
() => {
if (this.state.firstLaunch == 'true') {
this.props.navigation.navigate('Welcome')
} else {
if (userToken) {
this.props.navigation.navigate('App')
} else {
this.props.navigation.navigate('SignIn')
}
}
}, 0
);
}
And if the login is correct I just put this on Async:
AsyncStorage.setItem("userToken", "logged");
This for now its working perfectly, but I need to get 3-4 for functions to get information to the server then State It. Here is one of the functions:
getSignalsCount = async (username, password) => {
try {
var DeviceInfo = require('react-native-device-info');
//AUTH
fetch(Config.SERVER_URL + '/mob/auth', {
method: 'POST',
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
code: "1",
id: "",
sessId: "",
data: {
u: username,
p: password,
}
})
}).then((response) => response.json())
.then((res) => {
let res_code = res['code'];
let session = "";
let cl_id = 0;
let name = "";
if (res_code == 51) {
session = res['session'];
cl_id = res["data"]["response"]["client_id"];
name = res["data"]["response"]["name"];
this.setState({fullName:name});
//GET STATS
fetch(Config.SERVER_URL + '/mob/sport/getSignalsInfo', { //home
method: 'POST',
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
code: "9",
sessId: session,
data: {
devId: '1234567890',
devName: DeviceInfo.getUniqueID(),
u: username,
client_id: cl_id,
type: {
nums: 50000,
period: 12
}
}
})
}).then((response) => response.json())
.then((res) => {
var closed = res["data"]["response"]["data"]["closed"];
var opened = res["data"]["response"]["data"]["open"];
this.setState({ total_active_signals: opened, total_closed_signals: closed })
})
.done();
}
})
.done()
}
};
So if set this function on the Auth.js and then use it on the same screen with {this.state.total_active_signals} will show me the varible.
But I need it to be show also on HOME or maybe LOGIN and other pages that I may created in future. So I basic need this state to be use on maybe every screen.
I tried to create a global.js with:
module.exports = {
username: '',
};
And then in HOME:
//.....
import global from '../../global'
//....
<Text>Username: {GLOBAL.username}</Text>
But the question now is how to fill the global.js with the state so that, Home/Login/Profile/Stuff screens to get it later.
Thanks!
You basically have two options:
Use Redux and create an app wide state (store) to which all
components have access to (recommended). Your idea of a global state
fits pretty good with the concept of redux.
Pass data as props between components. You can also use a navigation library
to deal with this (e.g. react navigation or react native router
flux)

coverting javascript to python

I have a yale smart alarm and come across the the below javascript that allows you to access the alarm to get the status and set it. I'm wanting to use this in my home assistant set to which uses python.
const fetch = require('node-fetch');
const setCookie = require('set-cookie-parser');
const urls = {
login: 'https://www.yalehomesystem.co.uk/homeportal/api/login/check_login',
getStatus: 'https://www.yalehomesystem.co.uk/homeportal/api/panel/get_panel_mode',
setStatus: 'https://www.yalehomesystem.co.uk/homeportal/api/panel/set_panel_mode?area=1&mode=',
};
function getSessionCookie(username, password) {
let sessionCookie = null;
return fetch(urls.login, {
method: 'POST',
body: `id=${encodeURIComponent(username)}&password=${password}&rememberme=on&notify_id=&reg_id=Name`,
headers: {
'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'
},
})
.then((res) => {
sessionCookie = res.headers._headers['set-cookie'];
return res.json();
}).then(json => {
if (json.result === '0') {
return Promise.reject('Incorrect account details');
}
else {
return sessionCookie[0];
}
})
}
function getStatus(sessionCookie) {
return fetch(urls.getStatus, {
method: 'POST',
headers: {
'Cookie': sessionCookie,
},
}).then(res => res.text()).then(textResponse => {
// When initially writing this code I found if cookie payload
// was invalid I got this text response so I added this code to
// handle this, shouldn't happen but good to have an error message
// for this use case
if (textResponse === 'Disallowed Key Characters.') {
return Promise.reject('Invalid request');
}
else {
try {
// Hopefully if we got to this point we can parse the json
const json = JSON.parse(textResponse);
if (json.result === '0') {
return Promise.reject('Unable to get status');
}
else {
return json;
}
} catch (error) {
// If you get this error message I likely have not handled
// a error state that I wasnt aware of
return Promise.reject('Unable to parse response');
}
}
});
}
function setStatus (sessionCookie, mode) {
return new Promise((resolve, reject) => {
if (!sessionCookie || sessionCookie.length === 0) {
reject('Please call getSessionCookie to get your session cookie first');
}
if (mode !== 'arm' && mode !== 'home' && mode !== 'disarm') {
reject('Invalid mode passed to setStatus');
}
resolve(fetch(`${urls.setStatus}${mode}`, {
method: 'POST',
headers: {
'Cookie': sessionCookie,
},
}));
});
}
module.exports = {
getSessionCookie,
getStatus,
setStatus,
}
i'm every new to coding but was able to piece the below together to return the current status of my alarm. the problem is I'm unable to get it to work. based on the above code could someone please tell me what I'm missing, or if I'm going down the wrong rabbit hole....
import requests
import webbrowser
url = “https://www.yalehomesystem.co.uk/homeportal/api/login/check_login”
payload = {‘username’: ‘email#domaim.com’, ‘password’: ‘mypass’}
with requests.session() as s:
# fetch the login page
s.get(url, data=payload)
url1='https://www.yalehomesystem.co.uk/homeportal/api/panel/get_panel_mode'
# post to the login form
r = s.post(url1, data=payload)
print(r.text)
To add more contexts I'm getting the following error
{"result":"0","message":"system.permission_denied","code":"999"}

Categories

Resources