How to translate a text for a toast message - admin-on-rest

I want to use translation for a toast message. How can I do it?
See the code below:
fetch(request).then(response => {
if (response.status < 200 || response.status > 300) {
// throw new Error(response.statusText);
} // if
return response.json();
}).then (({token, message}) => {
if (token) {
localStorage.setItem('token', token);
} else {
throw new Error((translate('pos.search')));
} // else
});

Related

Service Worker "notificationclick" not firing

The notification is showing fine, but when I click on it, or any of the actions, nothing happens. I see no logging, no error messages, but the notification does close (although it closes even when I comment out the event.notification.close()).
I've tried using the Chrome debugger, and I can set a break point in the code that shows the notification, but all breakpoints within the notificationclick handler fail to pause execution.
I've spent days trying to get this to work and I'm at my wits' end.
const auth = firebase.auth();
const functions = firebase.functions();
const done = functions.httpsCallable("done");
const snooze = functions.httpsCallable("snooze");
self.addEventListener("notificationclick", event => {
console.log("notificationclick", event);
const uid = auth.currentUser.uid;
const { id, url } = event.notification.data;
event.notification.close();
event.waitUntil(() => {
switch (event.action) {
case "done":
console.log("Done");
return done({ uid, id });
case "snooze1":
console.log("Snooze 1 Hour");
return snooze({ uid, id, hours: 1 });
case "snooze24":
console.log("Snooze 1 Day");
return snooze({ uid, id, hours: 24 });
default:
console.log("Open App");
return clients
.matchAll({
includeUncontrolled: true,
type: "window"
})
.then(clientList => {
for (let i = 0; i < clientList.length; i++) {
let client = clientList[i];
if (url[0] === "#") {
if (client.url.endsWith(url) && "focus" in client) {
return client.focus();
}
} else {
if (
client.url.replace(/#.*$/, "") === url &&
"focus" in client
) {
return client.focus();
}
}
}
if (clients.openWindow) {
return clients.openWindow(location.origin + url);
}
});
}
});
});
firebase
.messaging()
.setBackgroundMessageHandler(({ data: { title, options } }) => {
options = JSON.parse(options);
options.actions = [
{ action: "done", title: "Done" },
{ action: "snooze1", title: "Snooze 1 Hour" },
{ action: "snooze24", title: "Snooze 1 Day" }
];
return self.registration.showNotification(title, options);
});
Hi Could you try below code and see if this is getting called-
self.addEventListener('notificationclick', function (event) {
event.notification.close();
var redirectUrl = null;
var tag = event.notification.tag;
if (event.action) {
redirectUrl = event.action
}
if (redirectUrl) {
event.waitUntil(async function () {
var allClients = await clients.matchAll({
includeUncontrolled: !0
});
var chatClient;
for (const client of allClients) {
if (redirectUrl != '/' && client.url.indexOf(redirectUrl) >= 0) {
client.focus();
chatClient = client;
break
}
}
if (chatClient == null || chatClient == 'undefined') {
chatClient = clients.openWindow(redirectUrl);
return chatClient
}
}().then(result => {
if (tag) {
//PostAction(tag, "click")
}
}))
}
});
Edited-
Attaching both js files. it is working at my end.
firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-messaging.js');
var config = {
apiKey: "your api key",
authDomain: "you firebase domain",
databaseURL: "your firbase db url",
projectId: "your project id",
storageBucket: "",
messagingSenderId: "sender id"
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload.data);
var notificationTitle = payload.data.Title;
var notificationOptions = {
body: payload.data.Body,
icon: payload.data.Icon,
image: payload.data.Image,
action: payload.data.ClickAction
};
console.log("strated sending msg" + notificationOptions);
return self.registration.showNotification(notificationTitle,notificationOptions);
});
self.addEventListener('notificationclick', function (event) {
console.log('On notification click: ', event.notification);
event.notification.close();
var redirectUrl = null;
if (event.notification.data) {
if (event.notification.data.FCM_MSG) {
redirectUrl = event.notification.data.FCM_MSG.data ? event.notification.data.FCM_MSG.data.click_action : null
} else {
redirectUrl = event.notification.data ? event.notification.data.click_action : null
}
}
console.log("redirect url is : " + redirectUrl);
if (redirectUrl) {
event.waitUntil(async function () {
var allClients = await clients.matchAll({
includeUncontrolled: true
});
var chatClient;
for (var i = 0; i < allClients.length; i++) {
var client = allClients[i];
if (client['url'].indexOf(redirectUrl) >= 0) {
client.focus();
chatClient = client;
break;
}
}
if (chatClient == null || chatClient == 'undefined') {
chatClient = clients.openWindow(redirectUrl);
return chatClient;
}
}());
}
});
self.addEventListener("notificationclose", function (event) {
event.notification.close();
console.log('user has clicked notification close');
});
application.js file :
/// <reference path="scripts/jquery-3.3.1.js" />
try {
var config = {
apiKey: "your api key",
authDomain: "you firebase domain",
databaseURL: "your firbase db url",
projectId: "your project id",
storageBucket: "",
messagingSenderId: "sender id"
};
firebase.initializeApp(config);
if ('serviceWorker' in navigator && 'PushManager' in window) {
console.log('Service Worker and Push is supported');
navigator.serviceWorker
.register('/firebase-messaging-sw.js')
.then((swReg) => {
firebase.messaging().useServiceWorker(swReg);
askForPermissioToReceiveNotifications();
})
.catch(function (error) {
console.error('Service Worker Error', error);
window.alert("Service Worker Error" + error);
})
} else {
console.warn('Push messaging is not supported');
window.alert("Push messaging is not supported " + (navigator.serviceWorker));
}
const askForPermissioToReceiveNotifications = async () => {
try {
const messaging = firebase.messaging();
console.log(messaging);
await messaging.requestPermission();
const token = await messaging.getToken();
if (token !== null || token !== 'undefined') {
await sendDeviceTokenToServerSide(token);
}
console.log('Got token : ' + token);
messaging.onMessage(function (payload) {
console.log('onMessage: ', payload);
setTimeout(() => {
navigator.serviceWorker.ready.then(function (registration) {
var notificationTitle = payload.notification.title;
var notificationOptions = {
body: payload.notification.body,
data: payload.data,
icon: payload.notification.icon,
image: payload.data.Image,
requireInteraction: payload.notification.requireInteraction,
tag: payload.notification.tag,
click_action: payload.data.click_action,
requireInteraction: true
};
registration.showNotification(notificationTitle, notificationOptions);
},50)
});
});
}
catch (e) { console.log('error in getting token: ' + e); window.alert("error in getting token: " + e); }
}
function sendDeviceTokenToServerSide(token) {
$.ajax({
type: 'POST',
url: '/Home/StoreToken',
timeout: 5000000,
data: { token: token },
success: function (success) {
console.log("device token is sent to server");
},
error: function (error) {
console.log("device error sending token to server : " + error);
window.alert("device error sending token to server : " + error);
}
});
}
} catch (e) {
window.alert("error: " + e);
}
function GetFcmUserToken(messaging) {
messaging.onTokenRefresh(function () {
messaging.getToken()
.then(function (refreshedToken) {
console.log('Token refreshed.');
return refreshedToken;
})
.catch(function (err) {
console.log('Unable to retrieve refreshed token ', err);
showToken('Unable to retrieve refreshed token ', err);
});
});
}
self.addEventListener('notificationclick', function (event) {
const clickedNotification = event.notification;
// Do something as the result of the notification click
const promiseChain = clients.openWindow(clickedNotification.data.Url);
event.waitUntil(promiseChain);
});
This code inside service worker js worked fine for me on chrome Desktop and Android.

