How to fetch credential for azure cognitive speech services - microsoft-cognitive

I have created a Speech Cognitive services on Azure portal and I would like to follow this guideline. somewhere in the mentioned guideline there is something like the following:
fetch('https://webchat-mockbot.azurewebsites.net/speechservices/token', { method: 'POST' }).
My question is with which address should I replace this part of the code?
I have tried several things with no success. For instance, I tried https://westeurope.api.cognitive.microsoft.com/sts/v1.0/issuetoken and tried to give one of the two keys that I see under Keys and Endpoints as the parameter of the post method. But it didn't work.
I even tried using subscription key and the region, but it also didn't work. Maybe I have not used the correct syntax.
I would be grateful if anybody could help me.
Update:
Here is my updated code which still has problem with the microphone:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Web Chat: Cognitive Services Speech Services using JavaScript</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script crossorigin="anonymous" src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
<style>
html,
body {
height: 100%;
}
body {
margin: 0;
}
#webchat {
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<div id="webchat" role="main"></div>
<script>
function createFetchSpeechServicesCredentials() {
let expireAfter = 0;
let lastPromise;
return () => {
const now = Date.now();
if (now > expireAfter) {
expireAfter = now + 300000;
lastPromise = fetch(
'https://westus.api.cognitive.microsoft.com/sts/v1.0/issueToken',
{ method: 'POST', headers: { 'Ocp-Apim-Subscription-Key': 'my_subscription-key-speech-services' } }
).then(
res => res.json(),
err => {
expireAfter = 0;
return Promise.reject(err);
}
);
}
return lastPromise;
};
}
const fetchSpeechServicesCredentials = createFetchSpeechServicesCredentials();
(async function () {
const res = await fetch('https://directline.botframework.com/v3/directline/tokens/generate',
{ method: 'POST', headers: { Authorization: 'Bearer My_direct_line_secret_key1' } });
const { token } = await res.json();
const webSpeechPonyfillFactory = await window.WebChat.createCognitiveServicesSpeechServicesPonyfillFactory({
credentials: fetchSpeechServicesCredentials
});
window.WebChat.renderWebChat(
{
directLine: window.WebChat.createDirectLine({ token }),
webSpeechPonyfillFactory
},
document.getElementById('webchat')
);
document.querySelector('#webchat > *').focus();
})().catch(err => console.error(err));
</script>
</body>
</html>
For simplicity, I copy the code which worked after the long discussion with #Hury Shen:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Web Chat: Cognitive Services Speech Services using JavaScript</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script crossorigin="anonymous" src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
<style>
html,
body {
height: 100%;
}
body {
margin: 0;
}
#webchat {
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<div id="webchat" role="main"></div>
<script>
(async function () {
const res = await fetch('https://directline.botframework.com/v3/directline/tokens/generate', { method: 'POST', headers: { Authorization: 'Bearer my-directline-secret-key' } });
const { token } = await res.json();
let authorizationToken;
const tokenRes = await fetch(
'https://westeurope.api.cognitive.microsoft.com/sts/v1.0/issuetoken',
{ method: 'POST', headers: { 'Ocp-Apim-Subscription-Key': 'my-cognitive-services-subscription-key' } }
);
if (tokenRes.status === 200) {
region = 'westeurope',
authorizationToken = await tokenRes.text()
} else {
return (new Error('error!'))
}
const webSpeechPonyfillFactory = await window.WebChat.createCognitiveServicesSpeechServicesPonyfillFactory({
authorizationToken: authorizationToken,
region: region
});
window.WebChat.renderWebChat({
directLine: window.WebChat.createDirectLine({ token }),
webSpeechPonyfillFactory: webSpeechPonyfillFactory
}, document.getElementById('webchat'));
})().catch(err => console.error(err));
</script>
</body>
</html>
Best,
Hanna

