YouTube Live Streaming API: LiveChatMessages userBannedEvent not showing - youtube-api

I'm currently creating a script that handles the ban events when a user is banned from a YouTube live chat, however the event is never emitted when a user is banned (even when I have mod perms on the stream). For authorization I'm using the youtube.force-ssl scope, but I still don't get the event, only textMessageEvent. Am I passing the improper permission/scope?
For anyone wondering, here's the code I'm using :)
I'm using a modified version of https://github.com/yuta0801/youtube-live-chat (made it so I could pass an authorization token and passing it in the request headers)
const YouTube = require('youtube-live-chat');
const yt = new YouTube("CHANNEL_ID", "API_KEY", "AUTH_TOKEN")
yt.on('ready', () => {
console.log('ready!')
yt.listen(5000)
})
yt.on('message', data => {
console.log(data.snippet.type)
})
yt.on('error', error => {
console.error(error)
})
request function in the lib that I modified
request(url, callback) {
let options = {
url: url,
method: 'GET',
json: true,
headers: {}
}
if(this.auth) options.headers.authorization = `Bearer ${this.auth}`
request(options, (error, response, data) => {
if (error)
this.emit('error', error)
else if (response.statusCode !== 200)
this.emit('error', data)
else
callback(data)
})
}
scope
eventLog

Related

How to send 400KB video back to server on "onpagehide" call

Issue
I have a MediaRecorder video of up to 400 KB that I need to send to the server.
I want to be able to also send the video when someone exits the page.
My code looks kind of like this:
window.onpagehide = (e) => {
e.preventDefault();
var blob = new Blob(this.data, {type: "video/mp4"});
var file = new File([blob], "recording");
var formData = new FormData();
formData.append("recording", file);
axios.post('my-site-url', formData)
.then(function (response) {
if(response.data.result) {
console.log("email has been sent")
} else {
console.log("failed to send email")
}
})
.catch(({response}) => {
console.log("an error occured during email call");
console.error(response);
})
return null;
}
However window.onpagehide doesn't allow async functions so axios.post isn't running at all.
NB: this issue is tested only on IOS Safari.
For Chrome and Edge I am using onbeforeunload and it works fine
Question
What synchronous axios.post alternative can I use for this scenario?
What I tried
navigator.sendBeacon
It looked pretty promising, but it has a limit of 64KB, so I couldn't rely on it.
fetch
fetch('my-site-url', {
method: 'POST',
body: formData
});
error message:
Fetch API cannot load my-site-url due to access control checks.
ajax
$.ajax({
type: 'POST',
async: false,
url: "my-site-url",
data: formData,
processData: false,
timeout: 5000,
});
error message:
XMLHttpRequest cannot load my-site-url due to access control checks.
XMLHttpRequest
var request = new XMLHttpRequest();
request.open('POST', 'my-site-url', false);
request.send(formData);
if (request.status === 200) {
console.log("success!");
}
error message:
XMLHttpRequest cannot load my-site-url due to access control checks.
But these are not CORS related issues, as they only happen when inside onpagehide on Safari.

How to get link to composition by using status callbacks twilio