React native: How to validate username and password while submitting

I have validate username and password,if username and password is wrong ,then i want through error like 'Invalid username/password'.if any one know,pls let me know.
async submit() {
//Validating username and password
const { username, password } = this.state;
if(username == ''){
this.setState({error:'Username is required'});
} else if(password == ''){
this.setState({error:'Password is required'});
} else {
this.setState({error: null})
let collection={};
collection.username=this.state.username;
collection.password=this.state.password;
// console.warn(collection);
var url = 'my url';
try {
let response = await fetch(url,
{
method: 'POST', // or 'PUT'
body: JSON.stringify(collection), // data can be `string` or {object}!
headers: new Headers({
'Content-Type': 'application/json'
})
});
let res = await response.text();
// console.warn(res);
if (response.status >= 200 && response.status < 300) {
//Handle success
let accessToken = res;
console.log(accessToken);
//On success we will store the access_token in the AsyncStorage
this.storeToken(accessToken);
// console.warn(accessToken);
//After storing value,it will navigate to home
this.props.navigation.navigate('Home');
} else {
//Handle error
console.log('Success:',response);
let error = res;
throw error;
}
} catch(error) {
console.log("error " + error);
}
}
}
response after giving invalid username/password:
0 {…}
field :password
message :Incorrect username or password.
I have written code like this based on status to validated username/password is correct/wrong.so here am posting code if it is useful for anyone in future.below code is,
if (response.status >= 200 && response.status < 300) {
//Handle success
let accessToken = res;
//On success we will store the access_token in the AsyncStorage
this.storeToken(accessToken);
console.warn(accessToken);
//After storing value,it will navigate to home
this.props.navigation.navigate('Home');
} else {
console.log('Success:',response);
this.setState({error:'Invalid username/password'});
let error = res;
throw error;
}