You need to use one of the keys under "Keys and Endpoints" in the header of your post request but not as the parameter of your post request. Below is a request sample for your reference:
const tokenRes = await fetch(
'https://westus.api.cognitive.microsoft.com/sts/v1.0/issueToken',
{ method: 'POST', headers: { 'Ocp-Apim-Subscription-Key': 'yourCognitiveServicesSubscriptionKey' } }
);
if (tokenRes.status === 200) {
region = 'westus',
authorizationToken = await tokenRes.text()
} else {
return (new Error('error!'))
}
You can also test it in postman. Below screenshot is my test, I put the key in "header" of the post request but not in "Params".
======================Update=====================
According to some test, I think you should use the endpoint address as below:
If do it in one app service, you should use:
https://webchat-mockbot.azurewebsites.net/directline/token
The js code should be:
const res = await fetch('https://webchat-mockbot.azurewebsites.net/directline/token', { method: 'POST' });
const { token } = await res.json();
If just for test(expose the key in page), you should use:
https://directline.botframework.com/v3/directline/tokens/generate
The js code should be:
const res = await fetch('https://directline.botframework.com/v3/directline/tokens/generate', { method: 'POST', headers: { Authorization: 'Bearer your_secret' }});
const { token } = await res.json();
======================Update 2=====================
You can modify your code according to the code below:
let authorizationToken;
const tokenRes = await fetch(
'https://westus.api.cognitive.microsoft.com/sts/v1.0/issueToken',
{ method: 'POST', headers: { 'Ocp-Apim-Subscription-Key': 'yourCognitiveServicesSubscriptionKey' } }
);
if (tokenRes.status === 200) {
authorizationToken = await tokenRes.text()
} else {
return (new Error('error!'))
}
const webSpeechPonyfillFactory = await window.WebChat.createCognitiveServicesSpeechServicesPonyfillFactory( {
authorizationToken: authorizationToken
} );
window.WebChat.renderWebChat({
directLine: directLine,
webSpeechPonyfillFactory: webSpeechPonyfillFactory
}, document.getElementById('webchat') );

Related

Retrieve data from the firebase dynamic link