Here is what I tried but it's not working.
This guy is responsible for creating a composition after the meeting is ended.
app.post('/api/endMeeting', (req, res) => {
const roomSid = req.body.roomSid;
userEmail = req.body.userEmail;
const client = require('twilio')(config.twilio.apiKey, config.twilio.apiSecret, {accountSid: config.twilio.accountSid});
client.video.rooms(roomSid).update({ status: 'completed' });
client.video.compositions.create({
roomSid: roomSid,
audioSources: '*',
videoLayout: {
grid : {
video_sources: ['*']
}
},
statusCallback: `${process.env.REACT_APP_BASE_URL}/api/getMeeting`,
statusCallbackMethod: 'POST',
format: 'mp4'
}).then(() => {
// sendRecordingEmail(composition.sid, userEmail);
res.status(200).send({
message: 'success'
});
}).catch(err => {
res.status(500).send({
message: err.message
});
});
});
And this guy will send the download link of the composition to the participant when it's available.
app.post('/api/getMeeting', (req, res) => {
if (req.query.StatusCallbackEvent === 'composition-available') {
const client = require('twilio')(config.twilio.apiKey, config.twilio.apiSecret, {accountSid: config.twilio.accountSid});
const compositionSid = req.query.CompositionSid;
const uri = "https://video.twilio.com/v1/Compositions/" + compositionSid + "/Media?Ttl=3600";
client.request({
method: "GET",
uri: uri,
}).then((response) => {
const requestUrl = request(response.data.redirect_to);
sendRecordingEmail(requestUrl, userEmail);
res.status(200).send("success");
}).catch((error) => {
res.status(500).send("Error fetching /Media resource " + error);
});
}
});
I can confirm that the composition is created exactly in the Twilio console.
But it seems the status callback guy is not working and I can see the below issue.
It seems I made mistakes in using the status callback.
Please let me know what is the problem and how I can solve this.
Thank you.
Thank you very much for #philnash's help in solving this problem.👍
I solved the above issue and I can get the download link of the composition for now.
The problem was in the status callback function and I should use req.body instead of req.query because of the status callback method. (It's POST on my code.)
Here is the code that is fixed.
app.post('/api/getMeeting', (req, res) => {
if (req.body.StatusCallbackEvent === 'composition-available') {
const client = require('twilio')(config.twilio.apiKey, config.twilio.apiSecret, {accountSid: config.twilio.accountSid});
const compositionSid = req.body.CompositionSid;
const uri = "https://video.twilio.com/v1/Compositions/" + compositionSid + "/Media?Ttl=3600";
client.request({
method: "GET",
uri: uri,
}).then((response) => {
const requestUrl = response.body.redirect_to; // Getting the redirect link that user can download composition
sendRecordingEmail(requestUrl, userEmail); // Send URL via email to the user
res.status(200).send("success");
}).catch((error) => {
res.status(500).send("Error fetching /Media resource " + error);
});
} else {
res.status(204).send('compositioin is not available');
}
});

Javascript post request callback, redirect from .NET MVC controller

I'm integrating PayPal checkout with an e-com solution, where upon PayPal successfully creating PayPal order/payment, I carry out some server side processing which eventually returns a RedirectResult (with a URL for payment failed or success accordingly) from my controller, back to the client/frontend.
I have the following code below, and was expecting it to redirect automatically, but no redirect occurrs.
paypal.Buttons({
createOrder: function (data, actions) {
return actions.order.create({
intent: "CAPTURE",
purchase_units: [{
amount: {
value: '5.20',
}
}]
});
},
onApprove: function (data, actions) {
return actions.order.capture().then(function (details) {
return fetch('/umbraco/surface/PayPalPayment/process', {
method: 'post',
redirect: 'follow',
body: JSON.stringify({
OrderID: data.orderID,
PayerID: data.payerID,
}),
headers: {
'content-type': 'application/json'
}
});
}).catch(error=>console.log("Error capturing order!", error));
}
}).render('#paypal-button-container');
If I explicitly redirect with the code below, then the action carries out.
onApprove: function (data, actions) {
return actions.order.capture().then(function (details) {
return fetch('/umbraco/surface/PayPalPayment/process', {
method: 'post',
redirect: 'follow',
body: JSON.stringify({
OrderID: data.orderID,
PayerID: data.payerID,
}),
headers: {
'content-type': 'application/json'
}
}).then(function () { window.location.replace('https://www.google.co.uk') });
}).catch(function (error) {
console.log("Error capturing order!", error);
window.location.replace('https://www.bbc.co.uk');
});
}
Basically, I'm wondering why fetch redirect does not follow the Redirect that is returned form my controller. Controller redirect for full completeness:
return new RedirectResult("/checkout/thank-you") ;
Let me try to rephrase your question
You want to know why the browser did not redirect after you made a fetch - even though fetch api response
was a RedirectResult
The reason is simple, you made a request in fetch, which means you are making ajax request (hence browser will not change)
you set the redirect to follow, which means after the first request (i.e after get response from
/umbraco/surface/PayPalPayment/process), it will follow to the url /checkout/thank-you
so, what you get in the then() will be the response of /checkout/thank-you
so overall, it did follow the response but maybe not the way you expected (follow within the ajax request, not browser changing the page)
If what you want is a redirect to specific page, after the success call to /umbraco/surface/PayPalPayment/process
Then do:
Modify your backend to return JsonResult of the url instead of RedirectResult
return Json(new {redirectUrl = "/checkout/thank-you"});
use then to redirect
// other code omitted
.then(function (response) { return response.json(); })
.then(function (data) {window.location.replace(data.redirectUrl)});

Microsoft Graph sendMail doesn't work and returns NULL

I'm trying to send e-mails with MS Graph 1.0 and I have not any get any result or response. E-Mails haven't been sent and sendMail method don't return any error o message... it only says "null".
My code is based on this example https://github.com/microsoftgraph/msgraph-sdk-javascript#post-and-patch and looks like this:
// Initialize Graph client
const client = graph.Client.init({
authProvider: (done) => {
done(null, accessToken);
}
});
try {
// construct the email object
var mail = {
subject: "Microsoft Graph JavaScript Sample",
toRecipients: [{
emailAddress: {
address: "mail#domain.com"
}
}],
body: {
content: "<h1>MicrosoftGraph JavaScript Sample</h1>Check out https://github.com/microsoftgraph/msgraph-sdk-javascript",
contentType: "html"
}
};
client
.api('/me/sendMail')
.post({message: mail}, (err, res) => {
console.log("---> " + res);
});
console.log("Try ends");
} catch (err) {
parms.message = 'Error retrieving messages';
parms.error = { status: `${err.code}: ${err.message}` };
parms.debug = JSON.stringify(err.body, null, 2);
res.render('error', parms);
}
I guess mail var needs a header, but anyway, API should return me something, right? And, obviously, which is the problem with the email sending?
I finally added rawResponse to .post call and look at err log...
client
.api('/me/sendMail')
.header("Content-type", "application/json")
.post({message: mail}, (err, res, rawResponse) => {
console.log(rawResponse);
console.log(err);
});
... and I could see that I had problem with my authentication token. So, I was using the api correctly and code from the question is ok.

Posting an Asana task using fetch

I'm trying to work with the Asana API as I learn React and Redux. I've been able to get data from the Asana API using fetch() just fine so far, but I'm having trouble posting a task.
Here is the code I'm using:
const options = (type, data) => {
const defaultHeaders = {
'Authorization': `Bearer ${apiKey}`,
'Asana-Fast-Api': 'true',
}
switch(type) {
case 'get':
return {
headers: defaultHeaders,
}
case 'post':
const body = JSON.stringify(data)
console.log(body);
return {
method: 'POST',
headers: defaultHeaders,
contentType: 'application/json',
body: body,
}
default:
return {
headers: defaultHeaders,
}
}
};
const asanaUrl = (props) => {
const numOfProps = props.length;
switch (numOfProps) {
case 3:
return `https://app.asana.com/api/1.0/${props[0]}/${props[1]}?${props[2]}`
case 2:
return `https://app.asana.com/api/1.0/${props[0]}?${props[1]}`
case 1:
return `https://app.asana.com/api/1.0/${props[0]}`
default:
return console.log(props)
}
}
export const asanaPost = (props, data) => {
return fetch(asanaUrl(props), options('post', data))
.then(response => response.json() )
}
In the console, I see the return from the console.log which shows the JSON I'm sending into my body key:
{"assignee":22800770039251,"name":"test","notes":"test"}
and the following error
Failed to load resource: the server responded with a status of 400 (Bad Request)
The URL appears to be correct: https://app.asana.com/api/1.0/tasks?workspace=31542879721131
The error message is:
"Must specify exactly one of project, tag, or assignee + workspace"
It doesn't seem to matter what fields I include in the body (including a project resulted in the same error), which makes me suspect that something else is afoot and the Asana API isn't getting a hold of the body or isn't able to interpret it with how I've set things up.
Thanks for helping me out with this!
The api url I use is
https://app.asana.com/api/1.0/tasks?opt_fields=html_notes
I also pass projects as a key and a string value in the body.
I do not use 'Asana-Fast-Api': 'true' in the headers

Resources