Confirm output of spell checker before proceeding in bot framework

I am trying to accomplish this:
I have a spell checker in the middleware. In case the user's input text does not match the corrected text, I would like to confirm the corrected text with the user before proceeding. I tried several approaches but have not been able to achieve this. Here's the code I wrote:
app.js:
var builder = require('botbuilder');
var restify = require('restify');
var spellService = require('./spell-service')
// Setup Restify Server
var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
console.log('%s listening to %s', server.name, server.url);
});
// Create connector and listen for messages
var connector = new builder.ChatConnector({
appId: process.env.MICROSOFT_APP_ID,
appPassword: process.env.MICROSOFT_APP_PASSWORD
});
server.post('/api/messages', connector.listen());
var bot = new builder.UniversalBot(connector, function (session) {
session.beginDialog('search');
});
bot.dialog('search', [
function (session, args, next) {
builder.Prompts.text(session, 'Type the name of a company you would like to search');
}
]);
//=========================================================
// Spell checker
//=========================================================
const dontCorrectIdentifier = "dontCorrect";
bot.use({
botbuilder: function (session, next) {
if (session.message.text.startsWith(dontCorrectIdentifier)) {
session.message.text = session.message.text.replace(dontCorrectIdentifier, "");
next();
} else {
spellService
.getCorrectedText(session.message.text)
.then(function (text) {
if (session.message.text !== text) {
var msg = new builder.Message(session)
.text("Did you mean \"" + text + "\"?")
.suggestedActions(builder.SuggestedActions.create(session, [
builder.CardAction.postBack(session, dontCorrectIdentifier + text, "Yes"),
builder.CardAction.postBack(session, dontCorrectIdentifier + session.message.text, "No")
]
));
builder.Prompts.text(session, msg);
}
next();
})
.catch(function (error) {
console.error(error);
next();
});
}
}
});
spell-service.js
// from https://dev.cognitive.microsoft.com/docs/services/56e73033cf5ff80c2008c679/operations/56e73036cf5ff81048ee6727
var request = require('request');
var SPELL_CHECK_API_URL = 'https://api.cognitive.microsoft.com/bing/v7.0/SpellCheck?mkt=en-US&mode=proof',
SPELL_CHECK_API_KEY = 'MY KEY';
/**
* Gets the correct spelling for the given text
* #param {string} text The text to be corrected
* #returns {Promise} Promise with corrected text if succeeded, error otherwise.
*/
exports.getCorrectedText = function (text) {
return new Promise(function (resolve, reject) {
if (text) {
var requestData = {
url: SPELL_CHECK_API_URL,
headers: {
"Ocp-Apim-Subscription-Key": SPELL_CHECK_API_KEY
},
form: {
text: text
},
json: true
};
request.post(requestData, function (error, response, body) {
if (error) {
reject(error);
} else if (response.statusCode != 200) {
reject(body);
} else {
var previousOffset = 0;
var result = '';
for (var i = 0; i < body.flaggedTokens.length; i++) {
var element = body.flaggedTokens[i];
// append the text from the previous offset to the current misspelled word offset
result += text.substring(previousOffset, element.offset);
// append the first suggested correction instead of the misspelled word
result += element.suggestions[0].suggestion;
// Increment the offset by the length of the misspelled word
previousOffset = element.offset + element.token.length;
}
// Append the text after the last misspelled word.
if (previousOffset < text.length) {
result += text.substring(previousOffset);
}
resolve(result);
}
});
} else {
resolve(text);
}
})
};
Based on Gary's suggestion, here's the right way to do this:
bot.use({
botbuilder: function (session, next) {
if (session.message.text.startsWith(dontCorrectIdentifier)) {
session.message.text = session.message.text.replace(dontCorrectIdentifier, "");
next();
} else {
spellService
.getCorrectedText(session.message.text)
.then(function (text) {
if (session.message.text !== text) {
var msg = new builder.Message(session)
.text("Did you mean \"" + text + "\"?")
.suggestedActions(builder.SuggestedActions.create(session, [
builder.CardAction.postBack(session, dontCorrectIdentifier + text, "Yes"),
builder.CardAction.postBack(session, dontCorrectIdentifier + session.message.text, "No")
]
));
session.send(msg);
} else {
next();
}
})
.catch(function (error) {
console.error(error);
next();
});
}
}
});
Modify the logic flow in the builder middle, which works fine on my side:
bot.use({
botbuilder: (session, next) => {
if (session.message.text.startsWith(dontCorrectIdentifier)) {
session.message.text = session.message.text.replace(dontCorrectIdentifier, "");
next();
} else {
var text = session.message.text;
var msg = new builder.Message(session)
.text("Did you mean \"" + text + "\"?")
.suggestedActions(builder.SuggestedActions.create(session, [
builder.CardAction.postBack(session, dontCorrectIdentifier + text, "Yes"),
builder.CardAction.postBack(session, dontCorrectIdentifier + session.message.text, "No")
]));
session.send(msg);
}
},
})
Use session.send(msg); replace builder.Prompts.text(session, msg).
And remove next() in the else condition.
You need to append text parameter in URL. I tried this in curl:
curl -v -X GET https://api.cognitive.microsoft.com/bing/v7.0/SpellCheck?mkt=en-US&mode=proof&text=hollo%2Cwrld
The other thing is hyphen between spell and service in your .js file. You can probably try to check json response first to see if you are getting correction back.