Im trying to get the data from the generated firebase dynamic link.
I passed Id while generating the dynamic link. I need to get the particular id from the generated dynamic link. Can you please help me.
Where it generates link as :https://thejyotistore.page.link/jNngseAasXzE5SuSA
const ShareLink = ({
fallbackUrl, id, product }) =>
{
const buildLink = async () =>
{
let link = await axios({
method: "POST",
url:
`https://firebasedynamiclinks
.googleapis.com/v1/shortLinks?
key=AIzaSyDNZvtkjAqf8c9esg
gSEzV2 L7. 3vEUv1FfQ`,
headers: {
"Content-Type":
"application/json",
},
data: {
dynamicLinkInfo: {
domainUriPrefix: `https://thejyotistore.page.link`,
link: `https://youtube.com/${id}`,
androidInfo: {
androidPackageName: "com.jyotistore.main",
},
},
},
});
if (link.status === 200 && link.data.hasOwnProperty("shortLink")) {
console.log(link.data.shortLink);
return link.data.shortLink;
}
};
const shareLink = async () =>
{
let shareUrl;
try {
shareUrl = await buildLink();
console.log(shareUrl);
} catch (error) {
console.log(error);
}
try {
if (shareUrl !== "") {
const result = await Share.share({
message: `Hey, ${"\n \n"}I would like to invite you to check out this New App from Jyoti Store. ${"\n \n"} ${product}Download the App now: ${"\n \n"} ${shareUrl}`,
});
}
} catch (error) {
console.log(error);
}
};

When I use the method from composable twice, it works weird

I created a composable as follows to attach a header whenever I use the useFetch function.
export const useCommon = () => {
async function useFetchToken(api: string, option: useFetchTokenTyle){
const autoOption:any = {
headers: (option.headers) ?? { Authorization: 'Bearer ' + ado_token.value }
}
...
return await useFetch(api, {...option,...autoOption})
}
return {
useFetchToken
}
}
and I use this useFetchToken composable twice in one
<script setup lang="ts">
const { useFetchToken } = useCommon()
let {data:category_lists, refresh:cateRefresh} = await useFetchToken('/api/action', {
baseURL: CATEGORY_API,
method: 'post',
body: {
action: 'DoSomeThing',
}
})
let {data:section_lists, refresh:sectionRefresh} = await useFetchToken('/api/action', {
baseURL: CATEGORY_API,
method: 'post',
body: {
action: 'DoSomeThing2',
}
})
Then, a strange result occurs.
"category_lists" affect from second useFetchToken composable.
"category_lists" is overwritten by 2nd useFetchToken composable.
When I delete 2nd useFetchToken part, "category_lists" work correctly.
When I change useFetchToken to useFetch, it will work well all.

Card element with favoris cannot trigger API call

I am really lost with Nextjs. I seem to have understood that I need to use swr but I am not sure that it will work in my case. or even how to make it work.
I have products which have the same component in several pages in my site. On this component, I have a favorites button which must be triggered on all these pages. on click, it must make a POST or DELETE, with a token and the product id.
My component looks like this for the moment and of course, postFavorites and deleteFavoris don't work:
import React, { useEffect, useState } from "react"
import Link from 'next/link'
import Styles from "./card.module.scss"
import axios from 'axios'
export default function Card(props) {
const [favoris, setFavoris] = useState(false);
const deleteFavoris = async () => {
console.log("click");
try {
const res = await axios({
method: 'POST',
url: `${process.env.NEXT_PUBLIC_BASE_API}/favorites`,
headers: {
Authorization: "Bearer " + session.token,
},
body: {
advert: props["#id"]
}
});
} catch (error) {
if (error.response) {
throw new Error(await error.response.data.message)
}
}
}
const postFavoris = async () => {
console.log("click");
try {
const res = await axios({
method: 'DELETE',
url: `${process.env.NEXT_PUBLIC_BASE_API}/favorites`,
headers: {
Authorization: "Bearer " + session.token,
},
body: {
advert: props["#id"]
}
});
} catch (error) {
if (error.response) {
throw new Error(await error.response.data.message)
}
}
}
const handleClick = () => {
if (favoris === true) {
deleteFavoris()
} else {
postFavoris()
}
setFavoris(!favoris)
}
return (
<div className={Styles.card}>
<Link href={"/annonce?id="+props.id} passHref>
<a className={Styles.imageCard} style={{backgroundImage: `url(${props.imageSrc})`}}>
<p className={Styles.localisationCard}><span className="material-icons">location_on</span>{props.localisation}</p>
</a>
</Link>
<div className={Styles.favCard + " " + ((favoris === true) && Styles.active)} onClick={() => handleClick()}></div>
<p className={Styles.titleCard}>{props.title}</p>
<p className={Styles.pricesCard}><span className="material-icons-outlined">local_offer</span>Prix : {props.prices}</p>
<p className={Styles.eligibilitesCard}><span className="material-icons-outlined">check_circle</span>Eligibilité ({props.eligibilities})</p>
</div>
)
}

fcm web push notification- not opening url (using click_action)

As mentioned in the title, I am unable to redirect to a url upon click on the notification. here's my code.
// Index.php
<html>
<meta charset="utf-8"/>
<title>Firebase Messaging </title>
<link rel="manifest" href="manifest.json">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<style>
div {
margin-bottom: 15px;
}
</style>
<body>
<div id="token"></div>
<div id="msg"></div>
<div id="notis"></div>
<div id="err"></div>
<script src="https://www.gstatic.com/firebasejs/4.6.2/firebase.js"></script>
<script>
MsgElem = document.getElementById("msg")
TokenElem = document.getElementById("token")
NotisElem = document.getElementById("notis")
ErrElem = document.getElementById("err")
var config = {
//some PRIVATE value
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging
.requestPermission()
.then(function () {
console.log("Notification permission granted.");
return messaging.getToken()
})
.then(function(token) {
sendToken(token);
setTokenSentToServer(true);
})
.catch(function (err) {
ErrElem.innerHTML = ErrElem.innerHTML + "; " + err
console.log("Unable to get permission to notify.", err);
});
messaging.onMessage(function(payload) {
console.log("Message received. ", payload);
notificationTitle = payload.data.title;
notificationOptions = {
body: payload.data.body,
icon: payload.data.icon,
click_action: payload.data.url,
};
var notification= new
Notification(notificationTitle,notificationOptions);
});
function setTokenSentToServer(sent)
{
window.localStorage.setItem('sentToServer', sent ? 1 : 0);
}
//this is ajax to send token to send.php
function sendToken(token)
{
$.ajax({
url: 'action.php',
method: 'POST',
data: 'tokens=' + token,
}).done(function(result){
console.log(result);
})
}
</script>
</body>
</html>
here's the next page, where i am using cookies to store the token and use it on next page.
<?php
if(isset($_POST['tokens']))
{ if(isset($_COOKIE["tokens"]))
{$tokens=$_POST['tokens'];
}
else
{
$tokens=$_POST['tokens'];
setcookie("tokens", $tokens, time() + (86400 * 30), "/");
}
}
header("Location: send.php");
?>
then the token is processed on send.php most likely with
<?php
$tokens= array($_COOKIE["tokens"]);
$msg=[
'title'=>'Title',
'body'=>'description.',
'icon'=>'logo.jpg',
'url'=>"https://google.com"
];
$payload=[
'registration_ids'=>$tokens,
'data'=>$msg
];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://fcm.googleapis.com/fcm/send",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS =>json_encode($payload),
CURLOPT_HTTPHEADER => array(
"authorization: key=/*the key*/",
"cache-control: no-cache",
"content-type: application/json",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
}
else
echo $response;
?>
and finally the service worker,
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-
messaging.js');
// Initialize the Firebase app in the service worker by passing in the
// messagingSenderId.
firebase.initializeApp({
'messagingSenderId': 'MY_SENDER_ID'
});
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ',payload);
// Customize notification here
const notificationTitle = payload.data.title;
const notificationOptions = {
body: payload.data.body,
icon: payload.data.icon,
click_action: payload.data.url,
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
The notification is coming very well, but whenever i click on it, it doesn't redirect. can anyone help me out with this code please.
thanks in advance.

.orderByChild() is not working on Firebase (vue.js)

I'm trying to sort my data by using .orderByChild, but the data are filter by the name of the node.
I added this on Firebase :
"concerts": {
".indexOn": "expires"
}
And here is my code in my index.js file :
loadConcerts ({commit}) {
commit('setLoading', true)
firebase.database().ref("concerts").orderByChild("expires").startAt(Date.now()/1e3).limitToFirst(7).once("value")
.then((data) => {
const concerts = []
const obj = data.val()
for (let key in obj) {
concerts.push({
expires: obj[key].expires,
...
})
}
commit('setLoadedConcerts', concerts)
commit('setLoading', false)
})
I also add this :
getters: {
loadedConcerts (state) {
return state.loadedConcerts.sort((concertA, concertB) => {
return concertA.expires > concertB.expires
})
},
loadedConcert (state) {
return (concertId) => {
return state.loadedConcerts.find((concert) => {
return concert.id === concertId
})
}
Maybe someone has a clue ? Thank you
In order to list the value in the correct order (by expires) you should use the forEach() method and not use directly data.val().
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Title</title>
<script src="https://www.gstatic.com/firebasejs/5.5.8/firebase.js"></script>
</head>
<body>
<script>
// Initialize Firebase
var config = {
apiKey: '......',
authDomain: '......',
databaseURL: '......',
projectId: '......',
storageBucket: '......'
};
firebase.initializeApp(config);
firebase
.database()
.ref('past')
.orderByChild('expires')
.startAt(Date.now() / 1e3)
.limitToFirst(7)
.once('value')
.then(data => {
const concerts = []
data.forEach(element => {
console.log(element.val());
concerts.push({ id: element.key, expires: element.val().expires});
});
});
</script>
</body>
</html>
PS: if you want to order with the reverse order, just store in another field the value of -1*expires

Resources