How to turn on Autorization?

"By default, an admin-on-rest app doesn’t require authentication".
I have written an application with AOR and Loopback API, etc, and it works well. Except for one thing, I can't turn on turn on authentication. Any username/password will work, just like in the Demo.
From what I can see all required components load, AuthClient etc., Loopback is configured and is waiting for user authorization requests but never gets any.
I copy/pasted a lot of Demo's parts...
Any hints please?
I use the unchanged authClient from kimkha aor loopback
import storage from './storage';
export const authClient = (loginApiUrl, noAccessPage = '/login') => {
return (type, params) => {
if (type === 'AUTH_LOGIN') {
const request = new Request(loginApiUrl, {
method: 'POST',
body: JSON.stringify(params),
headers: new Headers({ 'Content-Type': 'application/json' }),
});
return fetch(request)
.then(response => {
if (response.status < 200 || response.status >= 300) {
throw new Error(response.statusText);
}
return response.json();
})
.then(({ ttl, ...data }) => {
storage.save('lbtoken', data, ttl);
});
}
if (type === 'AUTH_LOGOUT') {
storage.remove('lbtoken');
return Promise.resolve();
}
if (type === 'AUTH_ERROR') {
const { status } = params;
if (status === 401 || status === 403) {
storage.remove('lbtoken');
return Promise.reject();
}
return Promise.resolve();
}
if (type === 'AUTH_CHECK') {
const token = storage.load('lbtoken');
if (token && token.id) {
return Promise.resolve();
} else {
storage.remove('lbtoken');
return Promise.reject({ redirectTo: noAccessPage });
}
}
return Promise.reject('Unkown method');
};
};

RXJS observer retry not a function

I would like to use the retry property of the observer to try 3 times before it gives up and throws an error. However when I run the following code I get 'retry is not a function'. Any ideas what is going on ?
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
this._log.debug('SecureHttpService#get: ' + url);
let resultObservable = Observable.create((observer) => {
this._log.debug('resultObservable');
this.tryReActivateToken().then(
(result) => {
this._log.debug('resultObservable#then#result: ' + result);
if (result === true) {
let headers = new Headers();
headers.append('Authorization', 'Bearer ' + this.access_token);
headers.append('X-Requested-With', 'XMLHttpRequest');
// headers.append('Accept', 'json');
this._log.debug(this.access_token);
let superGetObs = super.get(url, { headers: headers, withCredentials: true }).retry(3);
superGetObs.subscribe(
(next) => { observer.onNext(next); },
(error) => { observer.onError(error); },
() => { observer.onCompleted(); }
);
} else {
observer.onError(new Error('Could not log you in automatically'));
}
}, (error) => { this._log.debug('resultObservable#then#error: ' + error); observer.onError(error); });
});
return resultObservable;
}
The full error stack: http://pastebin.com/ScrzsNh0
Make sure you import the retry-operator with import "rxjs/add/operator/retry";

Resources